Skip to content

driver-sql: SQLite introspection reports only the FIRST column of a composite primary key (pk === 1 vs SQLite's 1,2,3… numbering) #10997

Closed

Description

@os-warren

Found while fixing the introspection seam for #10676 (packages/services/service-datasource). The defect is upstream of that seam, in driver-sql, so it is filed separately rather than widened into that PR.

What

SqlDriver.introspectPrimaryKeys (packages/drivers/driver-sql/src/sql-driver.ts, SQLite arm) collects primary-key columns with:

const result = await this.knex.raw(`PRAGMA table_info(${safeTableName})`);
for (const row of result) {
  if (row.pk === 1) {
    primaryKeys.push(row.name);
  }
}

PRAGMA table_info does not report pk as a boolean. It reports the column's 1-based position within the primary key — 0 for "not part of the key", 1 for the first key column, 2 for the second, and so on. Filtering on pk === 1 therefore keeps only the first member of a composite key and silently drops the rest.

Measured

Live in-memory SQLite at 368e7a06f, table created as t.primary(['order_id', 'line_no']):

PRAGMA table_info(order_lines):

name pk
order_id 1
line_no 2
sku 0

SqlDriver.introspectSchema() for that table:

{
  "name": "order_lines",
  "primaryKeys": ["order_id"],
  "columns": [
    { "name": "order_id", "isPrimary": true },
    { "name": "line_no",  "isPrimary": false },
    { "name": "sku",      "isPrimary": false }
  ]
}

line_no is a declared member of the primary key and is reported as not being one. Note that both output signals are wrong together, and for the same reason: introspectSchema derives col.isPrimary from primaryKeys (if (primaryKeys.includes(col.name)) col.isPrimary = true), so a consumer cannot recover the missing member by cross-checking the two.

Why it matters

Every consumer of SQLite introspection sees a composite-keyed table as single-keyed:

  • the federated-object codegen and the persisted external_catalog (ADR-0015) record a partial addressing/upsert key;
  • schema-drift comparison against a declared composite key reads as drift on the missing member.

SqliteWasmDriver extends SqlDriver and inherits this arm, so it is affected identically.

Fix direction

row.pk > 0 rather than row.pk === 1, and — since pk is an ordinal — push in pk order so primaryKeys reflects the declared key order rather than column order. Worth a pin over a real composite-keyed table; the current suite has none.

The Postgres and MySQL arms read from pg_index / KEY_COLUMN_USAGE and do not have this specific bug, though neither orders its result by key position either (ORDER BY is absent in both) — worth confirming in the same pass.

Not measured here

Only the SQLite arm was executed (better-sqlite3, in-memory). The Postgres and MySQL arms were read, not run — no server was reachable from this container.

Filed unassigned as a finding awaiting first-touch grading. Discovered from #10676.

Activity

  1. added theissue type on Aug 22, 2026
  2. added
    bug
    pm:queue
    domain:engine
    on Aug 22, 2026
  3. huangyiirene commented on Aug 22, 2026

    @huangyiirene
    Collaborator

    Triage: lands in packages/drivers/driver-sql (introspectPrimaryKeys, SQLite arm) ⇒ domain:engine, type Bug, queued (pm:queue).

    Grading rationale: measured, mechanical, and self-contained — PRAGMA table_info's pk is a 1-based ordinal, pk === 1 keeps only the first member of a composite key, and both output signals (primaryKeys, isPrimary) are wrong together so no consumer can cross-check its way out. Fix direction is in the card and is not a judgement call: row.pk > 0, push in pk-ordinal order, pin over a real composite-keyed table (the suite has none today); confirm the PG/MySQL arms' missing ORDER BY in the same pass. SqliteWasmDriver inherits the fix for free.

    Notes for the engine seat:


    Generated by Claude Code

  4. added
    pm:dispatched
    and removed
    pm:queue
    on Aug 22, 2026
  5. self-assigned this
    on Aug 22, 2026
  6. os-zhuang commented on Aug 22, 2026

    @os-zhuang
    Contributor

    Claim: PM loop round 1
    Session: session_01RfyXxZ2WPjcjhuXpiQQc3y
    Branch: claude/issue-10997-sqlite-composite-pk
    Worktree: objectstack-issue-10997
    Domain: domain:engine
    File surface: packages/drivers/driver-sql/src/sql-driver.ts (region: introspectPrimaryKeys — SQLite arm at/around :12694, plus the PG/MySQL arms only for the ORDER BY confirmation the card asks for) + a new test over a composite-keyed table (stop on breach; explain in the report)
    Container & model: S, mode:subagent, model: opus (tier per node scripts/pm/dispatch-gates.mjs --tier packages/drivers/driver-sql/src/sql-driver.ts — no path-derived mandate, floor sonnet/default opus; opus because the cross-dialect ordering question is read-and-judge, not gate-decided)
    Clause-②: no — this restores declared-vs-enforced on an existing introspection contract (a composite key is reported completely instead of partially). The accept set is unchanged and no public surface widens.
    Serial constraints cleared: sql-driver.ts is the lane's hot file and this is the fold-or-serial answer. Queued neighbours on the same file — #11009 (by-id predicate refusal) and #10998 (introspectSchema missing dialect/introspectedAt) — are NOT folded into this card and are NOT dispatched this round: five-gate check fails at gate ① (a pk === 1→pk > 0 predicate-and-ordinal repair is a different defect shape and a different fix mechanism from either neighbour, and #10998 additionally carries an unresolved driver-vs-spec routing question). They are serial behind this card. The prior blocker on this file, #10995, has landed — a037f7c on origin/main — so the seat post's "压在 #10995 之后" constraint is cleared. Lane had zero pm:dispatched cards at claim time. Batch siblings #10945/#11020/#11015 are package-disjoint.

    ⚠️ Read-coupling declared: #10676 (packages/services/service-datasource, the isPrimary/primaryKey seam) consumes what this card changes, and is deliberately left in the queue this round rather than dispatched alongside. If work here changes the introspection output shape, say so in the report so #10676 can be re-priced before it is dispatched.

    Premise re-verified live on origin/main @ 4257e4e before dispatch: if (row.pk === 1) is present at sql-driver.ts:12694. Zero-hit control: table_info also matches in the same file, so the grep was live.


    Generated by Claude Code

  7. os-zhuang commented on Aug 22, 2026

    @os-zhuang
    Contributor

    ⛔ Correction to my claim comment above (same session, session_01RfyXxZ2WPjcjhuXpiQQc3y) — one clause in my fold-or-serial rationale was already false when I wrote it.

    I wrote that #10998 "carries an unresolved driver-vs-spec routing question". That question was resolved at 2026-08-22T13:51Z, ~2 hours before my claim: triage unlocked #10998 from pm:blocked to pm:queue on the strength of the #10676 seam ruling (maintainer, live session, 「同意所有」 item 9 — the driver emits the spec shape). I read #10998's label correctly and reported it as queued, then restated a rationale from the older triage prose on this card without re-checking it against #10998's own newer comment. My error, and exactly the failure mode the outgoing seat post warns about: prose that reads authoritative and recent is the easiest kind to inherit unverified.

    The serial decision is unchanged, and does not depend on the false clause. Gate ① fails on its own: a pk === 1→pk > 0 predicate-and-ordinal repair in introspectPrimaryKeys is a different defect shape and a different fix mechanism from emitting dialect/introspectedAt in introspectSchema. #10998 stays queued and serial behind this card.

    What the correction does change — for the next round, not this one. Triage's unlock note pairs #10998 with #10676 as the two halves of one adjudicated driver-side alignment ("one modality and one file surface"), and explicitly says the five-gate fold test plausibly passes for dispatching those two as a single claim. That is a live fold candidate this seat should evaluate next round. Both are queued and unclaimed as of now.

    The read-coupling warning in my claim stands and is now sharper: #10676 is adjudicated and will move the same seam this card touches, so this card's report should still state whether it changed the introspection output shape.


    Generated by Claude Code

  8. os-zhuang commented on Aug 22, 2026

    @os-zhuang
    Contributor
    {
      "issue": 10997,
      "status": "done",
      "branch": "claude/issue-10997-sqlite-composite-pk",
      "pr": "https://github.com/objectstack-ai/objectstack/pull/11104",
      "premise_still_valid": true,
      "summary": "Re-derived the defect independently on origin/main: `if (row.pk === 1)` at sql-driver.ts:12694 (PM's line number confirmed, zero-hit control: `table_info` matches in the same file). Replaced it with `row.pk > 0` plus a numeric sort on the pk ordinal, so `primaryKeys` reports every member of a composite key in declared key order rather than only the first in column order. Added a pin over two real composite-keyed tables. Output SHAPE is unchanged (`IntrospectedTable` still `{name, columns, foreignKeys, primaryKeys}`, `primaryKeys` still `string[]`) — only completeness and order of the values change, so #10676 needs NO repricing; the truncation its `primaryKeyReader` docblock records as 'upstream of this seam and is not repaired here' is now repaired upstream. Stayed inside driver-sql: did not touch service-datasource (#10676) or the `dialect`/`introspectedAt` seam (#10998), and Clause ② was not reached (no declared contract changed, accept set unchanged).",
      "tests": "All evidence at commit 035bcfa73 (union re-run on final head after the changeset landed). RED BASELINE (pin run against unrepaired driver): 3 failed | 1789 passed | 72 skipped — `expected [ 'order_id' ] to deeply equal [ 'order_id', 'line_no' ]`, `expected [ 'shipment_id' ] to deeply equal [ 'shipment_id', 'carrier_code' ]`, `expected [ 'missing_key_member:line_no' ] to deeply equal []`. GREEN: `TEST_EXIT=0`, `Tests 1792 passed | 72 skipped (1864)`; `TYPECHECK_EXIT=0`. Exit codes captured before any pipe (redirect-then-capture), verdict lines quoted from each gate's own output. GATES — all 21 green: the 7 PM-named (check:driver-conformance `OK — 45 covered cell(s), 0 in the DEBT ledger, 0 exempt.`; check:slot-lookup `107 unswept site(s), none new`; check:test-source-alias `OK — 72 packages`; check:type-source-resolution `OK — 77 packages`; check-ci-filter-parity `OK: all 83 declared cross-package glob(s)`; check-plugin-teardown-shape `63 Plugin implementation(s) across 4457 source(s)`; check-affected-docs `339 cases pass`), the 5 changeset-triggered (all exit 0; objectui-changeset `all checks passed`), check:nul-bytes (`75 assertions`, exit 0), plus FIVE families the PM's lead did NOT name, found by re-running `node scripts/pm/dispatch-gates.mjs` with no paths (it derives its own change set from the merge base): check:query-options-erasure (`67 unswept non-test site(s), none new`), check:engine-double-contract (`OK — 377 pinned, 133 in the DEBT ledger, 2 exempt.`), check:where-matcher (`278 matcher(s), 278 answer correctly or refuse loudly`), check:type-check-coverage (`OK — 65/78 workspace packages type-checked`), check:type-check-debt (`--re-measure: OK — 33 ledger entr(ies) re-measured in 388.8s, 1908 raw tsc error(s) total, none above its recorded number`) — the last run against a fully built closure (`turbo run build`, 70/70 successful), since it refuses to measure on an unbuilt worktree. REPO-WIDE `pnpm lint` (`eslint . --no-inline-config`) RUN IN FULL, exit 0, no findings — no narrowing claimed. DOWNSTREAM (read-coupled consumers, prefix filter = downstream direction): driver-sqlite-wasm 395 passed, driver-turso 1006 passed, service-datasource 559 passed. No ablation was performed — the pin's red baseline over the real unrepaired driver is the direct measurement, so no mutation/rebuild leg was needed. DIALECT ARMS: SQLite EXECUTED (better-sqlite3, in-memory). Postgres and MySQL READ ONLY, NOT RUN — unreachability measured, not assumed: no listener on 127.0.0.1/localhost:5432 or :3306, no DSN env var, no `mysql` client, `psql` client present but no server, docker CLI present but `/var/run/docker.sock` absent (`failed to connect to the docker API`).",
      "open_questions": [],
      "out_of_scope_findings": [
        "filed as #11101: the Postgres and MySQL `introspectPrimaryKeys` arms return the key in unspecified row order — `ORDER BY` absent from both. Confirms the card's PG/MySQL question: the PG arm's `a.attnum = ANY(i.indkey)` reads an ordered int2vector as a SET and discards the position; the MySQL arm never selects or orders by `KEY_COLUMN_USAGE.ORDINAL_POSITION`. My call was to scope it OUT rather than land it unexecuted, on evidence rather than convenience: the whole method body sits in `catch { /* silently ignore */ } => []`, so a rewritten query invalid on some server version degrades to NO primary key at all with no diagnostic — turning a cosmetic ordering gap into invisible total loss of the key. Filed unassigned, no label, for PM triage; body flags the silent catch as arguably the more serious finding and deliberately does not fold it in."
      ]
    }

    Generated by Claude Code

  9. os-zhuang commented on Aug 22, 2026

    @os-zhuang
    Contributor

    ACCEPT — PR #11104. ⏳ Landing held until CI converges (not a reservation about the work).

    Reviewer of record: domain:engine seat, os-zhuang, session session_01RfyXxZ2WPjcjhuXpiQQc3y, round 1. Reviewed against the branch and against GitHub, not against the report.

    The fix, verified by me on the branch at 035bcfa73

    const keyedRows = (result as {…}[]).filter((row) => row.pk > 0);
    keyedRows.sort((a, b) => a.pk - b.pk);
    

    Both halves of the ruled direction, present: the ordinal predicate and the ordering. 3 files, all inside driver-sql plus the changeset — scope honoured, service-datasource (#10676) and the dialect/introspectedAt seam (#10998) untouched exactly as instructed.

    ⭐ The read-coupling I declared at claim time is resolved — and resolved in the direction that costs nothing

    I flagged that #10676 consumes what this card changes and asked for the report to state whether the output shape moved. It did not: IntrospectedTable is still {name, columns, foreignKeys, primaryKeys} and primaryKeys is still string[]. Only completeness and order of the values change. #10676 therefore needs no repricing — and better, the truncation its own primaryKeyReader docblock records as "upstream of this seam and is not repaired here" is now repaired upstream. I have noted that on #10676 so whoever picks it up does not re-derive it.

    Why the evidence here is the strongest of this round's three PRs

    • No ablation was performed, and that is the right call, not a gap. The pin was run against the real unrepaired driver first and went red with the exact expected messages — expected [ 'order_id' ] to deeply equal [ 'order_id', 'line_no' ] and two more. A red baseline over real code is a direct measurement; a mutation leg would have been a weaker simulation of it.
    • Repo-wide pnpm lint was run in full — no narrowing claimed. Likewise check:type-check-debt --re-measure against a fully built closure (turbo run build, 70/70), reporting "33 ledger entries re-measured, 1908 raw tsc errors total, none above its recorded number." Both of the narrowings the other two PRs in this round had to declare were simply retired here by doing the work.
    • 21 gate families green, five of which my dispatch list failed to name and the dev found by re-deriving from the tree.
    • Downstream consumers actually exercised: driver-sqlite-wasm 395, driver-turso 1006, service-datasource 559 — so the inherited-fix claim for the subclasses is measured, not asserted.

    Test quality — two things worth naming

    1. It pins the premise, not just the behaviour. There is an assertion that PRAGMA table_info returns {order_id: 1, line_no: 2, sku: 0}, commented "If SQLite ever reported pk as a boolean, the fix below would be wrong." Most fixes of this class pin only the repaired output; this one pins the external fact the repair rests on, so a SQLite behaviour change surfaces as a named failure instead of a mystery.
    2. The drift comparison carries a negative control. After asserting no drift, it asserts that a genuinely different declared key does drift, and that a reordered key drifts as key_order_mismatch. That is the difference between "this assertion is green" and "this assertion could ever be red" — the exact trap the review checklist warns about. There is also a guard against the repair degrading to pk >= 0 (an unkeyed table must report []).

    The dialect arms — reported honestly, which is what I asked for

    SQLite executed. Postgres and MySQL read only, and their unreachability was measured rather than assumed: no listener on :5432/:3306, no DSN env var, no mysql client, psql present but no server, docker CLI present but /var/run/docker.sock absent. That is a real reading, not "I couldn't, so I didn't."

    The scoping call on PG/MySQL ordering — PM concurs, and the reasoning is better than the finding

    The card asked for the PG/MySQL ORDER BY gap to be confirmed in the same pass. It was confirmed (the PG arm's a.attnum = ANY(i.indkey) reads an ordered int2vector as a set and discards position; the MySQL arm never selects ORDINAL_POSITION) and filed as #11101 rather than landed unexecuted.

    I endorse scoping it out, on the dev's evidence rather than on convenience: the whole method body sits inside catch { /* silently ignore */ } => [], so a rewritten query that is invalid on some server version degrades to no primary key at all, with no diagnostic — converting a cosmetic ordering gap into invisible total loss of the key, on arms that could not be executed here. Landing that blind would have been the wrong trade.

    ⚠️ For triage: the silent catch is arguably the more serious finding, and the dev said so rather than burying it. #11101 carries it; I have added the finding label (it was filed bare) and applied no grading.

    Checklist

    item verdict
    clause ② ✅ neither limb — no declared contract changed, accept set unchanged; restores declared-vs-enforced
    ACCEPT path fork (governed) ✅ clean ⇒ ready → merge queue, ⛔ not a human-merge card
    CI ⏳ 11/28 complete, all success, zero failures — this PR started last (17:02Z)

    ⛔ Not flipping to ready yet. On convergence I verify the Fixes #10997 first line myself, flip ready → merge queue, and follow to MERGED.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugdomain:enginepm:dispatched

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions