Lineage
Record which columns feed which across your databases, discovered from the data, so you and your agents can say where a value comes from and what a change affects.
Why Use a Lineage
A number in a report usually passed through several tables before it got there: an operational table, a staged copy in the warehouse, a fact table that sums it. The schema does not say so. When someone asks "where does gross come from?" or "what breaks if I change customers.email?", the answer lives in pipeline code, or in someone's memory.
A lineage writes that knowledge down as mappings, each one step from a source column to a target column:
crm_db.customers.email -> warehouse_db.stg_customers.email
crm_db.customers.customer_id -> warehouse_db.orders.customer_id
warehouse_db.invoices.net, tax -> warehouse_db.invoice_facts.gross (Added: net + tax)
Squid proposes these mappings by reading your data, you save the ones that are right, and an agent with the lineage attached answers from them instead of guessing from column names.
Overview
A lineage is a named record of which columns feed which, across the database connectors attached to it. It holds mappings: the source column feeds the target column, either copied as it is or calculated from it.
You can add every mapping by hand, or let Squid discover them:
- Copies: columns of different tables that hold the same values.
- Calculated columns: a sum, a part of a date, a code translated to another, and other rules, checked record by record.
- Views and stored procedures: what their SQL states, read by a model. MySQL views, and stored procedures in Postgres and MySQL.
- Databricks: the column-to-column flows Unity Catalog recorded.
Discovery only proposes. A run saves nothing: you read its proposal, change what you want and save it. Every saved mapping reaches the agents the lineage is attached to.
When to use it
| Situation | Recommendation |
|---|---|
| Data is copied or loaded between tables or databases | ✅ Lineage |
| Users ask an agent where a value comes from or what a change affects | ✅ Lineage, attached to the agent |
| You want to check a load on one real record | ✅ Lineage, with record trace |
| An agent needs to know how to join tables | An ontology |
| Users ask about business terms ("active customer", "churn") | A glossary |
Quick Start
Prerequisites
- Two or more tables in one or more database connectors, each connector with a discovered schema. Discovery needs at least two tables it can read.
- The Squid backend SDK. Every lineage call requires your app's API key, so run it from backend code and expose it to your frontend through an executable.
The lineage API is available in the TypeScript and Python SDKs. The examples below use two connectors: crm_db, an operational database with a customers table, and warehouse_db, which holds stg_customers (a loaded copy) and orders.
Step 1: Create a lineage and start discovery
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
import { LineageDiscoveryRun } from '@squidcloud/client';
export class LineageService extends SquidService {
@executable()
async createCustomerLineage(): Promise<string> {
const lineages = this.squid.ai().lineage();
// Creating the lineage stores no mappings yet.
const lineage = await lineages.createLineage({
name: 'Customer data',
description: 'From the CRM to the warehouse.',
integrationIds: ['crm_db', 'warehouse_db'],
});
// Starts a background run that proposes mappings. It saves nothing.
await lineages.discover(lineage.id);
return lineage.id;
}
@executable()
async waitForDiscovery(lineageId: string): Promise<LineageDiscoveryRun | undefined> {
const lineages = this.squid.ai().lineage();
// Poll until the run leaves 'running'. It ends as 'completed' or 'failed'.
for (let attempt = 0; attempt < 60; attempt++) {
const lineage = await lineages.getLineage(lineageId);
const run = lineage?.lastDiscoveryRun;
if (run?.status !== 'running') return run;
await new Promise((resolve) => setTimeout(resolve, 2000));
}
// Still running after two minutes: return the running record, and poll again later.
return (await lineages.getLineage(lineageId))?.lastDiscoveryRun;
}
}
import asyncio
from squidcloud_backend import SquidService, executable
class LineageService(SquidService):
@executable()
async def create_customer_lineage(self) -> str:
lineages = self.squid.ai().lineage()
# Creating the lineage stores no mappings yet.
lineage = await lineages.create_lineage(
'Customer data',
description='From the CRM to the warehouse.',
integration_ids=['crm_db', 'warehouse_db'],
)
# Starts a background run that proposes mappings. It saves nothing.
await lineages.discover(lineage['id'])
return lineage['id']
@executable()
async def wait_for_discovery(self, lineage_id: str) -> dict | None:
lineages = self.squid.ai().lineage()
# Poll until the run leaves 'running'. It ends as 'completed' or 'failed'.
for _ in range(60):
lineage = await lineages.get_lineage(lineage_id)
run = (lineage or {}).get('lastDiscoveryRun')
if not run or run['status'] != 'running':
return run
await asyncio.sleep(2)
# Still running after two minutes: return the running record, and poll again later.
return ((await lineages.get_lineage(lineage_id)) or {}).get('lastDiscoveryRun')
A completed run reports what it did in lastDiscoveryRun: tablesProfiled, pairsMeasured, mappingsAdded (how many mappings it proposes to add), mappingsNotFound, and notes, which name everything the run left out or could not read. A failed run sets error.
Step 2: Save what discovery proposes
When lastDiscoveryRun.status is completed, read the proposal with getDiscoveryResult() and save it with saveContent(). Send the result's revision, and its startedAt as resultStartedAt, which tells the save that the content comes from that result. You can send the proposal back as it is, or leave out the mappings you do not want:
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
export class LineageSaveService extends SquidService {
@executable()
async saveDiscovery(lineageId: string): Promise<number> {
const lineages = this.squid.ai().lineage();
// The whole content the run proposes: the stored mappings with its changes.
const result = await lineages.getDiscoveryResult(lineageId);
if (!result) return 0;
// Send the proposal back as it is, with the revision it builds on and the run it comes from.
const { content } = await lineages.saveContent({
lineageId,
content: result.content,
revision: result.revision,
resultStartedAt: result.startedAt,
});
return content.mappings.length;
}
@executable()
async saveConfidentMappings(lineageId: string): Promise<number> {
const lineages = this.squid.ai().lineage();
const result = await lineages.getDiscoveryResult(lineageId);
if (!result) return 0;
// Leave out what you do not want, such as weakly backed mappings. A proposed mapping you leave out
// is remembered, so later runs do not propose it again.
const mappings = result.content.mappings.filter(({ confidence }) => confidence !== 'low');
const { content } = await lineages.saveContent({
lineageId,
content: { mappings },
revision: result.revision,
resultStartedAt: result.startedAt,
});
return content.mappings.length;
}
}
from squidcloud_backend import SquidService, executable
class LineageSaveService(SquidService):
@executable()
async def save_discovery(self, lineage_id: str) -> int:
lineages = self.squid.ai().lineage()
# The whole content the run proposes: the stored mappings with its changes.
result = await lineages.get_discovery_result(lineage_id)
if not result:
return 0
# Send the proposal back as it is, with the revision it builds on and the run it comes from.
saved = await lineages.save_content(
lineage_id,
result['content'],
result['revision'],
result_started_at=result['startedAt'],
)
return len(saved['content']['mappings'])
@executable()
async def save_confident_mappings(self, lineage_id: str) -> int:
lineages = self.squid.ai().lineage()
result = await lineages.get_discovery_result(lineage_id)
if not result:
return 0
# Leave out what you do not want, such as weakly backed mappings. A proposed mapping you leave out
# is remembered, so later runs do not propose it again.
mappings = [m for m in result['content']['mappings'] if m['confidence'] != 'low']
saved = await lineages.save_content(
lineage_id,
{'mappings': mappings},
result['revision'],
result_started_at=result['startedAt'],
)
return len(saved['content']['mappings'])
To drop the proposal instead, call discardDiscoveryResult().
Step 3: Connect it to an agent
Attach the lineage to an agent that is connected to the same databases. See Using a Lineage with an Agent.
Core Concepts
Lineages
A lineage has a name, an optional description and integrationIds: the database connectors discovery reads and mappings may name. updateLineage() changes only the fields you send, and listLineages() returns each lineage with its mappingCount.
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
import { Lineage } from '@squidcloud/client';
export class LineageAdminService extends SquidService {
@executable()
async listLineages(): Promise<Lineage[]> {
// Each lineage carries mappingCount and its lastDiscoveryRun.
return this.squid.ai().lineage().listLineages();
}
@executable()
async addBillingDatabase(lineageId: string): Promise<Lineage> {
// An omitted field keeps its value. integrationIds replaces the whole list.
return this.squid
.ai()
.lineage()
.updateLineage({
id: lineageId,
integrationIds: ['crm_db', 'warehouse_db', 'billing_db'],
});
}
@executable()
async deleteLineage(lineageId: string): Promise<void> {
// Deletes the lineage, its mappings and the result of its last run.
await this.squid.ai().lineage().deleteLineage(lineageId);
}
}
from squidcloud_backend import SquidService, executable
class LineageAdminService(SquidService):
@executable()
async def list_lineages(self) -> list[dict]:
# Each lineage carries mappingCount and its lastDiscoveryRun.
return await self.squid.ai().lineage().list_lineages()
@executable()
async def add_billing_database(self, lineage_id: str) -> dict:
# An omitted field keeps its value. integration_ids replaces the whole list.
return await self.squid.ai().lineage().update_lineage(
lineage_id,
integration_ids=['crm_db', 'warehouse_db', 'billing_db'],
)
@executable()
async def delete_lineage(self, lineage_id: str) -> None:
# Deletes the lineage, its mappings and the result of its last run.
await self.squid.ai().lineage().delete_lineage(lineage_id)
The attached databases cannot change while a discovery run is going. Mappings of a database you detach stay until you remove them.
Mappings
A mapping is one step of lineage. Its source and target each name an integrationId, a table and a column, as the schema spells them.
| Field | Meaning |
|---|---|
origin | discovered when a run found it, human when a person added it |
confidence | high, medium or low: how strongly the evidence backs it |
score | 0 to 100, from the evidence. Content is returned strongest first |
evidence | What backs it: the method, counts and plain-sentence signals. See Evidence and confidence |
direction | Which side is the source and why: a basis and its reasons |
transformation | Set when the target is calculated from the source, not copied. See Calculated columns |
sourceReason | Why this source was picked among the columns that hold the same values |
alternatives | Up to 5 other columns that hold the same values, strongest first, each with the reason it was not picked |
notFoundInLastRun | Set on a discovered mapping when the last run that read both of its tables did not find it again |
Saving and editing
Every saved mapping reaches agents; mappings have no review status. A discovery run never changes what is stored.
getContent(lineageId) returns the stored mappings with a revision. saveContent({ lineageId, content, revision }) makes the stored mappings exactly the ones you send, in one write. A save tells a mapping by its source and target only, so you can send back a mapping you read, or just its two columns:
- A pair the lineage holds is stored as it holds it, with its evidence.
- A pair it holds the other way round is reversed. Its direction becomes a person's.
- Any other pair is added as a person's mapping (
origin: 'human',evidence.method: 'manual'), without comparing values. - A stored mapping you leave out is deleted. When it was discovered, it is remembered, and later runs do not propose it again. Adding the pair by hand brings it back.
Saving a discovery result. A save takes part in a discovery result only when it names it: send the result's startedAt as resultStartedAt (result_started_at in Python), with the result's revision. The pairs of that result then count like the stored ones:
| The save | A new pair the result proposes, sent | A new pair the result proposes, left out |
|---|---|---|
Names the result with resultStartedAt | Stored as the result holds it: discovered, with its evidence | Remembered, so later runs do not propose it again |
| Names no result | Added as a person's mapping: human, manual, without the evidence of the run | Not remembered: the next run proposes it again |
A stored mapping you send is kept either way. Only a save that names the result also stores the evidence the run refreshed for it, and its notFoundInLastRun flag.
So pass resultStartedAt whenever the content you save was built from getDiscoveryResult(), edited or not, and leave it out when the content comes from getContent().
When the stored content changed after you read the revision, the save fails with LINEAGE_CONTENT_CHANGED. Read the content again and reapply your change:
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
export class LineageEditService extends SquidService {
@executable()
async dropMappingsIntoTable(lineageId: string, table: string): Promise<number> {
const lineages = this.squid.ai().lineage();
for (let attempt = 0; attempt < 3; attempt++) {
const { content, revision } = await lineages.getContent(lineageId);
// Keep every mapping except the ones into the given table.
const mappings = content.mappings.filter(({ target }) => target.table !== table);
try {
const saved = await lineages.saveContent({ lineageId, content: { mappings }, revision });
return saved.content.mappings.length;
} catch (error) {
// Someone saved the lineage after getContent(): read it again and retry.
const changed = error instanceof Error && error.message.includes('LINEAGE_CONTENT_CHANGED');
if (!changed) throw error;
}
}
throw new Error('The lineage kept changing. Try again later.');
}
@executable()
async fixEmailMapping(lineageId: string, emailMappingId: string): Promise<void> {
const lineages = this.squid.ai().lineage();
const { content, revision } = await lineages.getContent(lineageId);
const mappings = content.mappings.map((mapping) =>
// A stored pair sent the other way round is reversed.
mapping.id === emailMappingId ? { source: mapping.target, target: mapping.source } : mapping
);
await lineages.saveContent({
lineageId,
revision,
content: {
mappings: [
...mappings,
// A pair the lineage does not hold is added as a person's mapping.
{
source: { integrationId: 'crm_db', table: 'customers', column: 'full_name' },
target: { integrationId: 'warehouse_db', table: 'stg_customers', column: 'display_name' },
},
],
},
});
}
}
from squidcloud import SquidHttpError
from squidcloud_backend import SquidService, executable
class LineageEditService(SquidService):
@executable()
async def drop_mappings_into_table(self, lineage_id: str, table: str) -> int:
lineages = self.squid.ai().lineage()
for _ in range(3):
stored = await lineages.get_content(lineage_id)
# Keep every mapping except the ones into the given table.
mappings = [m for m in stored['content']['mappings'] if m['target']['table'] != table]
try:
saved = await lineages.save_content(lineage_id, {'mappings': mappings}, stored['revision'])
return len(saved['content']['mappings'])
except SquidHttpError as error:
# Someone saved the lineage after get_content(): read it again and retry.
if 'LINEAGE_CONTENT_CHANGED' not in str(error):
raise
raise RuntimeError('The lineage kept changing. Try again later.')
@executable()
async def fix_email_mapping(self, lineage_id: str, email_mapping_id: str) -> None:
lineages = self.squid.ai().lineage()
stored = await lineages.get_content(lineage_id)
mappings = [
# A stored pair sent the other way round is reversed.
{'source': m['target'], 'target': m['source']} if m['id'] == email_mapping_id else m
for m in stored['content']['mappings']
]
# A pair the lineage does not hold is added as a person's mapping.
mappings.append({
'source': {'integrationId': 'crm_db', 'table': 'customers', 'column': 'full_name'},
'target': {'integrationId': 'warehouse_db', 'table': 'stg_customers', 'column': 'display_name'},
})
await lineages.save_content(lineage_id, {'mappings': mappings}, stored['revision'])
A save checks the columns of every pair the lineage does not store yet: the database must be attached, and the table and column must be in the schema and not hidden. A calculated column cannot be sent the other way round.
Discarding a proposal
The result of a run is kept for a day, until a save of the content, discardDiscoveryResult() or the next run removes it. Its revision is that of the stored content it was built on. A save that names a result that is no longer the current one (a newer run started, it was discarded, it expired, or the content changed since the run) fails with LINEAGE_CONTENT_CHANGED: run discovery again.
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
export class LineageDiscardService extends SquidService {
@executable()
async discardDiscovery(lineageId: string): Promise<void> {
const lineages = this.squid.ai().lineage();
const result = await lineages.getDiscoveryResult(lineageId);
// Passing startedAt removes only the result you read, never a newer run's.
if (result) await lineages.discardDiscoveryResult(lineageId, result.startedAt);
}
}
from squidcloud_backend import SquidService, executable
class LineageDiscardService(SquidService):
@executable()
async def discard_discovery(self, lineage_id: str) -> None:
lineages = self.squid.ai().lineage()
result = await lineages.get_discovery_result(lineage_id)
# Passing started_at removes only the result you read, never a newer run's.
if result:
await lineages.discard_discovery_result(lineage_id, started_at=result['startedAt'])
One mapping at a time
Three calls change single mappings and save at once, without a revision:
createMapping()adds a mapping by hand. Squid compares the values of the two columns when it can read both databases, and stores the mapping whatever they show. Values that do not back it giveconfidence: 'low'andevidence.method: 'manual'.deleteMappings()deletes mappings by id. A discovered one is remembered, so runs do not propose it again.reverseDirection()reverses every copy between the two tables of a mapping that runs the same way. Later runs keep the direction. Calculated columns keep theirs.
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
import { LineageMapping } from '@squidcloud/client';
export class LineageMappingService extends SquidService {
@executable()
async addPhoneMapping(lineageId: string): Promise<LineageMapping> {
// Table and column names are matched to the schema's spelling.
return this.squid
.ai()
.lineage()
.createMapping({
lineageId,
source: { integrationId: 'crm_db', table: 'customers', column: 'phone' },
target: { integrationId: 'warehouse_db', table: 'stg_customers', column: 'phone_number' },
});
}
@executable()
async reverseTablePair(mappingId: string): Promise<LineageMapping[]> {
// Returns every mapping between the two tables that now runs the new way.
return this.squid.ai().lineage().reverseDirection({ mappingId });
}
@executable()
async removeMappings(lineageId: string, mappingIds: string[]): Promise<void> {
await this.squid.ai().lineage().deleteMappings(lineageId, mappingIds);
}
}
from squidcloud_backend import SquidService, executable
class LineageMappingService(SquidService):
@executable()
async def add_phone_mapping(self, lineage_id: str) -> dict:
# Table and column names are matched to the schema's spelling.
return await self.squid.ai().lineage().create_mapping(
lineage_id,
{'integrationId': 'crm_db', 'table': 'customers', 'column': 'phone'},
{'integrationId': 'warehouse_db', 'table': 'stg_customers', 'column': 'phone_number'},
)
@executable()
async def reverse_table_pair(self, mapping_id: str) -> list[dict]:
# Returns every mapping between the two tables that now runs the new way.
return await self.squid.ai().lineage().reverse_direction(mapping_id)
@executable()
async def remove_mappings(self, lineage_id: str, mapping_ids: list[str]) -> None:
await self.squid.ai().lineage().delete_mappings(lineage_id, mapping_ids)
What Discovery Finds
discover(lineageId) starts a background run and returns at once. The run reads only the tables and columns the schema of each attached connector shows; a hidden table or column is never read. Up to two runs go at once per application.
Copied columns
The run samples each table, pairs columns of different tables that share sampled values or have similar names, and then searches the source column for up to 50 sampled values of the target column. The share it finds decides the confidence.
- Direction comes from the tables. A load column such as
_loaded_at, layer words in table names (stg,dim,fact), a column named as a reference to its source, an operational database feeding an analytical one, and which side holds a key once each count. When nothing says,direction.basisisguessand you can reverse it. Stored mappings fix the direction between their two tables for later runs. - One source per target column. When several columns hold the same values, the run picks one, says why in
sourceReasonand lists the others inalternatives. A column that several sources each feed in part gets a mapping per source, up to three. - Values compare as the source database compares them.
00123and123do not match, and a date held as text in SQL does not match a MongoDB date. - Date columns need similar names. Shared dates alone are treated as coincidence.
- Long text is not paired. A value longer than 255 characters is treated as prose.
Calculated columns
Where two tables share a key, the run lines their records up through it and tests rules on them. A column it finds a rule for gets a transformation:
| Field | Meaning |
|---|---|
kind | The kind of calculation, see below |
label | A short name, such as Sum or Year |
expression | The calculation, in words that name its input columns, or as the SQL of a view or stored procedure writes it |
ruleId | Groups the mappings of one calculation: a column calculated from two inputs has two mappings that share the ruleId |
| Kind | What it covers |
|---|---|
reformat | The same value in another format, such as 10-0001-77 to 10000177 |
date_part | A part of a date, such as its year |
concat | Several columns joined into one |
arithmetic | A sum, a difference, a product or a rescale of columns |
aggregate | A sum, a count, a minimum or a maximum over several rows, such as invoice lines |
code_mapping | A code translated one to one, such as DE to DEU |
expression | Any other expression, read from a view or a stored procedure |
A rule is proposed when it holds on at least 90% of at least 10 records and gives more than one value. Its evidence.method is rule, with the share of records it holds on in matchedPercent. A code mapping is rated medium at most. A calculated column cannot be reversed.
The rule search is bounded: records are lined up only between tables that share a column that is unique on one side, with similar names, for at most 20 table pairs per run and 30 seconds in all. The run's notes say what it did not reach.
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
interface CalculatedColumn {
target: string;
label: string;
expression: string;
inputs: string[];
}
export class LineageCalculationService extends SquidService {
@executable()
async listCalculatedColumns(lineageId: string): Promise<CalculatedColumn[]> {
const { content } = await this.squid.ai().lineage().getContent(lineageId);
const byRule: Record<string, CalculatedColumn> = {};
for (const { source, target, transformation } of content.mappings) {
if (!transformation) continue; // A plain copy.
// One mapping per input column: the ruleId groups them into one calculation.
byRule[transformation.ruleId] ??= {
target: `${target.table}.${target.column}`,
label: transformation.label,
expression: transformation.expression,
inputs: [],
};
byRule[transformation.ruleId].inputs.push(`${source.table}.${source.column}`);
}
return Object.values(byRule);
}
}
from squidcloud_backend import SquidService, executable
class LineageCalculationService(SquidService):
@executable()
async def list_calculated_columns(self, lineage_id: str) -> list[dict]:
stored = await self.squid.ai().lineage().get_content(lineage_id)
by_rule: dict[str, dict] = {}
for mapping in stored['content']['mappings']:
transformation = mapping.get('transformation')
if not transformation:
continue # A plain copy.
source, target = mapping['source'], mapping['target']
# One mapping per input column: the ruleId groups them into one calculation.
column = by_rule.setdefault(transformation['ruleId'], {
'target': f"{target['table']}.{target['column']}",
'label': transformation['label'],
'expression': transformation['expression'],
'inputs': [],
})
column['inputs'].append(f"{source['table']}.{source['column']}")
return list(by_rule.values())
Views and stored procedures
For a Postgres or MySQL connector, the run reads the SQL of the views the schema shows as tables, and of the stored procedures whose SQL names one of the schema's tables, and proposes what they state: which columns each one writes, and from which columns. At most 12 views and 12 stored procedures per database are read.
A model reads the SQL. This is the only step of discovery that calls a model, once per database, and only when the database has such views or stored procedures.
- The model sees table names, column names and SQL, never rows. Quoted text is removed from the SQL first, see Privacy.
- An input the model names counts only when the SQL names that table and column. This guards against invented names. It does not prove the model read the SQL right, so these mappings stay proposals until you save them.
- Stated beats measured. A mapping a view or a stored procedure states replaces a measured one into the same column, and fixes the direction between its tables unless a person set it. Its
evidence.methodisdefinitionand itsdirection.basisisrecorded.
A Postgres schema in Squid does not list views as tables, so a view in Postgres gives no mappings. MySQL views are read.
Databricks recorded flows
For a Databricks connector, the run reads the column-to-column flows Unity Catalog recorded in the last 90 days, inside the catalog of the connection. Each flow between two columns the schema shows becomes a mapping with evidence.method: 'platform' and direction.basis: 'recorded'. Like a view, a recorded flow replaces a measured mapping into the same column.
Reading the flows needs SELECT on system.access.column_lineage for the connector's credentials. Without it the run still completes, and its notes say that the lineage Databricks records could not be read.
Evidence and confidence
evidence.method says how a mapping was backed:
| Method | Meaning |
|---|---|
value_lookup | Sampled target values were looked up in the source column |
sampled_values | The two samples were compared, without a lookup |
name_only | The mapping rests on the column names. Always low |
rule | A calculation was checked record by record |
definition | Read from the SQL of a view or a stored procedure |
platform | A flow the data platform recorded itself |
manual | A person added it, and its values were not compared or did not back it |
evidence.matchedPercent is the share of the compared values found on the other side, or of the records a rule holds on, and evidence.comparedValues is how many were compared. For a looked-up copy, high needs at least 95% of the values found and medium at least 70%. Short or common values, such as small numbers and status codes, turn up in unrelated columns, so they are rated lower unless the column names agree too. Evidence holds counts and names only, never a value read from a database.
direction.basis says what decided which side is the source:
| Basis | Meaning |
|---|---|
inferred | Read from the tables, with the observations in reasons |
guess | Nothing says which side is the source |
recorded | A view, a stored procedure or the data platform states it |
human | A person added the mapping or reversed it |
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
export class LineageReviewService extends SquidService {
@executable()
async listMappingsToCheck(lineageId: string): Promise<string[]> {
const result = await this.squid.ai().lineage().getDiscoveryResult(lineageId);
if (!result) return [];
const toCheck = result.content.mappings.filter(({ confidence, direction, notFoundInLastRun }) => {
// Worth a look: weak evidence, a guessed direction, or a stored mapping the run did not find again.
return confidence !== 'high' || direction.basis === 'guess' || notFoundInLastRun;
});
return toCheck.map(({ source, target, confidence, evidence, direction, notFoundInLastRun }) => {
const pair = `${source.table}.${source.column} -> ${target.table}.${target.column}`;
const backing = `${confidence}, ${evidence.method}, direction ${direction.basis}`;
return `${pair}: ${backing}${notFoundInLastRun ? ', not found in the last run' : ''}`;
});
}
}
from squidcloud_backend import SquidService, executable
class LineageReviewService(SquidService):
@executable()
async def list_mappings_to_check(self, lineage_id: str) -> list[str]:
result = await self.squid.ai().lineage().get_discovery_result(lineage_id)
if not result:
return []
lines = []
for mapping in result['content']['mappings']:
source, target = mapping['source'], mapping['target']
not_found = mapping.get('notFoundInLastRun', False)
# Worth a look: weak evidence, a guessed direction, or a stored mapping the run did not find again.
if mapping['confidence'] == 'high' and mapping['direction']['basis'] != 'guess' and not not_found:
continue
pair = f"{source['table']}.{source['column']} -> {target['table']}.{target['column']}"
backing = f"{mapping['confidence']}, {mapping['evidence']['method']}, direction {mapping['direction']['basis']}"
lines.append(f"{pair}: {backing}{', not found in the last run' if not_found else ''}")
return lines
Later runs
A later run starts from the stored mappings. Its proposal holds them with their evidence refreshed, and adds what it finds now.
- A stored discovered mapping the run no longer finds is flagged with
notFoundInLastRun, when the run read both of its tables. The run does not remove it: keep it or leave it out when you save. A mapping a person added is never flagged. - A discovered mapping you removed before is not proposed again.
- A direction a person set is kept.
Checking a Lineage Against Live Data
Two calls read your databases at the moment you call them. They return values and store nothing.
Measure a mapping
measureMapping(mappingId) looks sampled values of the target column up in the source column now. It returns matchedPercent, comparedValues, and up to 5 matchedSamples and 5 unmatchedSamples, each cut to 200 characters.
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
export class LineageMeasureService extends SquidService {
@executable()
async describeMapping(mappingId: string): Promise<string> {
const measured = await this.squid.ai().lineage().measureMapping(mappingId);
const missing = measured.unmatchedSamples.join(', ') || 'none';
return `${measured.matchedPercent}% of ${measured.comparedValues} values found. Not found: ${missing}`;
}
}
from squidcloud_backend import SquidService, executable
class LineageMeasureService(SquidService):
@executable()
async def describe_mapping(self, mapping_id: str) -> str:
measured = await self.squid.ai().lineage().measure_mapping(mapping_id)
missing = ', '.join(measured['unmatchedSamples']) or 'none'
return f"{measured['matchedPercent']}% of {measured['comparedValues']} values found. Not found: {missing}"
Trace a record
traceRecord() follows one record through the stored mappings. You name a column that identifies the record and the value it holds there. The trace reads the rows that hold the value, then the record's rows in the tables that feed that table or are fed by it, and checks every mapping between the reached tables on those rows.
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
import { TraceLineageRecordResponse } from '@squidcloud/client';
export class LineageTraceService extends SquidService {
@executable()
async traceCustomer(lineageId: string, customerId: string): Promise<TraceLineageRecordResponse> {
return this.squid
.ai()
.lineage()
.traceRecord({
lineageId,
// A column that identifies the record, and the value the record holds there.
field: { integrationId: 'crm_db', table: 'customers', column: 'customer_id' },
value: customerId,
});
}
@executable()
async listDisagreements(lineageId: string, customerId: string): Promise<string[]> {
const trace = await this.traceCustomer(lineageId, customerId);
// agrees is false when a copy's target holds a value its source does not, on this record.
const disagreeing = trace.checks.filter(({ agrees }) => agrees === false);
return disagreeing.map(({ mappingId, sourceValues, targetValues }) => {
return `${mappingId}: ${sourceValues.join(', ')} vs ${targetValues.join(', ')}`;
});
}
}
from squidcloud_backend import SquidService, executable
class LineageTraceService(SquidService):
@executable()
async def trace_customer(self, lineage_id: str, customer_id: str) -> dict:
return await self.squid.ai().lineage().trace_record(
lineage_id,
# A column that identifies the record, and the value the record holds there.
{'integrationId': 'crm_db', 'table': 'customers', 'column': 'customer_id'},
customer_id,
)
@executable()
async def list_disagreements(self, lineage_id: str, customer_id: str) -> list[str]:
trace = await self.trace_customer(lineage_id, customer_id)
# agrees is False when a copy's target holds a value its source does not, on this record.
return [
f"{check['mappingId']}: {', '.join(check['sourceValues'])} vs {', '.join(check['targetValues'])}"
for check in trace['checks']
if check.get('agrees') is False
]
The response holds:
tables: the table the trace started from (side: 'start'), then the tables it reached, nearest first, eachupstreamordownstream, with thecolumnsread, therowsfound (every value as text ornull), the link it wasfoundBy, andtruncatedwhen more rows hold the record than are returned.checks: one per mapping between two reached tables, with thesourceValuesandtargetValueson the record's rows. For a copy,agreessays whether every target value is among the source values.notes: what the trace could not read, and why it reached no other table when the start table's copies join no identifier columns.
What to know about a trace:
- It follows identifier columns only. A table is reached through a stored copy whose two columns are both named like identifiers:
id,key,code,no,nbr,numornumber, or a name that ends in one of those after_or in camel case, such ascustomer_id,order_noorinvoiceId. A table linked only by a name or an amount is not reached, and the trace'snotessay so when the start table has copies but none of them links it. - A copy agrees by sets. Rows are not paired one to one.
- A calculated column is shown and not judged. Its check has the input and output values and no
agrees. - A cut read is not judged either. When a table has more rows of the record than were read, a copy that seems to differ gets no
agrees. - It reads the columns the mappings name, not whole rows, and skips mappings of columns hidden since they were stored.
- Limits: 10 tables, 20 rows of each, 50 columns of a table, 200 mappings checked, and 5 values per column in a check.
Using a Lineage with an Agent
Attach a lineage to an agent with addLineage(), from backend code. Only your app's API key can attach or detach one:
import { SquidService, executable } from '@squidcloud/backend';
export class AgentLineageService extends SquidService {
@executable()
async connectLineage(lineageId: string): Promise<void> {
await this.squid.ai().agent('sales-copilot').addLineage(lineageId);
}
}
The agent is then told, in its instructions, which columns feed which, with the calculation when a column is calculated. It sees only the mappings between columns of the databases it is connected to. The lineage is guidance: it limits nothing the agent may query. For removeLineage(), the lineageIds option, what the agent receives and the errors, see Connect a Lineage.
The agent calls are available in the TypeScript SDK. You can also attach a lineage in the Squid Console, with the Your Lineages ability.
Privacy
- Nothing read from rows is stored. A mapping's evidence holds counts, names and sentences about them. A calculation's
expressionnames columns and holds no value. The valuesmeasureMapping()andtraceRecord()read are returned to the caller and not saved. - Hidden tables and columns are never read. Discovery,
measureMapping()andtraceRecord()read only what the schema of the connector shows. A column you hide after its mapping was stored is no longer read, andcreateMapping(), or a save of a pair the lineage does not store yet, fails withLINEAGE_COLUMN_NOT_FOUNDwhen it names a hidden column. - Quoted text is removed from SQL before a model sees it. Every single-quoted literal in the SQL of a view or a stored procedure is replaced, and in MySQL every double-quoted one too, so a value written into the SQL reaches neither the model nor a mapping. One exception: text inside Postgres dollar quotes (
$$ ... $$) is not removed, because a function body is dollar-quoted code. - The model is only used for views and stored procedures. Copies, calculated columns and Databricks flows are found with database reads alone.
Limits
| Limit | Value |
|---|---|
| Lineages per application | 100 |
| Database connectors per lineage | 10 |
| Mappings per lineage | 5,000 |
| Name, description | 100 and 2,000 characters |
| Removed mappings a lineage remembers | 5,000, newest kept |
| Discovery runs at once, per application | 2 |
| Tables per database, per run | 40 |
| Columns per table, and per run | 150 and 2,000 |
| Value lookups per run | 300 |
| Table pairs checked for calculated columns | 20 per run, within 30 seconds |
| Views and stored procedures read, per database | 12 of each |
| Databricks flows read, per database | 5,000, from the last 90 days |
| Time a discovery result is kept | One day |
| Lineages per agent | 10 |
A run that reaches a limit still completes. What the limit left out is listed in lastDiscoveryRun.notes.
Error Handling
Calls fail with an error whose message holds one of these codes:
| Error | Cause | Solution |
|---|---|---|
LINEAGE_NOT_FOUND | The lineage id does not exist | Use listLineages() to find the id |
LINEAGE_NAME_REQUIRED, LINEAGE_NAME_TOO_LONG, LINEAGE_DESCRIPTION_TOO_LONG | The name is empty, or the name or description is past its limit | Send a name of up to 100 characters and a description of up to 2,000 |
LINEAGE_NOT_A_DATABASE | An id in integrationIds is not a database connector of the application | Check the connector id in the Console |
LINEAGE_TOO_MANY_INTEGRATIONS, LINEAGE_LIMIT | More than 10 connectors on a lineage, or more than 100 lineages | Split the lineage, or delete one you no longer need |
LINEAGE_HAS_NO_DATABASES | discover() on a lineage with no attached database | Add connectors to integrationIds with updateLineage() |
LINEAGE_DISCOVERY_RUN_IN_PROGRESS | A run is already going, or you changed the databases while one runs | Wait until lastDiscoveryRun.status is no longer running |
LINEAGE_TOO_MANY_RUNS | Two runs of the application are already going | Wait for one to end |
LINEAGE_CONTENT_CHANGED (409) | The content was saved after you read its revision, or the result named by resultStartedAt is no longer the current one: a newer run started, or it was discarded, expired, or built on older content | Read the content again, or run discovery again, and reapply your changes |
LINEAGE_DATABASE_NOT_ATTACHED | A column names a database the lineage does not attach | Add the connector to integrationIds with updateLineage() |
LINEAGE_SCHEMA_NOT_FOUND | An attached database has no discovered schema | Discover the schema of the connector in the Console |
LINEAGE_TABLE_NOT_FOUND, LINEAGE_COLUMN_NOT_FOUND | A table or column is not in the schema, or is hidden | Check the names against the schema |
LINEAGE_MAPPING_EXISTS, LINEAGE_MAPPING_EXISTS_REVERSED | The lineage, or the content you save, already holds the pair, the same or the other way | Keep the existing mapping, or reverse it with reverseDirection() |
LINEAGE_MAPPING_SAME_COLUMN | Source and target are the same column | Name two different columns |
LINEAGE_MAPPING_IS_CALCULATED | You tried to reverse a calculated column | Delete the mapping instead if the calculation is wrong |
LINEAGE_MAPPING_NOT_FOUND | The mapping id does not exist | Read the ids again with getContent() |
LINEAGE_MAPPING_LIMIT | The lineage would hold more than 5,000 mappings | Remove mappings you do not need, or split the lineage |
INVALID_LINEAGE_FIELD, INVALID_VALUE | A column without its integrationId, table and column, or an empty value to trace | Send all three names, and a non-empty string or a number |
INVALID_LINEAGE_CONTENT, INVALID_REVISION, INVALID_STARTED_AT | A save without a mappings list or a revision, or a resultStartedAt or startedAt that is not a number | Send the content, revision and startedAt you read |
INVALID_IDS, LINEAGE_TOO_MANY_IDS | deleteMappings() with no ids, an id that is not a string, or more than 5,000 ids | Send between 1 and 5,000 mapping ids |
A discovery run that fails sets lastDiscoveryRun.status to failed and its error, and leaves no result:
| Run error | Cause | Solution |
|---|---|---|
LINEAGE_NOT_ENOUGH_TABLES | The run could read fewer than two tables | Read notes for the tables and databases it could not read |
LINEAGE_DISCOVERY_RUN_FAILED | The run failed for another reason | Run discovery again |
The run was interrupted | The run stopped before it ended, such as on a restart | Run discovery again |
A run that completes can still have left things out. Always read notes:
- TypeScript
- Python
import { SquidService, executable } from '@squidcloud/backend';
export class LineageRunService extends SquidService {
@executable()
async describeLastRun(lineageId: string): Promise<string[]> {
const lineage = await this.squid.ai().lineage().getLineage(lineageId);
const run = lineage?.lastDiscoveryRun;
if (!run) return ['No discovery run yet.'];
if (run.status === 'failed') return [`Failed: ${run.error}`, ...run.notes];
// Notes name unreadable databases and tables, and whatever a limit left out.
return [`${run.status}: ${run.mappingsAdded} new, ${run.mappingsNotFound} not found again`, ...run.notes];
}
}
from squidcloud_backend import SquidService, executable
class LineageRunService(SquidService):
@executable()
async def describe_last_run(self, lineage_id: str) -> list[str]:
lineage = await self.squid.ai().lineage().get_lineage(lineage_id)
run = (lineage or {}).get('lastDiscoveryRun')
if not run:
return ['No discovery run yet.']
if run['status'] == 'failed':
return [f"Failed: {run.get('error')}", *run['notes']]
# Notes name unreadable databases and tables, and whatever a limit left out.
summary = f"{run['status']}: {run['mappingsAdded']} new, {run['mappingsNotFound']} not found again"
return [summary, *run['notes']]
In Python, a failed call raises SquidHttpError. Its status_code is the HTTP status, such as 409 for LINEAGE_CONTENT_CHANGED, and the code is in its message.
Best Practices
- Check before you save. Read the proposal, look at
confidence,evidence.signalsanddirection.basis, and leave out what is wrong. Nothing a run proposes reaches your agents until you save it. - Name the result you save. Pass
resultStartedAtwhen you save a discovery result. Without it the proposed mappings are stored as hand-made ones, without their evidence, and the ones you left out come back on the next run. - Fix a guessed direction once. Reverse it with
reverseDirection(), and later runs keep it. - Remove wrong mappings instead of ignoring them. A discovered mapping you remove is not proposed again, so each run gets quieter.
- Keep the schema focused. A run reads up to 40 tables per database. Limit the tables a connector discovers to the ones the lineage should cover, and hide the columns it must not read.
- Trace a real record before you trust a load. Sampled counts show that values overlap. A trace shows one record end to end.
- Run discovery again after a pipeline change.
notFoundInLastRunpoints at the mappings the data no longer backs. - Read
notesafter every run. They are where a missing permission, an unreadable table or a reached limit shows up.