Repository navigation
Description
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
huangyiirene commentedon Aug 22, 2026
Triage: lands in
packages/drivers/driver-sql(introspectPrimaryKeys, SQLite arm) ⇒domain:engine, typeBug, queued (pm:queue).Grading rationale: measured, mechanical, and self-contained —
PRAGMA table_info'spkis a 1-based ordinal,pk === 1keeps 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 inpk-ordinal order, pin over a real composite-keyed table (the suite has none today); confirm the PG/MySQL arms' missingORDER BYin the same pass.SqliteWasmDriverinherits the fix for free.Notes for the engine seat:
sql-driver.tsalso carries queued A compare-and-setwhereon a by-idupdateis silently inert — the extra predicate keys never reach the driver, andSqlHttpOutbox.redeliver's status guard is one of them #11009 (by-id predicate refusal, different function), queued driver-sql (PG): JSON-field values are bound without JSON.stringify — non-empty arrays and bare strings 500, empty array silently stored as {} #10995 (PG JSON binding), and parked driver-sql:introspectSchema()returns only{ tables }— the specIntrospectedSchemacontract'sdialectand (required)introspectedAtare never emitted #10998 (same seam, blocked on External object-draft drops the introspected primary key (isPrimary vs primaryKey seam) #10676). Fold-or-serial is the seat's five-gate call — these are different defect shapes in one file, so serial with region-level surface declarations is the likely answer, not a fold.external_catalog/ drift comparison) need no separate fix, but the drift-comparison case makes a good second assertion in the pin.Generated by Claude Code
os-zhuang commentedon Aug 22, 2026
Claim: PM loop round 1
Session:
session_01RfyXxZ2WPjcjhuXpiQQc3yBranch:
claude/issue-10997-sqlite-composite-pkWorktree:
objectstack-issue-10997Domain:
domain:engineFile surface:
packages/drivers/driver-sql/src/sql-driver.ts(region:introspectPrimaryKeys— SQLite arm at/around:12694, plus the PG/MySQL arms only for theORDER BYconfirmation 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 pernode 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.tsis 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 (introspectSchemamissingdialect/introspectedAt) — are NOT folded into this card and are NOT dispatched this round: five-gate check fails at gate ① (apk === 1→pk > 0predicate-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 —a037f7conorigin/main— so the seat post's "压在 #10995 之后" constraint is cleared. Lane had zeropm:dispatchedcards at claim time. Batch siblings #10945/#11020/#11015 are package-disjoint.packages/services/service-datasource, theisPrimary/primaryKeyseam) 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@4257e4ebefore dispatch:if (row.pk === 1)is present atsql-driver.ts:12694. Zero-hit control:table_infoalso matches in the same file, so the grep was live.Generated by Claude Code
os-zhuang commentedon Aug 22, 2026
⛔ 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:blockedtopm:queueon 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 > 0predicate-and-ordinal repair inintrospectPrimaryKeysis a different defect shape and a different fix mechanism from emittingdialect/introspectedAtinintrospectSchema. #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
os-zhuang commentedon Aug 22, 2026
{ "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
os-zhuang commentedon Aug 22, 2026
ACCEPT — PR #11104. ⏳ Landing held until CI converges (not a reservation about the work).
Reviewer of record:
domain:engineseat,os-zhuang, sessionsession_01RfyXxZ2WPjcjhuXpiQQc3y, round 1. Reviewed against the branch and against GitHub, not against the report.The fix, verified by me on the branch at
035bcfa73Both halves of the ruled direction, present: the ordinal predicate and the ordering. 3 files, all inside
driver-sqlplus the changeset — scope honoured,service-datasource(#10676) and thedialect/introspectedAtseam (#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:
IntrospectedTableis still{name, columns, foreignKeys, primaryKeys}andprimaryKeysis stillstring[]. Only completeness and order of the values change. #10676 therefore needs no repricing — and better, the truncation its ownprimaryKeyReaderdocblock 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
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.pnpm lintwas run in full — no narrowing claimed. Likewisecheck:type-check-debt --re-measureagainst 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.Test quality — two things worth naming
PRAGMA table_inforeturns{order_id: 1, line_no: 2, sku: 0}, commented "If SQLite ever reportedpkas 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.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 topk >= 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, nomysqlclient,psqlpresent but no server, docker CLI present but/var/run/docker.sockabsent. 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 BYgap to be confirmed in the same pass. It was confirmed (the PG arm'sa.attnum = ANY(i.indkey)reads an orderedint2vectoras a set and discards position; the MySQL arm never selectsORDINAL_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.findinglabel (it was filed bare) and applied no grading.Checklist
⛔ Not flipping to ready yet. On convergence I verify the
Fixes #10997first line myself, flip ready → merge queue, and follow to MERGED.Generated by Claude Code
fix(driver-sql): introspectPrimaryKeys returns the PG and MySQL key i…
fix(driver-sql): introspectPrimaryKeys returns the PG and MySQL key i…
docs(service-datasource): make the primaryKeyReader docblock true aga…
fix(service-datasource): emit the authorised `ObjectSchema.create` sh…