diff --git a/agent-skills/skills/hosts/databricks-genie/runtime.md b/agent-skills/skills/hosts/databricks-genie/runtime.md index 742919cb9..48fd24ee1 100644 --- a/agent-skills/skills/hosts/databricks-genie/runtime.md +++ b/agent-skills/skills/hosts/databricks-genie/runtime.md @@ -108,6 +108,37 @@ def run_sql(statement): --- +### 3.1 Required read-only diagnostics + +After defining `run_sql`, before `graph.snapshot()` or training, emit the checks specified in +`kumoai-reference/references/troubleshooting_signals.md` §0.1. Translate the reference's +Snowflake examples to Unity Catalog SQL executed with `run_sql`, on `WAREHOUSE_ID` and the same +`ws` identity as the connector; never use an active Snowpark session or Spark: + +- **Keys not probed in preflight:** count rows, non-null keys and distinct keys. Report empty + tables separately; stop on missing or repeated keys. For shared id-like scope columns, count + pairs via a grouped subquery and require both components non-null before reporting a scoped key. +- **Every confirmed link:** join to distinct parent keys; report matched of non-null child rows, + the share, unmatched rows, distinct unmatched values and nulls. Quote catalog/schema/table and + columns with `q`. Use `COALESCE(SUM(CASE WHEN ... THEN 1 ELSE 0 END), 0)` for conditional counts + and convert returned string counts to integers. Report incompatible key types before the + comparison; implicit SQL coercion is not evidence of a healthy link. For leading-zero + diagnostics use `CAST(... AS STRING)`, `LENGTH` and `LPAD`, with a length guard so a longer + child value can never be truncated into a padded match. +- **Unprobed event links:** count non-null and distinct foreign-key values. A unique link is an + observation for confirmation, not proof of an incorrect key. Retain it after recording the + user's specific confirmation; do not silently substitute another column. + +Print each link's counts and unmatched values' distinct count before asking the user to fix the +source, correct the link or explicitly accept its measured loss. Keep continuation approvals +per link, and preserve §0.1's default stops and confirmation requirements. When a query fails, +returns no usable counts, or lacks permission, name the unresolved check and raise before +snapshot/training; never report success or train on `coverage: not measured yet`. The notebook +contains executable adapted checks, not a request for the user to write SQL. All reads are +read-only evidence: no filtering, casting or padding changes the model input or confirmed graph. + +--- + ## 4. Destinations and read-back A confirmed destination `catalog.schema.table` is written through a connector on its own catalog diff --git a/agent-skills/skills/hosts/generic/runtime.md b/agent-skills/skills/hosts/generic/runtime.md index 398fee17c..e79126f53 100644 --- a/agent-skills/skills/hosts/generic/runtime.md +++ b/agent-skills/skills/hosts/generic/runtime.md @@ -194,6 +194,32 @@ destination. --- +### 2.2 Required read-only diagnostics + +After connecting and before `graph.snapshot()` or any training, generate the checks in +`kumoai-reference/references/troubleshooting_signals.md` §0.1: unprobed primary-key nulls and +uniqueness (including shared id-like scope columns), every link's coverage and leading-zero +comparison, and unprobed event-link repetition. Use the source's reader, never a Snowpark +session assumed to exist on this host: + +| Source | Reader and adaptation | +|---|---| +| Snowflake | `connector.session().sql(...).collect()` with Snowflake quoted identifiers. Use the §1/§2 reference examples and the connector's access context. | +| BigQuery | `bigquery.Client(project=PROJECT_ID, credentials=BQ_CREDENTIALS).query(sql).result()` with the dataset's own location. Quote all identifiers with `bq_name`. Use `COUNTIF`, `IF`, and `CAST(... AS STRING)` instead of Snowflake-only functions; count composite-key groups in a subquery and check both components for nulls. | +| Databricks | The statement API on the connector's confirmed SQL warehouse and the same identity (§2, §3). A cluster-only connector has no diagnostic SQL reader specified here: report the missing reader and stop; do not invent a warehouse. Use `q` for identifiers, `SUM(CASE WHEN ... THEN 1 ELSE 0 END)` with a zero default for conditional counts, and `CAST(... AS STRING)` for the diagnostic-only padding comparison. Statement results are strings: convert counts to integers, retaining null handling. | +| Files, S3, GCS | `pyarrow.dataset` on the confirmed source paths and formats, using the same filesystem credentials as the connector (§2, §3.1). Project only key and scope columns; do not sample these checks. Count nulls, distinct values and pairs, and test non-null child membership against distinct non-null parent keys. Compute diagnostic string padding separately with the length guard; never write or feed transformed arrays into Kumo. | + +Use source paths and table names confirmed at intake, not output locations. Report the counts +and choices defined by §0.1. A unique event link needs specific confirmation, not an automatic +rejection; unmatched rows need the user's decision even when most rows match. Record approved +continuations per link. If credentials, unsupported formats/types, resource limits or reader +errors prevent a required measurement, report it as unresolved and emit a raising guard before +snapshot/training. Never silently skip a check, invent zero counts, or train with coverage still +`not measured yet`. The emitted artifact must contain the adapted checks, not just a comment +asking the user to implement them. Diagnostics never change source data or graph choices. + +--- + ## 3. Destinations and read-back Build the output connector for the destination's own system, and the `PredictionOutputConfig` in diff --git a/agent-skills/skills/hosts/snowflake-coco/runtime.md b/agent-skills/skills/hosts/snowflake-coco/runtime.md index d8e316852..95c2bc84a 100644 --- a/agent-skills/skills/hosts/snowflake-coco/runtime.md +++ b/agent-skills/skills/hosts/snowflake-coco/runtime.md @@ -138,6 +138,54 @@ Snowflake destination before the session ends. Never describe a scratch path as plan a workflow that reads an artifact back in a later session without first confirming storage lifetime. +### 3.2 Link check — a read-only cell after graph validation + +The snapshot warns about a link only when **fewer than half** of its rows match +(`kumoai-reference/references/troubleshooting_signals.md` §1a), so a link that loses a few percent +of its rows passes silently. Every training notebook therefore carries this cell after building +and validating the confirmed graph, before `graph.snapshot()` or training: one line per confirmed +link, written verbatim from the proposal. `graph.validate()` must succeed before any coverage is +reported: it rejects incompatible key types (such as numeric `7` versus text `007`) while allowing +lossless integer widening. An implicit SQL conversion must never count as evidence of a healthy +link. Report any validation error with the key columns and types; do not cast them to proceed. +The cell prints diagnostic counts and raises if a comparison cannot run, before snapshot/training. +It never filters or writes, and nothing it reads reaches the graph. Use `connector.session()` so +the check sees the same rows as Kumo; never fall back to the active Snowpark session. + +```python +def q(name): + return '"' + name.replace('"', '""') + '"' + +graph.validate() # reject incompatible key types before SQL can coerce them into a match +LINKS = [('', '', '', '')] # every confirmed link, names as in the catalog +for child, fk, parent, pk in LINKS: + try: + r = connector.session().sql( + f'SELECT COUNT(*) AS N, COUNT(c.{q(fk)}) AS NON_NULL, ' + f'COALESCE(COUNT_IF(c.{q(fk)} IS NOT NULL AND p.K IS NULL), 0) AS UNMATCHED, ' + f'COUNT(DISTINCT IFF(p.K IS NULL, c.{q(fk)}, NULL)) AS UNMATCHED_VALUES ' + f'FROM {DATABASE}.{SCHEMA}.{q(child)} c LEFT JOIN ' + f'(SELECT DISTINCT {q(pk)} AS K FROM {DATABASE}.{SCHEMA}.{q(parent)}) p ' + f'ON c.{q(fk)} = p.K').collect()[0] + except Exception as err: # e.g. the two sides hold different types + raise RuntimeError( + f'LINK CHECK {child}.{fk} -> {parent}.{pk}: unresolved comparison: {err}' + ) from err + matched = r['NON_NULL'] - r['UNMATCHED'] + share = matched / r['NON_NULL'] if r['NON_NULL'] else 0.0 + print(f'LINK CHECK {child}.{fk} -> {parent}.{pk}: {matched} of {r["NON_NULL"]} non-null rows ' + f'matched ({share:.1%}); {r["UNMATCHED"]} unmatched rows, {r["UNMATCHED_VALUES"]} distinct ' + f'unmatched values; {r["N"] - r["NON_NULL"]} null') +``` + +**Read its output before anything else the run reports.** Every link's line goes into your reply +with its share. A link with any unmatched rows is a finding about the data, not a code problem: +lead the reply with the table, column, unmatched rows and distinct values, say the likely cause — +parent rows missing from the parent table, values that differ in format (`007` vs `7`), or a wrong +link when few or none match — and ask the user to choose: fix the source upstream, correct the +link, or continue knowing those rows get no edge. Stop there; a fix to an unrelated code error +waits for their answer. Never filter the rows, add parents, or cast either side in the notebook. + --- ## 4. What the Snowflake runtime provides @@ -192,7 +240,7 @@ Two further facts: the target destination must be writable by the identity's pri 3. `kumo.configure(scratch_dir=...)`, then the connector, in the §3 order: `from_spcs_env`, `from_connection_toml`, key pair from secrets. 4. Assert `connector.table_names()` (§3). -5. Tables → graph → `validate()` → predictive query → `snapshot()` → train → predict +5. Tables → graph → `validate()` → link check (§3.2) → predictive query → `snapshot()` → train → predict (portable core; `snapshot=` is required on `fit` and `predict`). 6. Write results to a durable Snowflake destination before the session ends (§3.1, §7). diff --git a/agent-skills/skills/kumo-data-science/SKILL.md b/agent-skills/skills/kumo-data-science/SKILL.md index 0668c6cf5..bc660712c 100644 --- a/agent-skills/skills/kumo-data-science/SKILL.md +++ b/agent-skills/skills/kumo-data-science/SKILL.md @@ -89,9 +89,9 @@ trainer, and `predict` runs against an explicitly rebuilt graph snapshot (see St - Choose the predictive problem, target, horizon, graph, or tuning for the user — refuse and name the minimum inputs needed - Join, clean, deduplicate, aggregate, create labels, or transform data **as model input**. - Diagnostic scalar aggregates during preflight — reported as proposal evidence, never written and - never fed to training — are not this; they exist so a key can be checked before it silently - discards rows + Diagnostic scalar aggregates during preflight or in a notebook's read-only check cell — reported + as evidence, never written and never fed to training — are not this; they exist so a key or a + link can be checked before it silently discards rows - Search for, rank, or curate tables by business relevance - Retry or resume jobs, or keep state across sessions. The one execution the agent performs is Step 3, and only when the user asks. @@ -178,16 +178,31 @@ preflight inside it. Present the graph proposal — seeds, tables, primary keys, time columns, links, `table_mode: all-connected [default]` — each line tagged `[supplied]` / `[declared]` / `[inferred]` / `[inferred, unverified]` / `[default]`. A semantic -view is resolved by `accept/semantic_view.md`, read only for a semantic view. If the user asked for embeddings, say they are included. **Stop and wait for confirmation.** +view is resolved by `accept/semantic_view.md`, read only for a semantic view. If the user asked for embeddings, say they are included. Every time column carries +its reason and the table's other timestamp columns; a table with several asks which one is the +event time (`accept/preflight.md` §4). **Stop and wait for confirmation.** User-supplied values take precedence over inferred ones. **Mandatory column-availability pass.** Before presenting the graph, decide the selected columns for every included table and add an `Excluded columns` section to the proposal. -- When a table's `time_column` marks the beginning of a row's validity or an interval, exclude any - candidate feature whose value is determined only after that time: the interval's eventual - endpoint, its realized duration, or a summary of the completed interval. At the row timestamp - those values are future information. Decide by semantic role, never by matching column names. +- When a table's `time_column` marks the beginning of a row's validity or an interval, the column + that marks when the row stops being valid is the table's **end time column**: declare it with + `end_time_column=`, never as a feature and never dropped (`accept/preflight.md` §4). Exclude any + other candidate feature whose value is determined only after that time: the interval's realized + duration, or a summary of the completed interval. At the row timestamp those values are future + information. Decide by semantic role, never by matching column names. +- For a query with a time window, flag every **current-state attribute**: a column on a + one-row-per-entity table that describes a state the entity can move in and out of (status, + plan, tier, stage, active or closed flag, current balance), when the table has no time column + recording when that value took effect and no end-time column. A creation or signup date does not + count: it dates the row, not the value. Such a column holds only today's value, so every past + anchor in training sees today's state — leakage when the state follows the outcome (a status + set by recent activity, for a churn or activity target). Fixed traits (birth year, signup + channel) are not flagged. List each under a `Flagged columns` section as + `. — current-state attribute, rows, no history [inferred]` and ask + whether its past values exist, for example as a history table with a time column. Flag only: + it stays selected unless the user chooses to leave it out or supplies the history. - Separate the target column from columns derived from it; both rules apply at once. - The target column itself **always stays** in the positional column list. The query references it by name, so dropping it fails with a missing column. @@ -207,6 +222,16 @@ Carry the confirmed exclusion set into code generation: a table with any exclusi with an explicit positional column list, because omitting it silently restores every source column. +**Column types.** `infer_metadata()` types each column from its name, its physical type and its +sampled values (`kumoai-reference/references/graph_construction.md` *How a semantic type is +inferred*), and those rules can contradict what a column means. Add a `Column types` section to +the proposal with one line for every selected non-key column a rule there matches: the type Kumo +will give it, the rule behind it, and the type its meaning calls for. Where the two differ, the +choice is the user's, at this gate; the notebook declares the confirmed type with +`with_column(...)`. A type confirmed here is a declaration, like a foreign key's `ID` — not a +change made to silence a data message (`kumoai-reference/references/troubleshooting_signals.md` +§1a). + **Assert what preflight could not find.** The proposal must state these explicitly rather than leaving them unmentioned, because each one changes whether the task is expressible: @@ -217,6 +242,8 @@ leaving them unmentioned, because each one changes whether the task is expressib conclude from a failed heuristic that the table must be an event or fact table. - a time-ranged target whose referenced table has no usable time column — say so, and say what would make the task expressible. A timestamp on another table does not repair the target. +- two links from one table to the same table — name the pair and ask which direction the user + wants (`accept/preflight.md` §6). Proposing both without comment is not a confirmation of both. | Condition | Transition | |---|---| @@ -235,7 +262,7 @@ generated before the task is confirmed: - Entity: one prediction per
. - Outcome: / - Window: <0 to N days after the prediction anchor> | static -- Task type: +- Task type: — - Output: predictions written to in the same notebook | notebook only, no predictions written - Scoring population (static tasks): rows whose is NULL | all rows, staged at - Threshold (binary classification, written or local): @@ -312,7 +339,9 @@ After ACCEPT, load `kumoai-reference/SKILL.md` and hand off the confirmed payloa describing the one line to add a destination later. That example is markdown text, never a code cell: a notebook with no confirmed destination contains no code that writes. Inside the markdown, show the code as text (a `text` fence), never as a `python` code block — - one that would run is a code cell that writes. + one that would run is a code cell that writes. A confirmed population table is not a + destination: staging it is the notebook's only write, and its name never implies an + output table. The predict call is part of the artifact, not a separate job the agent manages. The agent still executes nothing (Step 3 is opt-in). @@ -338,7 +367,8 @@ in the same or a later turn. Then, per `kumoai-reference/references/kumo_finetun - Report the outcome: the training metrics, or the exception and the cell that raised it - **Read what Kumo said about the data first.** A warning or error about the data — duplicate primary keys, a foreign key that matched few rows, invalid values read as null, a float or - mismatched key, an empty training table — leads the report, with the table, column and count, + mismatched key, an empty training table — or a link check line with unmatched rows + (`hosts//runtime.md`, where it has one) leads the report, with the table, column and count, and the decision goes to the user: fix the source, change the key or link, or accept the loss. A run that finished is not a success until they have decided. Never change the data, a column's type or the query to make such a message go away diff --git a/agent-skills/skills/kumo-data-science/accept/preflight.md b/agent-skills/skills/kumo-data-science/accept/preflight.md index abed8b5ba..8bf3a8727 100644 --- a/agent-skills/skills/kumo-data-science/accept/preflight.md +++ b/agent-skills/skills/kumo-data-science/accept/preflight.md @@ -139,11 +139,44 @@ agent does not deduplicate or filter. Until the user confirms it, the table is t keyless — usable as an edge source, but not as an edge destination and not as the `FOR EACH` entity. Confirmation is what lifts that restriction, not the existence of a candidate. +When a key repeats, test whether it is unique together with an **id-like** column that the table +shares with the tables linking to it — a tenant, organisation, account or region id; never a +time, amount or other measure, which can make any key look unique: +count the groups in `SELECT , FROM
GROUP BY , ` and compare with +`COUNT(*)`, also requiring zero nulls in either column. Use the active host's identifier quoting; +this grouped-subquery form works on BigQuery too. If one is, say the key is only unique within +`` and suggest a single combined key built upstream; Kumo keys are one column, and the agent never +builds one. If you cannot run the probe, do not ask the user to run it and do not take a go-ahead +as its result: the notebook runs it before `graph.snapshot()` and stops when the key repeats +(`kumoai-reference/references/troubleshooting_signals.md` §1). + ## 4. Time column per table The first `TIMESTAMP*`, `DATE`, or `DATETIME` column, preferring names ending in `_AT`, `_TS`, `_TIME`, `_DATE`, or named `EVENT_TIME` / `TIMESTAMP`. A table with none is static. +The time column decides which rows count as history and which fall into a target window, so the +pick is never silent. On **every** table's time-column line — even with a single candidate, and +even when the line came from a host-supplied preflight result — say why it was picked (the only +timestamp column; named as the row's creation or event time; the first candidate by type and +name) and list the table's **other** timestamp columns, or say there are none. When a table has +more than one, ask in the proposal which one marks when the row's fact happened or became known, +and say how to change it: name the column, and the notebook sets it as `time_column`. Names and +values cannot settle this; the user does. A column not chosen is still placed in time by §5. + +**An interval table declares its end column.** When a table's rows are valid over a period — its +time column is the start (`START_DATE`, `EFFECTIVE_START_TS`) and another date or timestamp column +marks when the row stops being valid (`END_DATE`, `EFFECTIVE_END_TS`) — name that column as the +table's **end time column**; do not drop it and do not leave it as an ordinary feature. Kumo keeps +an end time column out of the model's features, so it carries no future information, and the table +still records the period. Say so on the table's time-column line (`time column START_DATE, end +column END_DATE [inferred]`), and let the notebook set it (`end_time_column=`, +`kumoai-reference/references/graph_construction.md`). A column that is the table's only +timestamp, or that marks an event rather than the end of a validity period, is not an end time +column. An end time column is not listed under `Excluded columns`, and it does not change the +table's primary key: a keyless table with an end time column stays keyless unless the confirmed +graph names a key, and the notebook sets `primary_key=` only to the confirmed key. + For every time-ranged target aggregation, the table it references must have a usable `time_column`. If it does not, say so in the proposal and say what would make the task expressible: a timestamp on some other table does not repair the target. @@ -159,9 +192,10 @@ timestamps and must not be treated as one. For each table, place every candidate feature in time relative to that table's proposed `time_column`, then exclude the ones that are not yet knowable at it. -- When the time column marks the beginning of a validity period or interval, exclude a feature - whose value is only determined once that interval later changes or ends: its eventual endpoint, - its realized duration, or any summary of the completed interval. +- When the time column marks the beginning of a validity period or interval, the interval's end + column is declared as the end time column (§4), not excluded. Exclude a feature whose value is + only determined once that interval later changes or ends: its realized duration, or any summary + of the completed interval. - Exclude a feature computed from, or containing, the confirmed prediction target. - Apply the active host adapter's runtime column constraints. @@ -176,6 +210,48 @@ A link is proposed when a column in table A has the **same name** as the primary taken as well, where the source declares any. Nothing else is inferred — no fuzzy matching, no value overlap checks, no joins executed. +**Check event-link repetition; uniqueness alone is not an invalid link.** For every link whose +source is an event table (it has a time column and its rows are occurrences), probe the foreign +key with the §3 count. `N_DISTINCT = N_NON_NULL` means at most one event per parent through this +link, not that the link is wrong: `orders.shipment_id` can be unique while `orders.customer_id` +repeats. Report the counts and whether the link was inferred or supplied; ask whether the link +is intended or a different stable entity id is needed. Do not put it under `Not found` solely +for uniqueness. After the user explicitly confirms that non-repeating link, retain it and record +the confirmation. A one-to-one link between two entity tables needs no repetition probe. If the +probe cannot run here, the notebook runs it before the snapshot and pauses for confirmation of +an observed unique link (`kumoai-reference/references/troubleshooting_signals.md` §2). A generic +go-ahead is neither a probe result nor confirmation of an observation not yet reported. +Each link line names its basis: `declared`, `same name`, or `[supplied]` for a link the user +named. A column whose name only resembles another table's key — a prefix or suffix added, a +synonym, an abbreviation (`buyer_id` or `xuser_id` beside `user_id`, `sku` beside `product_id`) — +is never linked on that resemblance: list it under `Not found` as a possible link, say which key it +might reference, and let the user name it. Once named, it is `[supplied]`, and the user's +confirmation is the only basis it has. + +Value overlap never creates a link, but it is how every link is checked. For each link the graph +uses, report the share of its non-null values found in the parent key, so a wrong link stands out: +measured here when you can read rows (a scalar count, as for keys), otherwise by the notebook's link +check before training (`hosts//runtime.md`), and shown on the link line as `coverage: not +measured yet` until then. When it is measured, every link's share goes to the user; a low one means +the link, or the parent table, is wrong. + +**Two links from one table to the same table** — both ends of a connection, a follow, a referral, +a transfer — are a decision for the user, not two ordinary links. Kumo accepts both, but a query +that aggregates across that table to the shared parent fails query validation with +`Ambiguous link between tables` (the foreign key is not unique). Report the pair in the proposal, +under `Not found`, and ask which the user wants: +1. **One direction** — the graph gets a single `Edge` for the column they name. Removing the + extra `Edge` resolves the ambiguous path; it does not require removing the other column. + Keep that column when a confirmed query uses it. PQL confirmation follows this proposal, so + do not require a confirmed query here: retain the column pending that check and apply the + normal column-availability rules before code generation. +2. **Both, directed** — keep both links; fine as long as no query aggregates across that table to + the shared parent. +3. **Undirected** — the user writes each row twice upstream, the second copy with the two columns + swapped, and the graph keeps one link. + +Propose, never apply: the notebook does not copy, swap or drop rows. + ## 7. Seeds and table mode - **Seeds** are the tables behind `prediction_entity` and `prediction_target` (for link @@ -205,11 +281,14 @@ Table mode: all-connected [default] — 7 of 7 tables reachable from the seeds Metadata - customers: primary key CUSTOMER_ID [inferred] - fraud_events: primary key EVENT_ID [inferred] -- fraud_events: time column EVENT_AT [inferred] +- fraud_events: time column EVENT_AT [inferred] — named as the event time; other timestamp + columns: RESOLVED_AT. Which one marks when the event happened? Name another to use it instead +- customer_plans: time column VALID_FROM [inferred], end column VALID_TO [inferred] — a validity + period; VALID_TO is set as the end time column, not a feature - ... Links -- fraud_events.CUSTOMER_ID -> customers.CUSTOMER_ID [inferred] +- fraud_events.CUSTOMER_ID -> customers.CUSTOMER_ID [inferred] — same name; coverage: 99.6% of non-null values found - ... Excluded columns @@ -217,6 +296,10 @@ Excluded columns - fraud_events.DAYS_TO_RESOLVE [inferred] — duration of an interval that has not ended yet - ... +Column types +-
. [inferred] — Kumo: (); its meaning: — +- ... + Not found - payments: no primary key inferred [inferred] — treated as keyless; edge source only unless corrected - events: no usable time column [inferred] — a time-ranged target cannot reference this table @@ -225,14 +308,16 @@ Not found Confirm, or correct any line (your values take precedence). ``` -`Excluded columns` and `Not found` are local availability-gate extensions to the confirmation -format. +`Excluded columns`, `Column types` and `Not found` are local availability-gate extensions to the +confirmation format. `Column types` follows router Node 1c, *Column types*. ## 9. Never - Prepare, transform, aggregate or materialize **model inputs** — joining, cleaning, deduplicating, creating labels. A diagnostic scalar aggregate over source rows is permitted - solely as evidence for the proposal: row, distinct and null counts for a proposed or candidate key. Its + solely as evidence for the proposal: row, distinct and null counts for a proposed or candidate key, + distinct and null counts for an event link's foreign key, and the matched share of a proposed + link (§6). Its result is reported and then discarded; it is never written anywhere and never reaches training. - Rank tables by relevance or drop tables the user did not ask to drop. - Proceed to PQL before the proposal is confirmed. diff --git a/agent-skills/skills/kumo-model-persistence/references/reuse.md b/agent-skills/skills/kumo-model-persistence/references/reuse.md index 2ca79b960..7b02243c4 100644 --- a/agent-skills/skills/kumo-model-persistence/references/reuse.md +++ b/agent-skills/skills/kumo-model-persistence/references/reuse.md @@ -44,6 +44,12 @@ For an explicitly retained complete local bundle, use this alternative: loaded = kumo.Trainer.load(RETAINED_BUNDLE_DIRECTORY) ``` +`RETAINED_BUNDLE_DIRECTORY` is the directory that directly holds `training-spec.json`, as the +host's file listing shows it: for a copy laid out as `/model/training-spec.json` next to +`/metadata.json`, that is `/model`, not ``. A record kept beside the bundle +(its query, tables, columns, keys and edges) is read when the notebook is written, and the +notebook carries those values as literals, so the rebuilt graph can be reviewed before it runs. + Load only trusted publications. The loader checks bundle integrity and training metadata; hashes detect corruption, not publisher trust. Missing `training-spec.json`, incompatible spec versions or failed integrity checks are actionable restore errors. Retrieve the complete diff --git a/agent-skills/skills/kumoai-reference/references/graph_construction.md b/agent-skills/skills/kumoai-reference/references/graph_construction.md index 5995891ff..2758ab896 100644 --- a/agent-skills/skills/kumoai-reference/references/graph_construction.md +++ b/agent-skills/skills/kumoai-reference/references/graph_construction.md @@ -183,6 +183,43 @@ Rules: - Both `dtype` and `stype` must be resolved before a table is used in a `PredictiveQuery`; `infer_metadata()` resolves whatever is missing. +### How a semantic type is inferred + +For a column with no declared type, `infer_metadata()` reads, in order: its role (a primary key +is `ID`, a time column `timestamp`), its physical type (date, time, boolean and list types decide +on their own), its **name**, and then its **values**, in a sample of up to 10,000 rows. The first +that decides wins. The name and value rules below can contradict what a column means; the graph +gate reports each selected column they match (router Node 1c, *Column types*), and a confirmed +correction is declared with `with_column`. + +- **A name can make a column `ID`.** An integer or string column is typed `ID` by its name alone, + before any value is read, when the name ends in `id` (a few words such as `paid` or `fluid` + excepted) or contains `_id_`; has `code`, `key`, `hash`, `no`, `class`, `label`, `cate` or + `category` as an underscore-separated word at its start, middle or end (`discount_code`, + `dept_no`, `fraud_label`); or merely starts or ends with `key` or `code` (`keyword_count`, + `barcode`). Float columns are exempt. A measurement, a count or a class label with such a name + becomes an identifier: its values stop being magnitudes, and `SUM` or `AVG` over it fails the + query (`kumoai-reference/references/troubleshooting_signals.md` §3). Report it as + `Kumo: ID (named *_code)` beside the type its meaning calls for. A column that a `SUM` or `AVG` + target aggregates is declared `numerical` whenever its name matches — the request already says + it is a quantity — including a float column, which the rule exempts today but would not after + a change of physical type; say so at the gate. +- **Few distinct values make a number `categorical`.** Unless its name already decided it, a + column with at most 3 distinct sampled values is typed `categorical`, and so is an integer + column with at most 4,000 distinct values that are no more than 5% of the sampled rows. A name + containing `num`, `number`, `count`, `total`, `sum`, `avg`, `price`, `score`, `ratio` or + `value` as a prefix, a suffix or an underscore-separated word is typed `numerical` before the + values are read. A count without such a name — visits, items, contacts per row — usually lands + in `categorical`: as a `SUM` or `AVG` target the task stays regression but `pquery.validate()` + warns (`kumoai-reference/references/troubleshooting_signals.md` §3) and the column's history + is encoded as labels; as a static target (`PREDICT
.`) the task becomes + multiclass classification instead of regression. When the request asks for an amount, a total + or a number of something, report `Kumo: categorical (integer, few distinct values)` beside + `numerical`, declare `with_column('', stype=Stype.numerical)` in the notebook, and say on + the Node 1d *Task type* line that this is what makes the task regression. + +Source: shipped package (`kumo_core.stype_inference`, `kumo.engine.table`) + --- ## Step 4: build the graph @@ -245,10 +282,14 @@ Assigning time columns: - Do **not** designate an administrative last-modified timestamp unless it represents when the row became valid for modeling. - Tables without a meaningful timeline can legitimately have no time column. -- `end_time_column` exists as a `Table`/`from_source_table` parameter for rows with a validity - interval. - > Not verified: its exact semantics under this SDK. Do not describe or rely on its - > filtering behavior. +- Rows with a validity interval (the time column is the start, another column the end) declare + the end column with `end_time_column` on `Table.from_source_table(...)`, next to `time_column`: + `from_source_table(connector['T'], [...], time_column='START_DATE', end_time_column='END_DATE')`. Verified in the SDK source: the column is typed as a timestamp, it + must be among the table's `columns`, and it is left out of the model's feature columns + (`kumo_core.encoder_selection.feature_column_names`), so it does not leak. Sampling is + end-date-aware only on the entity table (after `FOR EACH`) and on the right-hand table of a link + prediction (`troubleshooting_signals.md`); say nothing more about its filtering. It needs no + primary key: a keyless event table keeps `primary_key=None` with an end time column set. Temporal splits: for a temporal predictive query, Kumo splits train/validation/holdout by the time column of the target table, and at prediction time accesses only data with timestamps at @@ -260,10 +301,10 @@ every selected feature in that row. If it marks the start of an interval, a fiel determined when that interval later changes or ends — its endpoint, its realized duration, or a summary of the completed interval — is future information and must not be used as a feature. -If such an interval endpoint is an ordinary candidate feature, omit it from the positional column -list. If it is configured as `end_time_column`, keep it selected as structural metadata and do not -present it as a feature; do not rely on its interval-filtering behaviour unless that behaviour has -been verified for the deployed bundle. +The interval's endpoint is configured as `end_time_column`: keep it selected as structural +metadata, never drop it and never present it as a feature. Its realized duration, or a summary of +the completed interval, is omitted from the positional column list. Do not rely on the endpoint's +interval-filtering behaviour beyond what is stated above. The same applies to the prediction target: keep the target column selected so the query and table metadata can reference it, and exclude only the companion columns derived from it. @@ -273,7 +314,8 @@ Leakage causes to screen for: - An event timestamp marks the start of a period while another column summarizes what happened by the end of that period. - A supposedly static entity column is overwritten over time, so the historical value is not - recoverable. + recoverable. Flagged at the graph gate (`kumo-data-science/SKILL.md` Node 1c, current-state + attributes); the user decides. - Training and holdout periods overlap or are ordered incorrectly. Fix the source timeline or drop the leaking field. Do not compensate with model tuning. @@ -399,8 +441,9 @@ Source: shipped package (`kumo.engine.table`, `kumo.engine.graph`, `kumoapi.grap Do not fill these from memory. If the task requires them, say so. -- `end_time_column` semantics under the Kumo Predict SDK (parameter exists; behavior only - documented for the separate KumoRFM product line, which is out of scope here). +- How `end_time_column` filters rows beyond the entity table and a link-prediction right-hand + table: declaring it is verified (it is a structural column, not a feature); any further + sampling behaviour is not. - Whether self-referencing edges (self-loops) are permitted. - Excluding the target label column from features at table-definition time: there is no known `features=` argument on `Table`. Control feature inclusion via `column_names` / `columns`. diff --git a/agent-skills/skills/kumoai-reference/references/kumo_finetuning_sdk.md b/agent-skills/skills/kumoai-reference/references/kumo_finetuning_sdk.md index bd74d0edc..39f893ef8 100644 --- a/agent-skills/skills/kumoai-reference/references/kumo_finetuning_sdk.md +++ b/agent-skills/skills/kumoai-reference/references/kumo_finetuning_sdk.md @@ -217,6 +217,11 @@ exact name, then its upper-cased form, so `connector['ENTITY_PROFILE']` never fi table names as `table_names()` returns them and column names as `.columns` returns them — in `primary_key=`, `time_column=`, column lists and filters. +**Set `primary_key=` only where the confirmed graph names a primary key.** A table the graph +lists as `no primary key` is built without `primary_key=`, even when it has a column that looks +like one (`status_event_id`) or an end time column; adding a key changes the graph the user +confirmed. + **Never exclude a column by a case-sensitive `!=` against a hand-typed literal.** A filter such as `c.name != 'END_DATE'` silently keeps a lower-case `end_date` — the comparison never matches, the column is never dropped, and nothing raises. Pass the confirmed `Excluded columns` from preflight @@ -342,6 +347,9 @@ Table.infer_metadata() only values. Correct every FK with `.with_column(col, stype=Stype.ID)`. - **A TEXT time column needs `dtype=Dtype.date`** declared, or staging will not cast it. - `infer_metadata()` takes no arguments. +- **An interval table sets `end_time_column`** to the column that marks when the row stops being + valid, keeps it in `column_names`, and never drops it + (`kumo-data-science/accept/preflight.md` §4, `graph_construction.md`). - Read-back attributes live under `.definition`: `.definition.pkey`, `.definition.time_col`, `.definition.end_time_col`. `.table_name` is on the table itself. @@ -394,13 +402,20 @@ Source: shipped package (`kumo.engine.graph`) ```python pquery = kumo.PredictiveQuery(graph=graph, query=QUERY) -pquery.validate() +response = pquery.validate() print('task type:', pquery.get_task_type()) +type_warnings = [w.message for w in response.warnings if w.title == 'Semantic Type Mismatch'] +if type_warnings: # e.g. a SUM over a column typed categorical: the user decides first + raise RuntimeError('Query validation warned about a semantic type; resolve before training:\n' + + '\n'.join(type_warnings)) ``` - The graph is bound at construction; parsing is lazy. - **Emit `validate()` with no arguments.** It raises on an invalid query; otherwise it returns a - `ValidationResponse` and logs its warnings. + `ValidationResponse` and logs its warnings. A warning titled `Semantic Type Mismatch` means a + column's inferred type does not fit what the query does with it (`troubleshooting_signals.md` + §3), so the notebook stops on one, after printing the task type, and the agent puts it to the + user. Other warnings are reported, not stopped on. - **Always emit `validate()` then `get_task_type()`** before training. The task type is never written in the query — it is inferred from the target's shape — so print it and confirm it matches intent. A query that validates can still be the wrong task. @@ -417,7 +432,22 @@ Source: shipped package (`kumo.engine.pquery.predictive_query`) Materialization is **explicit**. `fit` does not do it for you. ```python -snapshot = graph.snapshot() +import warnings + +# Kumo reports rows it dropped or could not link as warnings and keeps going +# (troubleshooting_signals.md §1a). Stop here, before any training, so the user decides first. +DATA_WARNINGS = ('duplicate primary-key', 'null or invalid primary key', + 'invalid values found', 'non-null rows') +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + snapshot = graph.snapshot() +for w in caught: + print(f'{w.category.__name__}: {w.message}') +data_problems = [str(w.message) for w in caught + if any(s in str(w.message) for s in DATA_WARNINGS)] +if data_problems and not DATA_LOSS_ACCEPTED: # config cell; False unless the user chose + raise RuntimeError('Kumo reported a problem in the data; stopped before training:\n' + + '\n'.join(data_problems)) training_table = pquery.generate_training_table(snapshot) prediction_table = pquery.generate_prediction_table( @@ -436,7 +466,13 @@ PredictiveQuery.generate_prediction_table(snapshot, *, prediction_time=None, pla - `snapshot` is **positional** on both. `prediction_time` and `plan` are keyword-only on `generate_prediction_table`. - `graph.snapshot()` reads every table through its connector and builds an on-disk DiskGraph index - under the scratch directory. An unchanged valid snapshot is reused on later runs. + under the scratch directory. An unchanged valid snapshot is reused on later runs, and its data + warnings are raised again. +- **The snapshot cell stops on a data warning.** Repeated or missing primary keys, unparseable + values and unmatched foreign keys are warnings, not errors: without the stop the notebook trains + on what is left. `DATA_LOSS_ACCEPTED = False` goes in the config cell; it becomes `True` only + after the user has seen the messages and chosen to continue with the loss, never on the agent's + own initiative. - `GraphSnapshot` exposes `.id`, `.index_path`, `.graph_config`. - `TrainingTable` exposes `.train_table_path` (ordinary parquet), `.manifest_path`, `.required_stages`, `.generation_plan`. @@ -501,6 +537,9 @@ prediction_table = kumo.PredictionTable.from_source_table( contain a target column. The SQL above stages only `ENTITY1`, which suffices for a static query on an entity without a timestamp; otherwise also select the anchor time as `TIMESTAMP`. - Rows the model trained on are scored too. Say so: those predictions are not out-of-sample. +- The population table is an input, not a destination. With no confirmed destination + (`notebook only`), the notebook stages the population and predicts with no `output_config`; + it defines no `OUTPUT_*` names and no output connector. Source: shipped package (`kumo_core.prediction.generate_prediction_table`, `kumo.engine.pquery.prediction_table.PredictionTable.from_source_table`) @@ -679,6 +718,7 @@ confirmed output destination (§12). ```python from datetime import datetime from pathlib import Path +import warnings import kumo.engine as kumo from kumo.engine import Edge @@ -688,6 +728,7 @@ from kumoapi.typing import Stype from snowflake.snowpark.context import get_active_session OUTPUT_DATABASE, OUTPUT_SCHEMA, OUTPUT_TABLE = '', '', '
' # confirmed destination +DATA_LOSS_ACCEPTED = False # True only after the user sees the warnings and accepts the loss session = get_active_session() # §3.3: only where the host provides the session @@ -729,12 +770,27 @@ pquery = kumo.PredictiveQuery( query=('PREDICT LIST_DISTINCT(transaction_events.location_id, 0, 30, days) ' 'RANK TOP 10 FOR EACH account_profile.account_id'), ) -pquery.validate() +response = pquery.validate() print('task type:', pquery.get_task_type()) +type_warnings = [w.message for w in response.warnings if w.title == 'Semantic Type Mismatch'] +if type_warnings: + raise RuntimeError('Query validation warned about a semantic type; resolve before training:\n' + + '\n'.join(type_warnings)) # 5. Materialize. PREDICTION_TIME is NAIVE — a tz-aware datetime raises ValueError. PREDICTION_TIME = datetime(2026, 8, 1) -snapshot = graph.snapshot() +DATA_WARNINGS = ('duplicate primary-key', 'null or invalid primary key', + 'invalid values found', 'non-null rows') +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + snapshot = graph.snapshot() +for w in caught: + print(f'{w.category.__name__}: {w.message}') +data_problems = [str(w.message) for w in caught + if any(s in str(w.message) for s in DATA_WARNINGS)] +if data_problems and not DATA_LOSS_ACCEPTED: + raise RuntimeError('Kumo reported a problem in the data; stopped before training:\n' + + '\n'.join(data_problems)) training_table = pquery.generate_training_table(snapshot) prediction_table = pquery.generate_prediction_table( snapshot, prediction_time=PREDICTION_TIME, # NAIVE datetime, inside the event history @@ -862,7 +918,16 @@ targets a superseded build and needs rewriting against §10 — do not copy its - [ ] `with_column(...)` results assigned or chained — it returns a new Table. - [ ] `Graph(tables=[...], edges=[Edge(...)])` — list form; `graph.validate()` emitted. - [ ] `pquery.validate()` and `get_task_type()` run before training, both called with no arguments. -- [ ] `graph.snapshot()` before generating any table. +- [ ] Every link out of an event table that preflight did not probe is probed before + `graph.snapshot()`. A non-repeating link is reported for explicit confirmation, not rejected + as invalid; continue after recording the user's confirmation (`troubleshooting_signals.md` §2). +- [ ] Every link's match rate probed before `graph.snapshot()`; the notebook stops when fewer + than half its rows match unless the user explicitly accepted that link's measured loss + (`troubleshooting_signals.md` §2). +- [ ] Every primary key preflight did not probe is probed before `graph.snapshot()`; the + notebook stops when it repeats (`troubleshooting_signals.md` §1). +- [ ] `graph.snapshot()` before generating any table, inside the §7 data-warning stop, with + `DATA_LOSS_ACCEPTED = False` in the config cell. - [ ] **`trainer.fit(training_table, snapshot=snapshot)`** — `snapshot=` present. - [ ] **`trainer.predict(prediction_table, snapshot=snapshot, ...)`** — `snapshot=` present. - [ ] `binary_classification_threshold` / `num_classes_to_return` on `predict`, never on diff --git a/agent-skills/skills/kumoai-reference/references/troubleshooting_signals.md b/agent-skills/skills/kumoai-reference/references/troubleshooting_signals.md index a57911a67..3b0e9bbad 100644 --- a/agent-skills/skills/kumoai-reference/references/troubleshooting_signals.md +++ b/agent-skills/skills/kumoai-reference/references/troubleshooting_signals.md @@ -5,7 +5,7 @@ Observable symptom → likely cause → fix. Ordered by when the agent hits them This file is the signal set as previously compiled. It is **not** re-verifiable against the published Kumo documentation, which is stale for this version of the local SDK and is not a source here — do not cite it, fetch it, or reconcile against it. > No verbatim Kumo exception text is established for this SDK. Entries below are keyed on the **observable condition**, not on a quoted message. **Do not fabricate Kumo error strings.** -> The five messages quoted in §1a are the exceptions: they are the SDK's own text, read from its source. +> The messages quoted in §1a and the semantic-type messages quoted in §3 are the exceptions: they are the SDK's own text, read from its source. **Who applies a fix.** A fix that changes the data — casting a column, deduplicating, flattening, filling or filtering values, combining columns into a key, normalising key types — is the user's @@ -41,6 +41,33 @@ Inspect a table through `.definition` (`.pkey`, `.time_col`, `.end_time_col`) an --- +### 0.1 Read-only diagnostics on the active host + +The SQL cells in §1 and §2 are **Snowflake examples**, not portable cells to copy unchanged. +Use the active `hosts//runtime.md` reader and identifier quoting. On Snowflake use +`connector.session()`, not an unrelated active session. On other sources translate the following +checks into that reader's SQL or Arrow operations, before `graph.snapshot()` and training. +Build and validate the confirmed graph before measuring link coverage so the SDK rejects +incompatible key types before a reader's implicit coercion can hide them; preserve allowed +lossless integer widening rather than imposing exact source-type equality: + +| Check | Required result and action | +|---|---| +| Primary keys not probed in preflight (§1) | Report total, non-null and distinct counts. Stop on missing or repeated keys; report an empty table separately. Test only shared id-like scope columns, requiring both columns non-null and one distinct pair per row, before suggesting a combined key upstream. | +| Every confirmed link (§2) | Report non-null child rows, matched rows and share, unmatched rows, distinct unmatched values and nulls. Use distinct parent keys so duplicate parent rows cannot multiply counts. Report key-type incompatibility before comparing; do not coerce it into a match. Present any unmatched rows for a user decision, even above 50% coverage. The low-coverage stop defaults on; only explicit acceptance of that link's measured loss permits continuation. | +| Leading-zero diagnosis (§2) | Compare string representations only in diagnostic results, never model inputs. Count hypothetical zero-padded matches only for child values no longer than the parent width; never truncate longer values into a match. Report the counts, without padding or casting the source supplied to the graph. | +| Unprobed event links (§2) | Report non-null and distinct foreign-key counts. If all non-null values are unique, ask whether that relationship is intended; retain it after recording specific confirmation, rather than rejecting it solely for uniqueness. | + +A failed, unavailable or unauthorized reader is **unresolved**, not zero coverage or a successful +check. Name the affected table/columns and reason, then raise before snapshot/training; never +silently skip it, switch identities, or treat `coverage: not measured yet` as measured. Do not +request the user to run an unspecified probe. Explain the missing access or reader support and +wait for it or a corrected confirmed graph. Successful diagnostics remain read-only evidence: +no transformed rows, joins or scalar results become model inputs, and no graph choices change +without the user's confirmation. + +--- + ## 1. Table definition ### Symptom: `connector.table("X")` raises `ValueError` @@ -74,8 +101,41 @@ Fully specify tables in production code to avoid unexpected re-inference. ### Symptom: row count silently drops after ingestion **Cause:** Duplicate primary key values — Kumo retains one row per key and drops the rest. **Fix:** Report how many rows the key repeats on (the preflight probe, or the snapshot warning in -§1a) and put the choice to the user: a different, genuinely unique key, or the source deduplicated -upstream. The agent does not deduplicate. +§1a, which stops the notebook before training) and put the choice to the user: a different, +genuinely unique key, or the source deduplicated upstream. The agent does not deduplicate. A key preflight could not probe — supplied, or confirmed +from an unverified candidate — is probed read-only before `graph.snapshot()`, and the notebook +stops when it repeats, after testing the id-like columns the table shares with its linking tables: +```python +def q(name): # a quoted Snowflake identifier + return '"' + name.replace('"', '""') + '"' + +KEYS = [('
', '', [''])] # keys preflight did not probe +for table, key, scopes in KEYS: + src = f'{DATABASE}.{SCHEMA}.{q(table)}' + n, n_distinct, n_non_null = connector.session().sql( + f'SELECT COUNT(*), COUNT(DISTINCT {q(key)}), COUNT({q(key)}) FROM {src}').collect()[0] + print(f'{table}.{key}: {n} rows, {n_distinct} distinct, {n_non_null} non-null') + if not n: + raise RuntimeError(f'{table}.{key}: table is empty; no key values could be checked.') + if n_distinct == n_non_null == n: + continue + unique_within = [] + for c in scopes: + pairs = connector.session().sql( + f'SELECT COUNT(*) FROM (SELECT {q(key)}, {q(c)} FROM {src} ' + f'GROUP BY {q(key)}, {q(c)}) pairs').collect()[0][0] + non_null = connector.session().sql( + f'SELECT COUNT(*) FROM {src} ' + f'WHERE {q(key)} IS NOT NULL AND {q(c)} IS NOT NULL').collect()[0][0] + if pairs == non_null == n: + unique_within.append(c) + raise RuntimeError(f'{table}.{key} is not unique ({n} rows, {n_distinct} distinct, ' + f'{n_non_null} non-null); unique together with: {unique_within or "none"}') +``` +When the key is unique together with one of those columns, the key is scoped to it (the same id +reused by different tenants or organisations), and linking on the key alone merges different +entities. Say so, and suggest a single combined key built in the source and used on both sides of +every link. Do not combine the columns in the notebook. Test only id-like columns. ### Symptom: a categorical column has very high cardinality **Cause:** Categorical supports up to **4,000 unique values by default**. @@ -98,13 +158,17 @@ change data, types or the query to make it go away (*Who applies a fix*, above). |---|---|---| | `Snapshot contains duplicate primary-key row(s) for
.` | `` rows share a key; Kumo keeps one per key and drops the rest | a different key, or the source deduplicated; or continue knowing `` rows are gone | | `Foreign key
. matched of non-null rows` | only `` of `` rows reach the parent; the rest get no edge | the link may be wrong (wrong column, or values differing in format, e.g. `007` vs `7`), or the parent rows are missing | +| `Snapshot dropped row(s) with a null or invalid primary key in
.` | `` rows have no usable key and are gone from the table | the source fixed upstream, or a different key; or continue knowing `` rows are gone | | ` invalid values found in
.` | `` values did not parse as the column's type and are read as null (see §5) | whether those rows are bad data, or the column's type is wrong | | `key
. has a floating-point dtype` | an ID column is stored as a float (often an integer key with nulls) | the column fixed upstream as an integer or string key | | `foreign key
. (dtype=…) cannot link to primary key
. (dtype=…)` | the two sides of a link hold different types | which side is right, fixed upstream; never cast one side in the notebook | -A float or mismatched key fails `graph.validate()` and stops the notebook. The other three are -warnings: the notebook keeps going and trains on what is left. Either way, the report the user -reads starts with the message, the table and column, and the count. +A float or mismatched key fails `graph.validate()` and stops the notebook. The other four are +warnings: Kumo keeps going and trains on what is left, so the notebook's snapshot cell turns them +into a stop before training (`kumo_finetuning_sdk.md` §7). Either way, the report the user reads +starts with the message, then, per table, how many rows were lost or left unlinked and why — +repeated key, missing key, or a value (a time, a number) that did not parse — and asks before +anything trains. --- @@ -121,14 +185,79 @@ print(table.has_primary_key()) ### Symptom: an edge is declared but the model learns nothing from it **Cause:** FK values do not actually match PK values. Rows with missing or unmatched key values are **silently ignored** when linkages are built, so a broken join looks like a sparse one. If the two -linked columns have different types, both are **cast to strings** — values equal as numbers may not -match as strings (`1.0` vs `1`). -**Fix:** There is **no `get_edge_stats()` in this SDK.** The snapshot reports the match rate -(§1a). Report it, and put a low one to the user before training: a wrong link to correct, or keys -to fix upstream so both sides hold the same values in the same type. Do not cast either side. +linked columns have incompatible types, `graph.validate()` rejects the graph before ingestion; +it permits matching types and lossless integer widening, not arbitrary numeric/text coercion. +**Fix:** There is **no `get_edge_stats()` in this SDK.** The snapshot warns about a low match +rate (§1a) but keeps going, so the notebook measures it itself, read-only, before +`graph.snapshot()`, for every link, and stops when fewer than half the rows match unless the +user has explicitly accepted that link's measured loss. It also counts +how many would match if the foreign key were padded with leading zeros to the primary key's +width — the signature of an id that was read as a number somewhere upstream (`007` became `7`): +```python +def q(name): # a quoted Snowflake identifier + return '"' + name.replace('"', '""') + '"' + +LINKS = [('', '', '', '')] # every confirmed link +ACCEPTED_UNMATCHED_LINKS = set() # (src, fk, dst, pk), only after the user accepts measured loss +for src, fk, dst, pk in LINKS: + n, matched, padded = connector.session().sql( + f'WITH p AS (SELECT DISTINCT TO_VARCHAR({q(pk)}) AS k FROM {DATABASE}.{SCHEMA}.{q(dst)}), ' + f'w AS (SELECT MAX(LENGTH(k)) AS w FROM p) ' + f'SELECT COUNT(f.{q(fk)}), COUNT(a.k), COUNT(b.k) ' + f'FROM {DATABASE}.{SCHEMA}.{q(src)} f CROSS JOIN w ' + f'LEFT JOIN p a ON a.k = TO_VARCHAR(f.{q(fk)}) ' + f'LEFT JOIN p b ON LENGTH(TO_VARCHAR(f.{q(fk)})) <= w.w ' + f'AND b.k = LPAD(TO_VARCHAR(f.{q(fk)}), w.w, \'0\')').collect()[0] + print(f'{src}.{fk} -> {dst}.{pk}: {matched} of {n} rows match; {padded} if zero-padded') + if n and matched < 0.5 * n and (src, fk, dst, pk) not in ACCEPTED_UNMATCHED_LINKS: + raise RuntimeError(f'{src}.{fk} matched {matched} of {n} rows to {dst}.{pk} ' + f'({padded} would match zero-padded to the key width).') +``` +The probe only diagnoses; it never feeds the graph. Report the counts and put the choice to the +user before training. Record only the particular link whose measured loss the user accepted in +`ACCEPTED_UNMATCHED_LINKS`; a generic go-ahead or confirmation of the link's identity is not +acceptance of unmatched rows. Other links still stop by default. When the zero-padded count is +high, say that the ids lost their leading zeros, that this cannot be recovered in the notebook, and that the fix is upstream: load or store +`
.` as text so the zeros survive. Otherwise the link is wrong, or the parent rows are +missing. Do not cast or pad either side in the notebook. +A link that loses fewer rows than that passes the snapshot silently. The host runtime's link +check cell, run after `graph.validate()` and before the snapshot, counts matched, unmatched and +null values for every link. Report each link's share, and put any unmatched rows to the user before +training: a wrong link to correct, parent rows missing upstream, or keys to fix upstream so both +sides hold the same values in the same type; or continue knowing those rows get no edge. Do not +cast either side, filter the rows or invent the missing parents. Set every foreign key to `Stype.ID`; left as numerical it is treated as a feature rather than a link. +### Symptom: an event table's foreign key never repeats +**Possible cause:** A per-event id was used instead of a stable entity id. But one event per +parent is valid too: `orders.shipment_id` can be unique while `orders.customer_id` repeats. +Uniqueness alone does not invalidate a link or prove that the table has no history. +**Fix:** Report the counts and ask the user to confirm the relationship. For event links not +already probed in preflight, run this read-only check before `graph.snapshot()`. Record explicit +confirmation of each observed non-repeating link in `CONFIRMED_UNIQUE_EVENT_LINKS`; leave the set +empty until the user has seen the counts and confirmed that link, not merely said go ahead. +```python +def q(name): # a quoted Snowflake identifier + return '"' + name.replace('"', '""') + '"' + +EVENT_LINKS = [('', '')] # every unprobed event link +CONFIRMED_UNIQUE_EVENT_LINKS = set() # (table, fkey), only after explicit confirmation +for table, fkey in EVENT_LINKS: + n, n_distinct = connector.session().sql( + f'SELECT COUNT({q(fkey)}), COUNT(DISTINCT {q(fkey)}) ' + f'FROM {DATABASE}.{SCHEMA}.{q(table)}').collect()[0] + print(f'{table}.{fkey}: {n} non-null rows, {n_distinct} distinct values') + if n and n_distinct == n: + print(f'WARNING: {table}.{fkey} never repeats; confirm whether this link is intended.') + if (table, fkey) not in CONFIRMED_UNIQUE_EVENT_LINKS: + raise RuntimeError(f'{table}.{fkey}: awaiting confirmation of the reported unique link.') +``` +Report the table, column, counts and whether the link was inferred or supplied. Let the user +confirm the link or name another stable id; after explicit confirmation, continue with the +retained link and its recorded confirmation. Never replace or drop it silently. A one-to-one +link between two entity tables is normal; do not probe it. + ### Symptom: the edge direction looks wrong / no neighbors are sampled **Cause:** `src_table` must be the table holding the **foreign key**; `dst_table` holds the matching **primary key**. Edges are bidirectional once declared, but the declaration itself is directional. **Fix:** @@ -181,6 +310,31 @@ pquery = kumo.PredictiveQuery( pquery.validate() ``` +### Symptom: `pquery.validate()` fails with `Ambiguous link between tables` +**Cause:** The query aggregates from one table to another that it reaches through two links — +two columns of one table pointing at the same parent. The validator cannot pick one. (The title is +the query validator's own text, from `kumopql`'s join validation.) +**Fix:** A graph change for the user to choose (`kumo-data-science/accept/preflight.md` §6): keep +one link, or have the rows written in both directions upstream and keep one link. Do not drop a +link or column, or copy or swap rows, in the notebook before the user has chosen. +### Symptom: the query fails with `Aggregation SUM is not intended to operate on foreign keys and ID-type columns.` +**Cause:** The column `SUM` or `AVG` aggregates is typed `ID`: it is a key, or `infer_metadata()` +typed it `ID` from its name (`graph_construction.md` *How a semantic type is inferred*). +Source: shipped package (`kumopql.validator.type_validator`). +**Fix:** Name the column, its type and why — "`orders.discount_code` is `ID` because it is named +`*_code`". A key is the wrong column to sum: aggregate a measurement, or `COUNT` the rows. A +measurement typed `ID` by its name is declared `.with_column('', stype=Stype.numerical)` — +a type declaration the user confirms at the graph gate (router Node 1c, *Column types*), never a +silent change. +### Symptom: `pquery.validate()` warns `Aggregation SUM is intended to operate on numerical columns, but
. has semantic type categorical.` +**Cause:** `infer_metadata()` typed the aggregated column from its few distinct values +(`graph_construction.md` *How a semantic type is inferred*), not from what it measures. The query +still validates and training would run. Source: shipped package (`kumopql.validator.type_validator`). +**Fix:** Stop before training and put it to the user: the column, the type Kumo gave it and why, +and the task type `get_task_type()` reports. A quantity is declared +`.with_column('', stype=Stype.numerical)` once the user confirms it (router Node 1c, +*Column types*). The same applies to every other warning `validate()` titles `Semantic Type Mismatch`. + ### Symptom: aggregation window rejected **Cause:** Both *start* and *end* must be **non-negative integers**, and *end* must be **greater than** *start*. **Fix:** Correct the bounds. Semantics: start is exclusive, end is inclusive. `SUM(TRANSACTIONS.PRICE, 10, 30)` from a `2020-01-01` anchor aggregates `2020-01-11 00:00:00 < t <= 2020-01-31 00:00:00`. @@ -206,7 +360,7 @@ print(training_table.data_df().head()) ### Symptom: an `END_DATE` column is set on a non-entity table and appears to be ignored **Cause:** End-date-aware sampling is currently supported **only** on the entity table (after `FOR EACH`) and on the RHS table in link prediction (after `LIST_DISTINCT`). -**Fix:** Do not rely on end dates elsewhere. +**Fix:** Do not rely on end dates elsewhere to filter rows. Declare the end column as `end_time_column` anyway (`graph_construction.md`): it stays out of the features, which is what keeps it from leaking; it does not change sampling on other tables. ### Symptom: date-only boundary includes one day too few / too many **Cause:** A date such as `2025-10-01` is interpreted at the **start** of that day. The target window is left-open, right-closed. diff --git a/agent-skills/tests/test_data_prep_review_examples.py b/agent-skills/tests/test_data_prep_review_examples.py new file mode 100644 index 000000000..f03a2eaf7 --- /dev/null +++ b/agent-skills/tests/test_data_prep_review_examples.py @@ -0,0 +1,225 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Execute documented guard cells with local readers; no SDK, cloud or GPU required.""" +import contextlib +import io +import re +import sqlite3 +import unittest +import warnings +from pathlib import Path +from types import SimpleNamespace + +SKILLS = Path(__file__).resolve().parents[1] / 'skills' +REFERENCE = SKILLS / 'kumoai-reference' / 'references' + + +def block(path, heading): + section = path.read_text().split(heading, 1)[1] + return re.search(r'```python\n(.*?)```', section, re.S)[1] + + +class CountIf: + def __init__(self): + self.count = 0 + + def step(self, value): + self.count += bool(value) + + def finalize(self): + # Snowflake COUNT_IF returns NULL when no rows match. + return self.count or None + + +class Session: + def __init__(self): + self.db = sqlite3.connect(':memory:') + self.db.row_factory = sqlite3.Row + self.db.create_aggregate('COUNT_IF', 1, CountIf) + self.db.create_function('IFF', 3, lambda cond, yes, no: yes if cond else no) + self.db.create_function('TO_VARCHAR', 1, lambda x: None if x is None else str(x)) + self.db.create_function('LPAD', 3, lambda s, w, c: None if s is None or w is None + else s.rjust(w, c)[:w]) + + def sql(self, query): + rows = self.db.execute(query.replace('DB.SC.', '')).fetchall() + return SimpleNamespace(collect=lambda: rows) + + def table(self, name, column, values): + self.db.execute(f'CREATE TABLE "{name}" ("{column}" TEXT)') + self.db.executemany(f'INSERT INTO "{name}" VALUES (?)', [(x,) for x in values]) + + +class DataPrepExamplesTest(unittest.TestCase): + def run_cell(self, code, **env): + output = io.StringIO() + if 'session' in env and 'connector' not in env: + env['connector'] = SimpleNamespace(session=lambda: env['session']) + env.setdefault('graph', SimpleNamespace(validate=lambda: None)) + with contextlib.redirect_stdout(output): + exec(compile(code, '', 'exec'), env) + return output.getvalue() + + def link_cell(self): + return block(SKILLS / 'hosts/snowflake-coco/runtime.md', '### 3.2 Link check') + + def link_env(self, child, parent): + reader = Session() + reader.table('', '', child) + reader.table('', '', parent) + return dict(connector=SimpleNamespace(session=lambda: reader), DATABASE='DB', SCHEMA='SC') + + def test_fully_matched_link_uses_connector_session(self): + # No active `session` is provided: using it would fail. + out = self.run_cell(self.link_cell(), **self.link_env(['a', 'b'], ['a', 'b'])) + self.assertIn('2 of 2 non-null rows matched (100.0%)', out) + self.assertIn('0 unmatched rows', out) + + def test_empty_child_reports_zero_counts(self): + out = self.run_cell(self.link_cell(), **self.link_env([], ['a'])) + self.assertIn('0 of 0 non-null rows matched', out) + self.assertIn('0 unmatched rows', out) + + def test_partial_link_reports_unmatched_and_null(self): + out = self.run_cell(self.link_cell(), **self.link_env(['a', 'x', None], ['a'])) + self.assertIn('1 of 2 non-null rows matched (50.0%)', out) + self.assertIn('1 unmatched rows, 1 distinct unmatched values; 1 null', out) + + def test_failed_comparison_preserves_cause_and_names(self): + error = ValueError('incompatible columns') + + def sql(_): + raise error + + connector = SimpleNamespace(session=lambda: SimpleNamespace(sql=sql)) + with self.assertRaisesRegex(RuntimeError, '. -> .') as caught: + self.run_cell(self.link_cell(), connector=connector, DATABASE='DB', SCHEMA='SC') + self.assertIs(caught.exception.__cause__, error) + + def test_incompatible_graph_stops_before_querying_coverage(self): + def invalid_graph(): + raise ValueError('foreign key child.fk cannot link to primary key parent.pk') + + def forbidden_session(): + self.fail('coverage queried before graph validation succeeded') + + with self.assertRaisesRegex(ValueError, 'cannot link'): + self.run_cell(self.link_cell(), graph=SimpleNamespace(validate=invalid_graph), + connector=SimpleNamespace(session=forbidden_session), + DATABASE='DB', SCHEMA='SC') + + def test_connector_session_failure_does_not_fall_back(self): + def unavailable(): + raise ValueError('unavailable') + + with self.assertRaisesRegex(RuntimeError, 'unresolved comparison'): + self.run_cell(self.link_cell(), connector=SimpleNamespace(session=unavailable), + session=Session(), DATABASE='DB', SCHEMA='SC') + + def snapshot_cell(self): + example = block(REFERENCE / 'kumo_finetuning_sdk.md', '## 10. Complete verified example') + return 'DATA_WARNINGS =' + example.split('DATA_WARNINGS =', 1)[1].split('training_table =', 1)[0] + + def test_snapshot_guards_clean_warning_and_accepted_paths(self): + for message, accepted in [(None, False), ('unrelated warning', False), + ('Snapshot contains 2 duplicate primary-key row(s)', True)]: + with self.subTest(message=message, accepted=accepted): + def snapshot(): + if message: + warnings.warn(message) + return object() + out = self.run_cell(self.snapshot_cell(), warnings=warnings, + graph=SimpleNamespace(snapshot=snapshot), + DATA_LOSS_ACCEPTED=accepted) + if message: + self.assertIn(message, out) + + def test_snapshot_stops_on_each_data_warning(self): + for message in ['duplicate primary-key', 'null or invalid primary key', + 'invalid values found', 'non-null rows']: + with self.subTest(message=message): + def snapshot(): + warnings.warn(message) + with self.assertRaisesRegex(RuntimeError, 'stopped before training'): + self.run_cell(self.snapshot_cell(), warnings=warnings, + graph=SimpleNamespace(snapshot=snapshot), DATA_LOSS_ACCEPTED=False) + + def test_complete_example_semantic_warning_stops_before_materialization(self): + example = block(REFERENCE / 'kumo_finetuning_sdk.md', '## 10. Complete verified example') + cell = 'response = ' + example.split('response = ', 1)[1].split('# 5.', 1)[0] + for title in ['Semantic Type Mismatch', 'Other warning', None]: + with self.subTest(title=title): + response = SimpleNamespace(warnings=[] if title is None else [ + SimpleNamespace(title=title, message='review the type')]) + query = SimpleNamespace(validate=lambda: response, get_task_type=lambda: 'regression') + if title == 'Semantic Type Mismatch': + with self.assertRaisesRegex(RuntimeError, 'review the type'): + self.run_cell(cell, pquery=query) + else: + self.run_cell(cell, pquery=query) + + def test_padding_cannot_truncate_a_longer_key_into_a_match(self): + code = block(REFERENCE / 'troubleshooting_signals.md', + '### Symptom: an edge is declared but the model learns nothing from it') + reader = Session() + reader.table('', '', ['10075', '7', '007']) + reader.table('', '', ['100', '007']) + # 1/3 exact matches triggers the existing default stop; inspect the padding count there. + with self.assertRaisesRegex(RuntimeError, '2 would match zero-padded'): + self.run_cell(code, session=reader, DATABASE='DB', SCHEMA='SC') + + def test_approved_low_coverage_link_can_continue(self): + code = block(REFERENCE / 'troubleshooting_signals.md', + '### Symptom: an edge is declared but the model learns nothing from it') + reader = Session() + reader.table('', '', ['a', 'x', 'y']) + reader.table('', '', ['a']) + code = code.replace('ACCEPTED_UNMATCHED_LINKS = set()', + "ACCEPTED_UNMATCHED_LINKS = {('', '', '', '')}") + self.assertIn('1 of 3 rows match', self.run_cell( + code, session=reader, DATABASE='DB', SCHEMA='SC')) + + def test_composite_key_probe_excludes_null_components(self): + code = block(REFERENCE / 'troubleshooting_signals.md', + '### Symptom: row count silently drops after ingestion') + for scope, expected in [('tenant-b', "['']"), (None, 'none')]: + with self.subTest(scope=scope): + reader = Session() + reader.db.execute('CREATE TABLE "
" ("" TEXT, "" TEXT)') + reader.db.executemany('INSERT INTO "
" VALUES (?, ?)', + [('a', 'tenant-a'), ('a', scope)]) + with self.assertRaises(RuntimeError) as caught: + self.run_cell(code, session=reader, DATABASE='DB', SCHEMA='SC') + self.assertIn('unique together with: ' + expected, str(caught.exception)) + + def test_empty_key_is_not_reported_as_duplicate(self): + code = block(REFERENCE / 'troubleshooting_signals.md', + '### Symptom: row count silently drops after ingestion') + reader = Session() + reader.table('
', '', []) + with self.assertRaisesRegex(RuntimeError, 'table is empty'): + self.run_cell(code, session=reader, DATABASE='DB', SCHEMA='SC') + + def test_unique_event_link_requires_then_accepts_specific_confirmation(self): + code = block(REFERENCE / 'troubleshooting_signals.md', + "### Symptom: an event table's foreign key never repeats") + reader = Session() + reader.table('', '', ['a', 'b']) + with self.assertRaisesRegex(RuntimeError, 'awaiting confirmation'): + self.run_cell(code, session=reader, DATABASE='DB', SCHEMA='SC') + confirmed = code.replace('CONFIRMED_UNIQUE_EVENT_LINKS = set()', + "CONFIRMED_UNIQUE_EVENT_LINKS = {('', '')}") + self.assertIn('2 non-null rows, 2 distinct', self.run_cell( + confirmed, session=reader, DATABASE='DB', SCHEMA='SC')) + + def test_repeating_event_link_does_not_require_unique_link_confirmation(self): + code = block(REFERENCE / 'troubleshooting_signals.md', + "### Symptom: an event table's foreign key never repeats") + reader = Session() + reader.table('', '', ['a', 'a']) + self.assertNotIn('WARNING', self.run_cell(code, session=reader, DATABASE='DB', SCHEMA='SC')) + + +if __name__ == '__main__': + unittest.main() diff --git a/skills/kumo-data-science/SKILL.md b/skills/kumo-data-science/SKILL.md index 6aae6b86b..8cf36a79f 100644 --- a/skills/kumo-data-science/SKILL.md +++ b/skills/kumo-data-science/SKILL.md @@ -7,7 +7,7 @@ description: "Use for KumoAI graphs and predictive models on relational data in ## Build marker -**`SKILL-BUILD: 2026-11-19-bef5ab4e-dirty`** +**`SKILL-BUILD: 2026-12-01-776d904f-dirty`** Quote this string verbatim whenever asked which build of the skill is loaded. If you cannot read it from this file, you have not loaded the skill — say so rather than guessing. @@ -89,9 +89,9 @@ trainer, and `predict` runs against an explicitly rebuilt graph snapshot (see St - Choose the predictive problem, target, horizon, graph, or tuning for the user — refuse and name the minimum inputs needed - Join, clean, deduplicate, aggregate, create labels, or transform data **as model input**. - Diagnostic scalar aggregates during preflight — reported as proposal evidence, never written and - never fed to training — are not this; they exist so a key can be checked before it silently - discards rows + Diagnostic scalar aggregates during preflight or in a notebook's read-only check cell — reported + as evidence, never written and never fed to training — are not this; they exist so a key or a + link can be checked before it silently discards rows - Search for, rank, or curate tables by business relevance - Retry or resume jobs, or keep state across sessions. The one execution the agent performs is Step 3, and only when the user asks. @@ -178,16 +178,31 @@ preflight inside it. Present the graph proposal — seeds, tables, primary keys, time columns, links, `table_mode: all-connected [default]` — each line tagged `[supplied]` / `[declared]` / `[inferred]` / `[inferred, unverified]` / `[default]`. A semantic -view is resolved by `accept/semantic_view.md`, read only for a semantic view. If the user asked for embeddings, say they are included. **Stop and wait for confirmation.** +view is resolved by `accept/semantic_view.md`, read only for a semantic view. If the user asked for embeddings, say they are included. Every time column carries +its reason and the table's other timestamp columns; a table with several asks which one is the +event time (`accept/preflight.md` §4). **Stop and wait for confirmation.** User-supplied values take precedence over inferred ones. **Mandatory column-availability pass.** Before presenting the graph, decide the selected columns for every included table and add an `Excluded columns` section to the proposal. -- When a table's `time_column` marks the beginning of a row's validity or an interval, exclude any - candidate feature whose value is determined only after that time: the interval's eventual - endpoint, its realized duration, or a summary of the completed interval. At the row timestamp - those values are future information. Decide by semantic role, never by matching column names. +- When a table's `time_column` marks the beginning of a row's validity or an interval, the column + that marks when the row stops being valid is the table's **end time column**: declare it with + `end_time_column=`, never as a feature and never dropped (`accept/preflight.md` §4). Exclude any + other candidate feature whose value is determined only after that time: the interval's realized + duration, or a summary of the completed interval. At the row timestamp those values are future + information. Decide by semantic role, never by matching column names. +- For a query with a time window, flag every **current-state attribute**: a column on a + one-row-per-entity table that describes a state the entity can move in and out of (status, + plan, tier, stage, active or closed flag, current balance), when the table has no time column + recording when that value took effect and no end-time column. A creation or signup date does not + count: it dates the row, not the value. Such a column holds only today's value, so every past + anchor in training sees today's state — leakage when the state follows the outcome (a status + set by recent activity, for a churn or activity target). Fixed traits (birth year, signup + channel) are not flagged. List each under a `Flagged columns` section as + `
. — current-state attribute, rows, no history [inferred]` and ask + whether its past values exist, for example as a history table with a time column. Flag only: + it stays selected unless the user chooses to leave it out or supplies the history. - Separate the target column from columns derived from it; both rules apply at once. - The target column itself **always stays** in the positional column list. The query references it by name, so dropping it fails with a missing column. @@ -207,6 +222,16 @@ Carry the confirmed exclusion set into code generation: a table with any exclusi with an explicit positional column list, because omitting it silently restores every source column. +**Column types.** `infer_metadata()` types each column from its name, its physical type and its +sampled values (`kumoai-reference/references/graph_construction.md` *How a semantic type is +inferred*), and those rules can contradict what a column means. Add a `Column types` section to +the proposal with one line for every selected non-key column a rule there matches: the type Kumo +will give it, the rule behind it, and the type its meaning calls for. Where the two differ, the +choice is the user's, at this gate; the notebook declares the confirmed type with +`with_column(...)`. A type confirmed here is a declaration, like a foreign key's `ID` — not a +change made to silence a data message (`kumoai-reference/references/troubleshooting_signals.md` +§1a). + **Assert what preflight could not find.** The proposal must state these explicitly rather than leaving them unmentioned, because each one changes whether the task is expressible: @@ -217,6 +242,8 @@ leaving them unmentioned, because each one changes whether the task is expressib conclude from a failed heuristic that the table must be an event or fact table. - a time-ranged target whose referenced table has no usable time column — say so, and say what would make the task expressible. A timestamp on another table does not repair the target. +- two links from one table to the same table — name the pair and ask which direction the user + wants (`accept/preflight.md` §6). Proposing both without comment is not a confirmation of both. | Condition | Transition | |---|---| @@ -235,7 +262,7 @@ generated before the task is confirmed: - Entity: one prediction per
. - Outcome: / - Window: <0 to N days after the prediction anchor> | static -- Task type: +- Task type: — - Output: predictions written to in the same notebook | notebook only, no predictions written - Scoring population (static tasks): rows whose is NULL | all rows, staged at - Threshold (binary classification, written or local): @@ -312,7 +339,9 @@ After ACCEPT, load `kumoai-reference/SKILL.md` and hand off the confirmed payloa describing the one line to add a destination later. That example is markdown text, never a code cell: a notebook with no confirmed destination contains no code that writes. Inside the markdown, show the code as text (a `text` fence), never as a `python` code block — - one that would run is a code cell that writes. + one that would run is a code cell that writes. A confirmed population table is not a + destination: staging it is the notebook's only write, and its name never implies an + output table. The predict call is part of the artifact, not a separate job the agent manages. The agent still executes nothing (Step 3 is opt-in). @@ -338,7 +367,8 @@ in the same or a later turn. Then, per `kumoai-reference/references/kumo_finetun - Report the outcome: the training metrics, or the exception and the cell that raised it - **Read what Kumo said about the data first.** A warning or error about the data — duplicate primary keys, a foreign key that matched few rows, invalid values read as null, a float or - mismatched key, an empty training table — leads the report, with the table, column and count, + mismatched key, an empty training table — or a link check line with unmatched rows + (`hosts//runtime.md`, where it has one) leads the report, with the table, column and count, and the decision goes to the user: fix the source, change the key or link, or accept the loss. A run that finished is not a success until they have decided. Never change the data, a column's type or the query to make such a message go away diff --git a/skills/kumo-data-science/accept/preflight.md b/skills/kumo-data-science/accept/preflight.md index abed8b5ba..8bf3a8727 100644 --- a/skills/kumo-data-science/accept/preflight.md +++ b/skills/kumo-data-science/accept/preflight.md @@ -139,11 +139,44 @@ agent does not deduplicate or filter. Until the user confirms it, the table is t keyless — usable as an edge source, but not as an edge destination and not as the `FOR EACH` entity. Confirmation is what lifts that restriction, not the existence of a candidate. +When a key repeats, test whether it is unique together with an **id-like** column that the table +shares with the tables linking to it — a tenant, organisation, account or region id; never a +time, amount or other measure, which can make any key look unique: +count the groups in `SELECT , FROM
GROUP BY , ` and compare with +`COUNT(*)`, also requiring zero nulls in either column. Use the active host's identifier quoting; +this grouped-subquery form works on BigQuery too. If one is, say the key is only unique within +`` and suggest a single combined key built upstream; Kumo keys are one column, and the agent never +builds one. If you cannot run the probe, do not ask the user to run it and do not take a go-ahead +as its result: the notebook runs it before `graph.snapshot()` and stops when the key repeats +(`kumoai-reference/references/troubleshooting_signals.md` §1). + ## 4. Time column per table The first `TIMESTAMP*`, `DATE`, or `DATETIME` column, preferring names ending in `_AT`, `_TS`, `_TIME`, `_DATE`, or named `EVENT_TIME` / `TIMESTAMP`. A table with none is static. +The time column decides which rows count as history and which fall into a target window, so the +pick is never silent. On **every** table's time-column line — even with a single candidate, and +even when the line came from a host-supplied preflight result — say why it was picked (the only +timestamp column; named as the row's creation or event time; the first candidate by type and +name) and list the table's **other** timestamp columns, or say there are none. When a table has +more than one, ask in the proposal which one marks when the row's fact happened or became known, +and say how to change it: name the column, and the notebook sets it as `time_column`. Names and +values cannot settle this; the user does. A column not chosen is still placed in time by §5. + +**An interval table declares its end column.** When a table's rows are valid over a period — its +time column is the start (`START_DATE`, `EFFECTIVE_START_TS`) and another date or timestamp column +marks when the row stops being valid (`END_DATE`, `EFFECTIVE_END_TS`) — name that column as the +table's **end time column**; do not drop it and do not leave it as an ordinary feature. Kumo keeps +an end time column out of the model's features, so it carries no future information, and the table +still records the period. Say so on the table's time-column line (`time column START_DATE, end +column END_DATE [inferred]`), and let the notebook set it (`end_time_column=`, +`kumoai-reference/references/graph_construction.md`). A column that is the table's only +timestamp, or that marks an event rather than the end of a validity period, is not an end time +column. An end time column is not listed under `Excluded columns`, and it does not change the +table's primary key: a keyless table with an end time column stays keyless unless the confirmed +graph names a key, and the notebook sets `primary_key=` only to the confirmed key. + For every time-ranged target aggregation, the table it references must have a usable `time_column`. If it does not, say so in the proposal and say what would make the task expressible: a timestamp on some other table does not repair the target. @@ -159,9 +192,10 @@ timestamps and must not be treated as one. For each table, place every candidate feature in time relative to that table's proposed `time_column`, then exclude the ones that are not yet knowable at it. -- When the time column marks the beginning of a validity period or interval, exclude a feature - whose value is only determined once that interval later changes or ends: its eventual endpoint, - its realized duration, or any summary of the completed interval. +- When the time column marks the beginning of a validity period or interval, the interval's end + column is declared as the end time column (§4), not excluded. Exclude a feature whose value is + only determined once that interval later changes or ends: its realized duration, or any summary + of the completed interval. - Exclude a feature computed from, or containing, the confirmed prediction target. - Apply the active host adapter's runtime column constraints. @@ -176,6 +210,48 @@ A link is proposed when a column in table A has the **same name** as the primary taken as well, where the source declares any. Nothing else is inferred — no fuzzy matching, no value overlap checks, no joins executed. +**Check event-link repetition; uniqueness alone is not an invalid link.** For every link whose +source is an event table (it has a time column and its rows are occurrences), probe the foreign +key with the §3 count. `N_DISTINCT = N_NON_NULL` means at most one event per parent through this +link, not that the link is wrong: `orders.shipment_id` can be unique while `orders.customer_id` +repeats. Report the counts and whether the link was inferred or supplied; ask whether the link +is intended or a different stable entity id is needed. Do not put it under `Not found` solely +for uniqueness. After the user explicitly confirms that non-repeating link, retain it and record +the confirmation. A one-to-one link between two entity tables needs no repetition probe. If the +probe cannot run here, the notebook runs it before the snapshot and pauses for confirmation of +an observed unique link (`kumoai-reference/references/troubleshooting_signals.md` §2). A generic +go-ahead is neither a probe result nor confirmation of an observation not yet reported. +Each link line names its basis: `declared`, `same name`, or `[supplied]` for a link the user +named. A column whose name only resembles another table's key — a prefix or suffix added, a +synonym, an abbreviation (`buyer_id` or `xuser_id` beside `user_id`, `sku` beside `product_id`) — +is never linked on that resemblance: list it under `Not found` as a possible link, say which key it +might reference, and let the user name it. Once named, it is `[supplied]`, and the user's +confirmation is the only basis it has. + +Value overlap never creates a link, but it is how every link is checked. For each link the graph +uses, report the share of its non-null values found in the parent key, so a wrong link stands out: +measured here when you can read rows (a scalar count, as for keys), otherwise by the notebook's link +check before training (`hosts//runtime.md`), and shown on the link line as `coverage: not +measured yet` until then. When it is measured, every link's share goes to the user; a low one means +the link, or the parent table, is wrong. + +**Two links from one table to the same table** — both ends of a connection, a follow, a referral, +a transfer — are a decision for the user, not two ordinary links. Kumo accepts both, but a query +that aggregates across that table to the shared parent fails query validation with +`Ambiguous link between tables` (the foreign key is not unique). Report the pair in the proposal, +under `Not found`, and ask which the user wants: +1. **One direction** — the graph gets a single `Edge` for the column they name. Removing the + extra `Edge` resolves the ambiguous path; it does not require removing the other column. + Keep that column when a confirmed query uses it. PQL confirmation follows this proposal, so + do not require a confirmed query here: retain the column pending that check and apply the + normal column-availability rules before code generation. +2. **Both, directed** — keep both links; fine as long as no query aggregates across that table to + the shared parent. +3. **Undirected** — the user writes each row twice upstream, the second copy with the two columns + swapped, and the graph keeps one link. + +Propose, never apply: the notebook does not copy, swap or drop rows. + ## 7. Seeds and table mode - **Seeds** are the tables behind `prediction_entity` and `prediction_target` (for link @@ -205,11 +281,14 @@ Table mode: all-connected [default] — 7 of 7 tables reachable from the seeds Metadata - customers: primary key CUSTOMER_ID [inferred] - fraud_events: primary key EVENT_ID [inferred] -- fraud_events: time column EVENT_AT [inferred] +- fraud_events: time column EVENT_AT [inferred] — named as the event time; other timestamp + columns: RESOLVED_AT. Which one marks when the event happened? Name another to use it instead +- customer_plans: time column VALID_FROM [inferred], end column VALID_TO [inferred] — a validity + period; VALID_TO is set as the end time column, not a feature - ... Links -- fraud_events.CUSTOMER_ID -> customers.CUSTOMER_ID [inferred] +- fraud_events.CUSTOMER_ID -> customers.CUSTOMER_ID [inferred] — same name; coverage: 99.6% of non-null values found - ... Excluded columns @@ -217,6 +296,10 @@ Excluded columns - fraud_events.DAYS_TO_RESOLVE [inferred] — duration of an interval that has not ended yet - ... +Column types +-
. [inferred] — Kumo: (); its meaning: — +- ... + Not found - payments: no primary key inferred [inferred] — treated as keyless; edge source only unless corrected - events: no usable time column [inferred] — a time-ranged target cannot reference this table @@ -225,14 +308,16 @@ Not found Confirm, or correct any line (your values take precedence). ``` -`Excluded columns` and `Not found` are local availability-gate extensions to the confirmation -format. +`Excluded columns`, `Column types` and `Not found` are local availability-gate extensions to the +confirmation format. `Column types` follows router Node 1c, *Column types*. ## 9. Never - Prepare, transform, aggregate or materialize **model inputs** — joining, cleaning, deduplicating, creating labels. A diagnostic scalar aggregate over source rows is permitted - solely as evidence for the proposal: row, distinct and null counts for a proposed or candidate key. Its + solely as evidence for the proposal: row, distinct and null counts for a proposed or candidate key, + distinct and null counts for an event link's foreign key, and the matched share of a proposed + link (§6). Its result is reported and then discarded; it is never written anywhere and never reaches training. - Rank tables by relevance or drop tables the user did not ask to drop. - Proceed to PQL before the proposal is confirmed. diff --git a/skills/kumo-data-science/hosts/generic/runtime.md b/skills/kumo-data-science/hosts/generic/runtime.md index 398fee17c..e79126f53 100644 --- a/skills/kumo-data-science/hosts/generic/runtime.md +++ b/skills/kumo-data-science/hosts/generic/runtime.md @@ -194,6 +194,32 @@ destination. --- +### 2.2 Required read-only diagnostics + +After connecting and before `graph.snapshot()` or any training, generate the checks in +`kumoai-reference/references/troubleshooting_signals.md` §0.1: unprobed primary-key nulls and +uniqueness (including shared id-like scope columns), every link's coverage and leading-zero +comparison, and unprobed event-link repetition. Use the source's reader, never a Snowpark +session assumed to exist on this host: + +| Source | Reader and adaptation | +|---|---| +| Snowflake | `connector.session().sql(...).collect()` with Snowflake quoted identifiers. Use the §1/§2 reference examples and the connector's access context. | +| BigQuery | `bigquery.Client(project=PROJECT_ID, credentials=BQ_CREDENTIALS).query(sql).result()` with the dataset's own location. Quote all identifiers with `bq_name`. Use `COUNTIF`, `IF`, and `CAST(... AS STRING)` instead of Snowflake-only functions; count composite-key groups in a subquery and check both components for nulls. | +| Databricks | The statement API on the connector's confirmed SQL warehouse and the same identity (§2, §3). A cluster-only connector has no diagnostic SQL reader specified here: report the missing reader and stop; do not invent a warehouse. Use `q` for identifiers, `SUM(CASE WHEN ... THEN 1 ELSE 0 END)` with a zero default for conditional counts, and `CAST(... AS STRING)` for the diagnostic-only padding comparison. Statement results are strings: convert counts to integers, retaining null handling. | +| Files, S3, GCS | `pyarrow.dataset` on the confirmed source paths and formats, using the same filesystem credentials as the connector (§2, §3.1). Project only key and scope columns; do not sample these checks. Count nulls, distinct values and pairs, and test non-null child membership against distinct non-null parent keys. Compute diagnostic string padding separately with the length guard; never write or feed transformed arrays into Kumo. | + +Use source paths and table names confirmed at intake, not output locations. Report the counts +and choices defined by §0.1. A unique event link needs specific confirmation, not an automatic +rejection; unmatched rows need the user's decision even when most rows match. Record approved +continuations per link. If credentials, unsupported formats/types, resource limits or reader +errors prevent a required measurement, report it as unresolved and emit a raising guard before +snapshot/training. Never silently skip a check, invent zero counts, or train with coverage still +`not measured yet`. The emitted artifact must contain the adapted checks, not just a comment +asking the user to implement them. Diagnostics never change source data or graph choices. + +--- + ## 3. Destinations and read-back Build the output connector for the destination's own system, and the `PredictionOutputConfig` in diff --git a/skills/kumo-model-persistence/references/reuse.md b/skills/kumo-model-persistence/references/reuse.md index 2ca79b960..7b02243c4 100644 --- a/skills/kumo-model-persistence/references/reuse.md +++ b/skills/kumo-model-persistence/references/reuse.md @@ -44,6 +44,12 @@ For an explicitly retained complete local bundle, use this alternative: loaded = kumo.Trainer.load(RETAINED_BUNDLE_DIRECTORY) ``` +`RETAINED_BUNDLE_DIRECTORY` is the directory that directly holds `training-spec.json`, as the +host's file listing shows it: for a copy laid out as `/model/training-spec.json` next to +`/metadata.json`, that is `/model`, not ``. A record kept beside the bundle +(its query, tables, columns, keys and edges) is read when the notebook is written, and the +notebook carries those values as literals, so the rebuilt graph can be reviewed before it runs. + Load only trusted publications. The loader checks bundle integrity and training metadata; hashes detect corruption, not publisher trust. Missing `training-spec.json`, incompatible spec versions or failed integrity checks are actionable restore errors. Retrieve the complete diff --git a/skills/kumoai-reference/references/graph_construction.md b/skills/kumoai-reference/references/graph_construction.md index 5995891ff..2758ab896 100644 --- a/skills/kumoai-reference/references/graph_construction.md +++ b/skills/kumoai-reference/references/graph_construction.md @@ -183,6 +183,43 @@ Rules: - Both `dtype` and `stype` must be resolved before a table is used in a `PredictiveQuery`; `infer_metadata()` resolves whatever is missing. +### How a semantic type is inferred + +For a column with no declared type, `infer_metadata()` reads, in order: its role (a primary key +is `ID`, a time column `timestamp`), its physical type (date, time, boolean and list types decide +on their own), its **name**, and then its **values**, in a sample of up to 10,000 rows. The first +that decides wins. The name and value rules below can contradict what a column means; the graph +gate reports each selected column they match (router Node 1c, *Column types*), and a confirmed +correction is declared with `with_column`. + +- **A name can make a column `ID`.** An integer or string column is typed `ID` by its name alone, + before any value is read, when the name ends in `id` (a few words such as `paid` or `fluid` + excepted) or contains `_id_`; has `code`, `key`, `hash`, `no`, `class`, `label`, `cate` or + `category` as an underscore-separated word at its start, middle or end (`discount_code`, + `dept_no`, `fraud_label`); or merely starts or ends with `key` or `code` (`keyword_count`, + `barcode`). Float columns are exempt. A measurement, a count or a class label with such a name + becomes an identifier: its values stop being magnitudes, and `SUM` or `AVG` over it fails the + query (`kumoai-reference/references/troubleshooting_signals.md` §3). Report it as + `Kumo: ID (named *_code)` beside the type its meaning calls for. A column that a `SUM` or `AVG` + target aggregates is declared `numerical` whenever its name matches — the request already says + it is a quantity — including a float column, which the rule exempts today but would not after + a change of physical type; say so at the gate. +- **Few distinct values make a number `categorical`.** Unless its name already decided it, a + column with at most 3 distinct sampled values is typed `categorical`, and so is an integer + column with at most 4,000 distinct values that are no more than 5% of the sampled rows. A name + containing `num`, `number`, `count`, `total`, `sum`, `avg`, `price`, `score`, `ratio` or + `value` as a prefix, a suffix or an underscore-separated word is typed `numerical` before the + values are read. A count without such a name — visits, items, contacts per row — usually lands + in `categorical`: as a `SUM` or `AVG` target the task stays regression but `pquery.validate()` + warns (`kumoai-reference/references/troubleshooting_signals.md` §3) and the column's history + is encoded as labels; as a static target (`PREDICT
.`) the task becomes + multiclass classification instead of regression. When the request asks for an amount, a total + or a number of something, report `Kumo: categorical (integer, few distinct values)` beside + `numerical`, declare `with_column('', stype=Stype.numerical)` in the notebook, and say on + the Node 1d *Task type* line that this is what makes the task regression. + +Source: shipped package (`kumo_core.stype_inference`, `kumo.engine.table`) + --- ## Step 4: build the graph @@ -245,10 +282,14 @@ Assigning time columns: - Do **not** designate an administrative last-modified timestamp unless it represents when the row became valid for modeling. - Tables without a meaningful timeline can legitimately have no time column. -- `end_time_column` exists as a `Table`/`from_source_table` parameter for rows with a validity - interval. - > Not verified: its exact semantics under this SDK. Do not describe or rely on its - > filtering behavior. +- Rows with a validity interval (the time column is the start, another column the end) declare + the end column with `end_time_column` on `Table.from_source_table(...)`, next to `time_column`: + `from_source_table(connector['T'], [...], time_column='START_DATE', end_time_column='END_DATE')`. Verified in the SDK source: the column is typed as a timestamp, it + must be among the table's `columns`, and it is left out of the model's feature columns + (`kumo_core.encoder_selection.feature_column_names`), so it does not leak. Sampling is + end-date-aware only on the entity table (after `FOR EACH`) and on the right-hand table of a link + prediction (`troubleshooting_signals.md`); say nothing more about its filtering. It needs no + primary key: a keyless event table keeps `primary_key=None` with an end time column set. Temporal splits: for a temporal predictive query, Kumo splits train/validation/holdout by the time column of the target table, and at prediction time accesses only data with timestamps at @@ -260,10 +301,10 @@ every selected feature in that row. If it marks the start of an interval, a fiel determined when that interval later changes or ends — its endpoint, its realized duration, or a summary of the completed interval — is future information and must not be used as a feature. -If such an interval endpoint is an ordinary candidate feature, omit it from the positional column -list. If it is configured as `end_time_column`, keep it selected as structural metadata and do not -present it as a feature; do not rely on its interval-filtering behaviour unless that behaviour has -been verified for the deployed bundle. +The interval's endpoint is configured as `end_time_column`: keep it selected as structural +metadata, never drop it and never present it as a feature. Its realized duration, or a summary of +the completed interval, is omitted from the positional column list. Do not rely on the endpoint's +interval-filtering behaviour beyond what is stated above. The same applies to the prediction target: keep the target column selected so the query and table metadata can reference it, and exclude only the companion columns derived from it. @@ -273,7 +314,8 @@ Leakage causes to screen for: - An event timestamp marks the start of a period while another column summarizes what happened by the end of that period. - A supposedly static entity column is overwritten over time, so the historical value is not - recoverable. + recoverable. Flagged at the graph gate (`kumo-data-science/SKILL.md` Node 1c, current-state + attributes); the user decides. - Training and holdout periods overlap or are ordered incorrectly. Fix the source timeline or drop the leaking field. Do not compensate with model tuning. @@ -399,8 +441,9 @@ Source: shipped package (`kumo.engine.table`, `kumo.engine.graph`, `kumoapi.grap Do not fill these from memory. If the task requires them, say so. -- `end_time_column` semantics under the Kumo Predict SDK (parameter exists; behavior only - documented for the separate KumoRFM product line, which is out of scope here). +- How `end_time_column` filters rows beyond the entity table and a link-prediction right-hand + table: declaring it is verified (it is a structural column, not a feature); any further + sampling behaviour is not. - Whether self-referencing edges (self-loops) are permitted. - Excluding the target label column from features at table-definition time: there is no known `features=` argument on `Table`. Control feature inclusion via `column_names` / `columns`. diff --git a/skills/kumoai-reference/references/kumo_finetuning_sdk.md b/skills/kumoai-reference/references/kumo_finetuning_sdk.md index bd74d0edc..39f893ef8 100644 --- a/skills/kumoai-reference/references/kumo_finetuning_sdk.md +++ b/skills/kumoai-reference/references/kumo_finetuning_sdk.md @@ -217,6 +217,11 @@ exact name, then its upper-cased form, so `connector['ENTITY_PROFILE']` never fi table names as `table_names()` returns them and column names as `.columns` returns them — in `primary_key=`, `time_column=`, column lists and filters. +**Set `primary_key=` only where the confirmed graph names a primary key.** A table the graph +lists as `no primary key` is built without `primary_key=`, even when it has a column that looks +like one (`status_event_id`) or an end time column; adding a key changes the graph the user +confirmed. + **Never exclude a column by a case-sensitive `!=` against a hand-typed literal.** A filter such as `c.name != 'END_DATE'` silently keeps a lower-case `end_date` — the comparison never matches, the column is never dropped, and nothing raises. Pass the confirmed `Excluded columns` from preflight @@ -342,6 +347,9 @@ Table.infer_metadata() only values. Correct every FK with `.with_column(col, stype=Stype.ID)`. - **A TEXT time column needs `dtype=Dtype.date`** declared, or staging will not cast it. - `infer_metadata()` takes no arguments. +- **An interval table sets `end_time_column`** to the column that marks when the row stops being + valid, keeps it in `column_names`, and never drops it + (`kumo-data-science/accept/preflight.md` §4, `graph_construction.md`). - Read-back attributes live under `.definition`: `.definition.pkey`, `.definition.time_col`, `.definition.end_time_col`. `.table_name` is on the table itself. @@ -394,13 +402,20 @@ Source: shipped package (`kumo.engine.graph`) ```python pquery = kumo.PredictiveQuery(graph=graph, query=QUERY) -pquery.validate() +response = pquery.validate() print('task type:', pquery.get_task_type()) +type_warnings = [w.message for w in response.warnings if w.title == 'Semantic Type Mismatch'] +if type_warnings: # e.g. a SUM over a column typed categorical: the user decides first + raise RuntimeError('Query validation warned about a semantic type; resolve before training:\n' + + '\n'.join(type_warnings)) ``` - The graph is bound at construction; parsing is lazy. - **Emit `validate()` with no arguments.** It raises on an invalid query; otherwise it returns a - `ValidationResponse` and logs its warnings. + `ValidationResponse` and logs its warnings. A warning titled `Semantic Type Mismatch` means a + column's inferred type does not fit what the query does with it (`troubleshooting_signals.md` + §3), so the notebook stops on one, after printing the task type, and the agent puts it to the + user. Other warnings are reported, not stopped on. - **Always emit `validate()` then `get_task_type()`** before training. The task type is never written in the query — it is inferred from the target's shape — so print it and confirm it matches intent. A query that validates can still be the wrong task. @@ -417,7 +432,22 @@ Source: shipped package (`kumo.engine.pquery.predictive_query`) Materialization is **explicit**. `fit` does not do it for you. ```python -snapshot = graph.snapshot() +import warnings + +# Kumo reports rows it dropped or could not link as warnings and keeps going +# (troubleshooting_signals.md §1a). Stop here, before any training, so the user decides first. +DATA_WARNINGS = ('duplicate primary-key', 'null or invalid primary key', + 'invalid values found', 'non-null rows') +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + snapshot = graph.snapshot() +for w in caught: + print(f'{w.category.__name__}: {w.message}') +data_problems = [str(w.message) for w in caught + if any(s in str(w.message) for s in DATA_WARNINGS)] +if data_problems and not DATA_LOSS_ACCEPTED: # config cell; False unless the user chose + raise RuntimeError('Kumo reported a problem in the data; stopped before training:\n' + + '\n'.join(data_problems)) training_table = pquery.generate_training_table(snapshot) prediction_table = pquery.generate_prediction_table( @@ -436,7 +466,13 @@ PredictiveQuery.generate_prediction_table(snapshot, *, prediction_time=None, pla - `snapshot` is **positional** on both. `prediction_time` and `plan` are keyword-only on `generate_prediction_table`. - `graph.snapshot()` reads every table through its connector and builds an on-disk DiskGraph index - under the scratch directory. An unchanged valid snapshot is reused on later runs. + under the scratch directory. An unchanged valid snapshot is reused on later runs, and its data + warnings are raised again. +- **The snapshot cell stops on a data warning.** Repeated or missing primary keys, unparseable + values and unmatched foreign keys are warnings, not errors: without the stop the notebook trains + on what is left. `DATA_LOSS_ACCEPTED = False` goes in the config cell; it becomes `True` only + after the user has seen the messages and chosen to continue with the loss, never on the agent's + own initiative. - `GraphSnapshot` exposes `.id`, `.index_path`, `.graph_config`. - `TrainingTable` exposes `.train_table_path` (ordinary parquet), `.manifest_path`, `.required_stages`, `.generation_plan`. @@ -501,6 +537,9 @@ prediction_table = kumo.PredictionTable.from_source_table( contain a target column. The SQL above stages only `ENTITY1`, which suffices for a static query on an entity without a timestamp; otherwise also select the anchor time as `TIMESTAMP`. - Rows the model trained on are scored too. Say so: those predictions are not out-of-sample. +- The population table is an input, not a destination. With no confirmed destination + (`notebook only`), the notebook stages the population and predicts with no `output_config`; + it defines no `OUTPUT_*` names and no output connector. Source: shipped package (`kumo_core.prediction.generate_prediction_table`, `kumo.engine.pquery.prediction_table.PredictionTable.from_source_table`) @@ -679,6 +718,7 @@ confirmed output destination (§12). ```python from datetime import datetime from pathlib import Path +import warnings import kumo.engine as kumo from kumo.engine import Edge @@ -688,6 +728,7 @@ from kumoapi.typing import Stype from snowflake.snowpark.context import get_active_session OUTPUT_DATABASE, OUTPUT_SCHEMA, OUTPUT_TABLE = '', '', '
' # confirmed destination +DATA_LOSS_ACCEPTED = False # True only after the user sees the warnings and accepts the loss session = get_active_session() # §3.3: only where the host provides the session @@ -729,12 +770,27 @@ pquery = kumo.PredictiveQuery( query=('PREDICT LIST_DISTINCT(transaction_events.location_id, 0, 30, days) ' 'RANK TOP 10 FOR EACH account_profile.account_id'), ) -pquery.validate() +response = pquery.validate() print('task type:', pquery.get_task_type()) +type_warnings = [w.message for w in response.warnings if w.title == 'Semantic Type Mismatch'] +if type_warnings: + raise RuntimeError('Query validation warned about a semantic type; resolve before training:\n' + + '\n'.join(type_warnings)) # 5. Materialize. PREDICTION_TIME is NAIVE — a tz-aware datetime raises ValueError. PREDICTION_TIME = datetime(2026, 8, 1) -snapshot = graph.snapshot() +DATA_WARNINGS = ('duplicate primary-key', 'null or invalid primary key', + 'invalid values found', 'non-null rows') +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + snapshot = graph.snapshot() +for w in caught: + print(f'{w.category.__name__}: {w.message}') +data_problems = [str(w.message) for w in caught + if any(s in str(w.message) for s in DATA_WARNINGS)] +if data_problems and not DATA_LOSS_ACCEPTED: + raise RuntimeError('Kumo reported a problem in the data; stopped before training:\n' + + '\n'.join(data_problems)) training_table = pquery.generate_training_table(snapshot) prediction_table = pquery.generate_prediction_table( snapshot, prediction_time=PREDICTION_TIME, # NAIVE datetime, inside the event history @@ -862,7 +918,16 @@ targets a superseded build and needs rewriting against §10 — do not copy its - [ ] `with_column(...)` results assigned or chained — it returns a new Table. - [ ] `Graph(tables=[...], edges=[Edge(...)])` — list form; `graph.validate()` emitted. - [ ] `pquery.validate()` and `get_task_type()` run before training, both called with no arguments. -- [ ] `graph.snapshot()` before generating any table. +- [ ] Every link out of an event table that preflight did not probe is probed before + `graph.snapshot()`. A non-repeating link is reported for explicit confirmation, not rejected + as invalid; continue after recording the user's confirmation (`troubleshooting_signals.md` §2). +- [ ] Every link's match rate probed before `graph.snapshot()`; the notebook stops when fewer + than half its rows match unless the user explicitly accepted that link's measured loss + (`troubleshooting_signals.md` §2). +- [ ] Every primary key preflight did not probe is probed before `graph.snapshot()`; the + notebook stops when it repeats (`troubleshooting_signals.md` §1). +- [ ] `graph.snapshot()` before generating any table, inside the §7 data-warning stop, with + `DATA_LOSS_ACCEPTED = False` in the config cell. - [ ] **`trainer.fit(training_table, snapshot=snapshot)`** — `snapshot=` present. - [ ] **`trainer.predict(prediction_table, snapshot=snapshot, ...)`** — `snapshot=` present. - [ ] `binary_classification_threshold` / `num_classes_to_return` on `predict`, never on diff --git a/skills/kumoai-reference/references/troubleshooting_signals.md b/skills/kumoai-reference/references/troubleshooting_signals.md index a57911a67..3b0e9bbad 100644 --- a/skills/kumoai-reference/references/troubleshooting_signals.md +++ b/skills/kumoai-reference/references/troubleshooting_signals.md @@ -5,7 +5,7 @@ Observable symptom → likely cause → fix. Ordered by when the agent hits them This file is the signal set as previously compiled. It is **not** re-verifiable against the published Kumo documentation, which is stale for this version of the local SDK and is not a source here — do not cite it, fetch it, or reconcile against it. > No verbatim Kumo exception text is established for this SDK. Entries below are keyed on the **observable condition**, not on a quoted message. **Do not fabricate Kumo error strings.** -> The five messages quoted in §1a are the exceptions: they are the SDK's own text, read from its source. +> The messages quoted in §1a and the semantic-type messages quoted in §3 are the exceptions: they are the SDK's own text, read from its source. **Who applies a fix.** A fix that changes the data — casting a column, deduplicating, flattening, filling or filtering values, combining columns into a key, normalising key types — is the user's @@ -41,6 +41,33 @@ Inspect a table through `.definition` (`.pkey`, `.time_col`, `.end_time_col`) an --- +### 0.1 Read-only diagnostics on the active host + +The SQL cells in §1 and §2 are **Snowflake examples**, not portable cells to copy unchanged. +Use the active `hosts//runtime.md` reader and identifier quoting. On Snowflake use +`connector.session()`, not an unrelated active session. On other sources translate the following +checks into that reader's SQL or Arrow operations, before `graph.snapshot()` and training. +Build and validate the confirmed graph before measuring link coverage so the SDK rejects +incompatible key types before a reader's implicit coercion can hide them; preserve allowed +lossless integer widening rather than imposing exact source-type equality: + +| Check | Required result and action | +|---|---| +| Primary keys not probed in preflight (§1) | Report total, non-null and distinct counts. Stop on missing or repeated keys; report an empty table separately. Test only shared id-like scope columns, requiring both columns non-null and one distinct pair per row, before suggesting a combined key upstream. | +| Every confirmed link (§2) | Report non-null child rows, matched rows and share, unmatched rows, distinct unmatched values and nulls. Use distinct parent keys so duplicate parent rows cannot multiply counts. Report key-type incompatibility before comparing; do not coerce it into a match. Present any unmatched rows for a user decision, even above 50% coverage. The low-coverage stop defaults on; only explicit acceptance of that link's measured loss permits continuation. | +| Leading-zero diagnosis (§2) | Compare string representations only in diagnostic results, never model inputs. Count hypothetical zero-padded matches only for child values no longer than the parent width; never truncate longer values into a match. Report the counts, without padding or casting the source supplied to the graph. | +| Unprobed event links (§2) | Report non-null and distinct foreign-key counts. If all non-null values are unique, ask whether that relationship is intended; retain it after recording specific confirmation, rather than rejecting it solely for uniqueness. | + +A failed, unavailable or unauthorized reader is **unresolved**, not zero coverage or a successful +check. Name the affected table/columns and reason, then raise before snapshot/training; never +silently skip it, switch identities, or treat `coverage: not measured yet` as measured. Do not +request the user to run an unspecified probe. Explain the missing access or reader support and +wait for it or a corrected confirmed graph. Successful diagnostics remain read-only evidence: +no transformed rows, joins or scalar results become model inputs, and no graph choices change +without the user's confirmation. + +--- + ## 1. Table definition ### Symptom: `connector.table("X")` raises `ValueError` @@ -74,8 +101,41 @@ Fully specify tables in production code to avoid unexpected re-inference. ### Symptom: row count silently drops after ingestion **Cause:** Duplicate primary key values — Kumo retains one row per key and drops the rest. **Fix:** Report how many rows the key repeats on (the preflight probe, or the snapshot warning in -§1a) and put the choice to the user: a different, genuinely unique key, or the source deduplicated -upstream. The agent does not deduplicate. +§1a, which stops the notebook before training) and put the choice to the user: a different, +genuinely unique key, or the source deduplicated upstream. The agent does not deduplicate. A key preflight could not probe — supplied, or confirmed +from an unverified candidate — is probed read-only before `graph.snapshot()`, and the notebook +stops when it repeats, after testing the id-like columns the table shares with its linking tables: +```python +def q(name): # a quoted Snowflake identifier + return '"' + name.replace('"', '""') + '"' + +KEYS = [('
', '', [''])] # keys preflight did not probe +for table, key, scopes in KEYS: + src = f'{DATABASE}.{SCHEMA}.{q(table)}' + n, n_distinct, n_non_null = connector.session().sql( + f'SELECT COUNT(*), COUNT(DISTINCT {q(key)}), COUNT({q(key)}) FROM {src}').collect()[0] + print(f'{table}.{key}: {n} rows, {n_distinct} distinct, {n_non_null} non-null') + if not n: + raise RuntimeError(f'{table}.{key}: table is empty; no key values could be checked.') + if n_distinct == n_non_null == n: + continue + unique_within = [] + for c in scopes: + pairs = connector.session().sql( + f'SELECT COUNT(*) FROM (SELECT {q(key)}, {q(c)} FROM {src} ' + f'GROUP BY {q(key)}, {q(c)}) pairs').collect()[0][0] + non_null = connector.session().sql( + f'SELECT COUNT(*) FROM {src} ' + f'WHERE {q(key)} IS NOT NULL AND {q(c)} IS NOT NULL').collect()[0][0] + if pairs == non_null == n: + unique_within.append(c) + raise RuntimeError(f'{table}.{key} is not unique ({n} rows, {n_distinct} distinct, ' + f'{n_non_null} non-null); unique together with: {unique_within or "none"}') +``` +When the key is unique together with one of those columns, the key is scoped to it (the same id +reused by different tenants or organisations), and linking on the key alone merges different +entities. Say so, and suggest a single combined key built in the source and used on both sides of +every link. Do not combine the columns in the notebook. Test only id-like columns. ### Symptom: a categorical column has very high cardinality **Cause:** Categorical supports up to **4,000 unique values by default**. @@ -98,13 +158,17 @@ change data, types or the query to make it go away (*Who applies a fix*, above). |---|---|---| | `Snapshot contains duplicate primary-key row(s) for
.` | `` rows share a key; Kumo keeps one per key and drops the rest | a different key, or the source deduplicated; or continue knowing `` rows are gone | | `Foreign key
. matched of non-null rows` | only `` of `` rows reach the parent; the rest get no edge | the link may be wrong (wrong column, or values differing in format, e.g. `007` vs `7`), or the parent rows are missing | +| `Snapshot dropped row(s) with a null or invalid primary key in
.` | `` rows have no usable key and are gone from the table | the source fixed upstream, or a different key; or continue knowing `` rows are gone | | ` invalid values found in
.` | `` values did not parse as the column's type and are read as null (see §5) | whether those rows are bad data, or the column's type is wrong | | `key
. has a floating-point dtype` | an ID column is stored as a float (often an integer key with nulls) | the column fixed upstream as an integer or string key | | `foreign key
. (dtype=…) cannot link to primary key
. (dtype=…)` | the two sides of a link hold different types | which side is right, fixed upstream; never cast one side in the notebook | -A float or mismatched key fails `graph.validate()` and stops the notebook. The other three are -warnings: the notebook keeps going and trains on what is left. Either way, the report the user -reads starts with the message, the table and column, and the count. +A float or mismatched key fails `graph.validate()` and stops the notebook. The other four are +warnings: Kumo keeps going and trains on what is left, so the notebook's snapshot cell turns them +into a stop before training (`kumo_finetuning_sdk.md` §7). Either way, the report the user reads +starts with the message, then, per table, how many rows were lost or left unlinked and why — +repeated key, missing key, or a value (a time, a number) that did not parse — and asks before +anything trains. --- @@ -121,14 +185,79 @@ print(table.has_primary_key()) ### Symptom: an edge is declared but the model learns nothing from it **Cause:** FK values do not actually match PK values. Rows with missing or unmatched key values are **silently ignored** when linkages are built, so a broken join looks like a sparse one. If the two -linked columns have different types, both are **cast to strings** — values equal as numbers may not -match as strings (`1.0` vs `1`). -**Fix:** There is **no `get_edge_stats()` in this SDK.** The snapshot reports the match rate -(§1a). Report it, and put a low one to the user before training: a wrong link to correct, or keys -to fix upstream so both sides hold the same values in the same type. Do not cast either side. +linked columns have incompatible types, `graph.validate()` rejects the graph before ingestion; +it permits matching types and lossless integer widening, not arbitrary numeric/text coercion. +**Fix:** There is **no `get_edge_stats()` in this SDK.** The snapshot warns about a low match +rate (§1a) but keeps going, so the notebook measures it itself, read-only, before +`graph.snapshot()`, for every link, and stops when fewer than half the rows match unless the +user has explicitly accepted that link's measured loss. It also counts +how many would match if the foreign key were padded with leading zeros to the primary key's +width — the signature of an id that was read as a number somewhere upstream (`007` became `7`): +```python +def q(name): # a quoted Snowflake identifier + return '"' + name.replace('"', '""') + '"' + +LINKS = [('', '', '', '')] # every confirmed link +ACCEPTED_UNMATCHED_LINKS = set() # (src, fk, dst, pk), only after the user accepts measured loss +for src, fk, dst, pk in LINKS: + n, matched, padded = connector.session().sql( + f'WITH p AS (SELECT DISTINCT TO_VARCHAR({q(pk)}) AS k FROM {DATABASE}.{SCHEMA}.{q(dst)}), ' + f'w AS (SELECT MAX(LENGTH(k)) AS w FROM p) ' + f'SELECT COUNT(f.{q(fk)}), COUNT(a.k), COUNT(b.k) ' + f'FROM {DATABASE}.{SCHEMA}.{q(src)} f CROSS JOIN w ' + f'LEFT JOIN p a ON a.k = TO_VARCHAR(f.{q(fk)}) ' + f'LEFT JOIN p b ON LENGTH(TO_VARCHAR(f.{q(fk)})) <= w.w ' + f'AND b.k = LPAD(TO_VARCHAR(f.{q(fk)}), w.w, \'0\')').collect()[0] + print(f'{src}.{fk} -> {dst}.{pk}: {matched} of {n} rows match; {padded} if zero-padded') + if n and matched < 0.5 * n and (src, fk, dst, pk) not in ACCEPTED_UNMATCHED_LINKS: + raise RuntimeError(f'{src}.{fk} matched {matched} of {n} rows to {dst}.{pk} ' + f'({padded} would match zero-padded to the key width).') +``` +The probe only diagnoses; it never feeds the graph. Report the counts and put the choice to the +user before training. Record only the particular link whose measured loss the user accepted in +`ACCEPTED_UNMATCHED_LINKS`; a generic go-ahead or confirmation of the link's identity is not +acceptance of unmatched rows. Other links still stop by default. When the zero-padded count is +high, say that the ids lost their leading zeros, that this cannot be recovered in the notebook, and that the fix is upstream: load or store +`
.` as text so the zeros survive. Otherwise the link is wrong, or the parent rows are +missing. Do not cast or pad either side in the notebook. +A link that loses fewer rows than that passes the snapshot silently. The host runtime's link +check cell, run after `graph.validate()` and before the snapshot, counts matched, unmatched and +null values for every link. Report each link's share, and put any unmatched rows to the user before +training: a wrong link to correct, parent rows missing upstream, or keys to fix upstream so both +sides hold the same values in the same type; or continue knowing those rows get no edge. Do not +cast either side, filter the rows or invent the missing parents. Set every foreign key to `Stype.ID`; left as numerical it is treated as a feature rather than a link. +### Symptom: an event table's foreign key never repeats +**Possible cause:** A per-event id was used instead of a stable entity id. But one event per +parent is valid too: `orders.shipment_id` can be unique while `orders.customer_id` repeats. +Uniqueness alone does not invalidate a link or prove that the table has no history. +**Fix:** Report the counts and ask the user to confirm the relationship. For event links not +already probed in preflight, run this read-only check before `graph.snapshot()`. Record explicit +confirmation of each observed non-repeating link in `CONFIRMED_UNIQUE_EVENT_LINKS`; leave the set +empty until the user has seen the counts and confirmed that link, not merely said go ahead. +```python +def q(name): # a quoted Snowflake identifier + return '"' + name.replace('"', '""') + '"' + +EVENT_LINKS = [('', '')] # every unprobed event link +CONFIRMED_UNIQUE_EVENT_LINKS = set() # (table, fkey), only after explicit confirmation +for table, fkey in EVENT_LINKS: + n, n_distinct = connector.session().sql( + f'SELECT COUNT({q(fkey)}), COUNT(DISTINCT {q(fkey)}) ' + f'FROM {DATABASE}.{SCHEMA}.{q(table)}').collect()[0] + print(f'{table}.{fkey}: {n} non-null rows, {n_distinct} distinct values') + if n and n_distinct == n: + print(f'WARNING: {table}.{fkey} never repeats; confirm whether this link is intended.') + if (table, fkey) not in CONFIRMED_UNIQUE_EVENT_LINKS: + raise RuntimeError(f'{table}.{fkey}: awaiting confirmation of the reported unique link.') +``` +Report the table, column, counts and whether the link was inferred or supplied. Let the user +confirm the link or name another stable id; after explicit confirmation, continue with the +retained link and its recorded confirmation. Never replace or drop it silently. A one-to-one +link between two entity tables is normal; do not probe it. + ### Symptom: the edge direction looks wrong / no neighbors are sampled **Cause:** `src_table` must be the table holding the **foreign key**; `dst_table` holds the matching **primary key**. Edges are bidirectional once declared, but the declaration itself is directional. **Fix:** @@ -181,6 +310,31 @@ pquery = kumo.PredictiveQuery( pquery.validate() ``` +### Symptom: `pquery.validate()` fails with `Ambiguous link between tables` +**Cause:** The query aggregates from one table to another that it reaches through two links — +two columns of one table pointing at the same parent. The validator cannot pick one. (The title is +the query validator's own text, from `kumopql`'s join validation.) +**Fix:** A graph change for the user to choose (`kumo-data-science/accept/preflight.md` §6): keep +one link, or have the rows written in both directions upstream and keep one link. Do not drop a +link or column, or copy or swap rows, in the notebook before the user has chosen. +### Symptom: the query fails with `Aggregation SUM is not intended to operate on foreign keys and ID-type columns.` +**Cause:** The column `SUM` or `AVG` aggregates is typed `ID`: it is a key, or `infer_metadata()` +typed it `ID` from its name (`graph_construction.md` *How a semantic type is inferred*). +Source: shipped package (`kumopql.validator.type_validator`). +**Fix:** Name the column, its type and why — "`orders.discount_code` is `ID` because it is named +`*_code`". A key is the wrong column to sum: aggregate a measurement, or `COUNT` the rows. A +measurement typed `ID` by its name is declared `.with_column('', stype=Stype.numerical)` — +a type declaration the user confirms at the graph gate (router Node 1c, *Column types*), never a +silent change. +### Symptom: `pquery.validate()` warns `Aggregation SUM is intended to operate on numerical columns, but
. has semantic type categorical.` +**Cause:** `infer_metadata()` typed the aggregated column from its few distinct values +(`graph_construction.md` *How a semantic type is inferred*), not from what it measures. The query +still validates and training would run. Source: shipped package (`kumopql.validator.type_validator`). +**Fix:** Stop before training and put it to the user: the column, the type Kumo gave it and why, +and the task type `get_task_type()` reports. A quantity is declared +`.with_column('', stype=Stype.numerical)` once the user confirms it (router Node 1c, +*Column types*). The same applies to every other warning `validate()` titles `Semantic Type Mismatch`. + ### Symptom: aggregation window rejected **Cause:** Both *start* and *end* must be **non-negative integers**, and *end* must be **greater than** *start*. **Fix:** Correct the bounds. Semantics: start is exclusive, end is inclusive. `SUM(TRANSACTIONS.PRICE, 10, 30)` from a `2020-01-01` anchor aggregates `2020-01-11 00:00:00 < t <= 2020-01-31 00:00:00`. @@ -206,7 +360,7 @@ print(training_table.data_df().head()) ### Symptom: an `END_DATE` column is set on a non-entity table and appears to be ignored **Cause:** End-date-aware sampling is currently supported **only** on the entity table (after `FOR EACH`) and on the RHS table in link prediction (after `LIST_DISTINCT`). -**Fix:** Do not rely on end dates elsewhere. +**Fix:** Do not rely on end dates elsewhere to filter rows. Declare the end column as `end_time_column` anyway (`graph_construction.md`): it stays out of the features, which is what keeps it from leaking; it does not change sampling on other tables. ### Symptom: date-only boundary includes one day too few / too many **Cause:** A date such as `2025-10-01` is interpreted at the **start** of that day. The target window is left-open, right-closed.