Skip to content

Commit 850bcec

Browse files
feat(driver-sql): compare the share-grant subquery by the key's type on PostgreSQL (ADR-0155 O2, ruling A) (#35967)
Fixes #35906 <!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao8mXHQniWvfYM2uHoosm2Da)_ Refs #33787 Clause-②: yes The compiled share-grant subquery changes its SQL on PostgreSQL for a key that is not text, and keeps ADR-0155 D-0's same rows (ruled A). A behaviour change in its own right: on a `character(n)` key the subquery silently missed padded ids under step 3's SQL (the list answered `[k1, k2]`, the leaf `[k2]`); the `bpchar` cast makes it answer the list's rows. No producer writes the leaf before step 6, so no reader has seen the miss. Metadata-protocol: none ## 维护者速读 - 问题:用户暂时无感。PostgreSQL 上主键是数字、uuid 或定长字符的外部表,新的共享子查询要么直接报错,要么悄悄漏掉被共享的记录;今天按名单读的结果是对的。 - 这一步做什么:属于「共享记录不再被五千条上限截断」这项工作,落实维护者选定的「按主键类型比较」:驱动第一次遇到这张表时读一次它的主键类型并记住,子查询按这个类型比较,读出的记录与今天按名单读的完全相同。 - 不做会怎样:最后一步切换后,这类外部表上被共享的人会读不到记录或直接报错;在那之前没有任何地方写入这种条件,所以这一步出错也碰不到用户,可以直接撤回。 - 要你做的:无。Oracle 上以十六字节二进制存 uuid 的外部表这次无法实测,按代码推断会报错,已按你裁的 A 另开 #35952 补上(第 6 步等它);MySQL 和 SQL Server 只核对了编译出的语句,按厂商文档结果相同。 ## What changes On PostgreSQL, the `SharedRecordIds` subquery now compares `record_id` as the outer key's own type. This is ADR-0155's O2, ruled A on the decision card. - **The statement.** The inner read projects `record_id` cast to the base type of the column it is compared with: `id IN (SELECT CAST(NULLIF(record_id, '') AS "pg_catalog"."int4") FROM sys_record_share WHERE …)`. A domain is cast to the type under it. The cast carries no typmod, the way a bound list member has none, so a long value is compared and never truncated. The `WHERE` is step 3's, unchanged. - A `text` or `varchar` key takes no cast and compiles to step 3's exact statement. That covers every table the platform creates. - `NULLIF(record_id, '')` keeps the cast total on a blank grant if a planner evaluates the projection before the blank-id guard. NULL is in no `IN` set, so the set is unchanged. - **The type.** `fixed-read-leaf-key-type.ts` (new) reads each column's base type of the compared table from `pg_catalog` (`pg_attribute`, with domains walked down through `pg_type.typbasetype`). It reads once per physical table, as `getBuilder` addresses it, and caches the answer for the life of the driver's knex client. - The filter compiler is synchronous, so the read happens before it. Every door that compiles a `where` calls `primeFixedReadLeafKeyTypes` beside its existing catalog primes (`primeMssqlGuidColumns`): `findRows`, `count`, `updateMany`, `deleteMany`, `aggregate` (and each joined parent), `distinct`, `analyzeQuery` and the window-function read. - The prime walks the `where` for a leaf in a field's `$in`. A statement with no leaf costs a walk and no read. It reads the door object's table, and the parent table of any composed `ReadableIds` scope the leaf sits in. - The prime reads nothing on any dialect other than PostgreSQL. - A failed read records nothing. So does an empty one, where the relation is not visible to the pooled connection yet. The next door asks again. - **No reading, no statement (L2 F1).** "No reading" is kept apart from "read: a text key". On PostgreSQL a leaf compared with a table the driver holds no reading of is refused in ADR-0139 D3's envelope (`INTERNAL_ERROR` / 500, logged once per knex client) and never compiled uncast, which on a `character(n)` key would miss a padded grant silently. A table has no reading when no door primed it, or when the catalog read failed or found no such relation. A type name knex cannot bind as one identifier is refused the same way. - **Read where the statement runs (L2 S1, ADR-0155 D-0).** A door in the caller's transaction reads the catalog on that transaction's own connection, inside a savepoint (a knex nested transaction), using the door's options. A pool the transaction holds cannot time the read out, a table the transaction created is read, and a failed read rolls back the savepoint alone, so the caller's transaction stays usable. That reading is kept for that transaction only, because it may describe a table that never commits. It reaches every savepoint derived from that transaction (knex's `parentTransaction`), so `updateMany` on an object whose `updated_at` is only presumed, which retries its stamped write in a savepoint `attemptWithoutPoisoning` opens, compiles with it (delta-2 L1 R1 / L2 S2); a savepoint's own reading never reaches its parent. Each transaction pays one savepoint and one catalog read per table it compares a leaf against. While that savepoint is open, knex runs the caller's other concurrent statements on the transaction inside it, so a failed catalog read rolls back a concurrent write made during the read (named in the prime's docblock, carried to step 6). A door with no transaction reads on the pool, as before. - `aggregate` primes its `where` and its per-measure `filter`s together, as the SQL Server prime does (L1 N1). - **The compile site.** The `$in` arm passes the outer object, column and evaluator name to `fixedReadLeafSubquery`, which looks up the reading: a cast, no cast (a text key), or a refusal (no reading). `sql-driver.ts` changes on two existing lines (the private stub's signature) and stays at 10067 of its 10071-line ceiling. - **Step 3's L2 nit N3.** The `fixedReadLeaves` comment said "every dialect". It now says the leaf compiles on every dialect and gives the same rows as the id list on SQLite and PostgreSQL only. - **Unchanged:** the leaf's position, the inner read's predicates, the absence of a tenant scope inside the subquery (① ruled A), the refusal envelope (`INTERNAL_ERROR` / 500), and Turso's remote transport. That transport reads only `fixedInnerReadPredicates`, which is untouched, and it is SQLite. No producer writes the leaf. ### Read these first (risk order) 1. `packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts`, `primeFixedReadLeafKeyTypes` and `COLUMN_BASE_TYPES_SQL`. These are the catalog read and its cache key. The risk is a table keyed differently in the prime and in the compile, which refuses every leaf on that table. 2. `packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts`, `fixedReadLeafSubquery`. This is the cast's only emission point and the no-reading refusal. The risk is a cast on a text key, which would change step 3's statement. 3. The door hunks (`sql-driver-crud.ts`, `sql-driver-bulk-operations.ts`, `sql-driver-aggregation.ts`, …). The risk is a door that compiles a `where` without priming it, which now refuses every leaf there; each door is pinned as a fresh driver's first statement. ## Why ADR-0155 D-0: "**An outer key of another type answers the same rows.** Where an object's `id` column is not a string, the subquery answers the rows today's list answers (O2)." The maintainer's ruling (option A) reads: "So `driver-sql` casts `record_id` to the outer key's base type on PostgreSQL. The type is read once per object from the catalog and cached. The result is the same rows as today's id list for integer and uuid keys, with a pin per type on live PG." Federated PostgreSQL tables are sharing-scoped, so this is reachable the moment step 6 (#33787) writes the leaf. ## Tests <details><summary>Measured on live PostgreSQL 16.15 before and after the change: today's list against the leaf, per key type</summary> The before readings are at `170ca481f0` and the after readings at `7c8cf753aa` (built locally on 170ca48, replayed onto main 523ada4 as `f00b6312c7` / `0f3e1d467e` with identical `git patch-id --stable`; no driver-sql file changed on main in between). Each table is a raw-DDL table bound with `registerExternalObject`. | key | grants | list (today) | leaf before | leaf after | |---|---|---|---|---| | `integer` | `42`, `07`, ` 7` | `[42, 7]` | `DATABASE_ERROR` / 500 (42883) | `[42, 7]` | | `bigint` | `07`, `9007199254740993` | `[7, 9007199254740993]` | 500 | same as list | | `smallint` | `7` | `[7]` | 500 | `[7]` | | `numeric(10,2)` | `7`, `8.50` | `[7.00, 8.50]` | 500 | same as list | | `uuid` | upper-case, braced | both rows | 500 | both rows | | domain over `integer` | `07`, `42` | `[42, 7]` | 500 | `[42, 7]` | | `character(4)` | `k1` plus two spaces, `k2` | `[k1, k2]` | **`[k2]`: a silent miss** | `[k1, k2]` | | `varchar(10) COLLATE "C"` | `k1`, `K2` | `[k1]` | `[k1]` | `[k1]` (no cast) | | `text` | `k1`, `k2` plus a space | `[k1]` | `[k1]` | `[k1]` (no cast) | | `integer`, grant `abc` | | `DATABASE_ERROR` / 500, 22P02 | 500 | `DATABASE_ERROR` / 500, 22P02 | | `uuid`, grant `not-a-uuid` | | `DATABASE_ERROR` / 500, 22P02 | 500 | `DATABASE_ERROR` / 500, 22P02 | The `character(n)` row is a silent miss under step 3's statement: the list compares as `bpchar`, which ignores padding, while the column-to-column comparison compares as text. Casting to `bpchar` fixes it. </details> New pins: - `sql-driver-fixed-read-leaf-conformance.test.ts`, in the PostgreSQL cell: eight key types (`integer`, `smallint`, `numeric(10,2)`, `bigint`, `uuid` bound through a remote schema, `character(4)`, a domain over `integer`, and `text`). - Each type checks four things against today's list: `find` + `count`, the negation and an `$or` position, the predicate update (the write form through `updateMany`), and the compiled statement. A cast is present for each non-text key, and `text` compiles step 3's statement byte for byte. - Four more pins: the nested position under a composed `ReadableIds` scope, `aggregate`, a malformed grant id, and the read count. The malformed-id pin asserts `code` + `status` equal to the list's, with 22P02 and not 42883. The read-count pin asserts one catalog read per table, nothing on a second statement or another verb, and nothing for a statement with no leaf. - Each table also holds a blank grant (N4's witness), which the cast never sees as a value. - **Each door primes for itself (L1 R1).** `count`, `updateMany`, `deleteMany`, `distinct`, `aggregate`, the aggregate's joined parent, `analyzeQuery` and `findWithWindowFunctions` each run as the FIRST statement of a fresh `SqlDriver` on the `character(4)` key, asserting the list's rows or count and the `bpchar` cast in every statement that reads the grants. - **In the caller's transaction (L2 S1).** (a) A pool of one connection, held by the caller's transaction, with a 1s acquire timeout: `find`, `count` and `updateMany` answer the list's rows, every grant-reading statement carries the `bpchar` cast, and nothing is logged. (b) A `character(4)` table created in the caller's uncommitted transaction: the list and the leaf both answer `[k1]`, with the cast. (c) The catalog read fails inside the transaction (a test seam turns it into `select 1/0`, a real PostgreSQL error inside the savepoint): `find` and `count` are refused with `INTERNAL_ERROR` / 500, logged once. The caller's transaction then still runs `select 1` and a list read, and with the seam removed the next leaf statement answers the list's rows. (d) On a fresh driver, a managed object over a table it did not create (`updated_at` presumed), text and `character(4)` keys: a predicate `updateMany` with the write-form leaf in a caller transaction answers the list's rows, touches them, settles the presumption, and the `character(4)` statement carries the cast. At `99e085ec96` both (d) pins were red with `INTERNAL_ERROR` / 500 (no reading). - `fixed-read-leaf-key-type.test.ts` (new, no server): the prime and the compile through a never-dialled PostgreSQL driver whose catalog read is stubbed. - It covers the read's bindings for a bare table and a schema-qualified one, the compiled statement byte for byte, the cache, and that the cast adds no parameter. - It covers the text and varchar keys, an unbindable type name (refused), no reading at all and the failed and empty reads (each refused with `INTERNAL_ERROR` / 500, logged once, nothing recorded, asked again), a column the read table lacks (no cast), a read in a savepoint on the caller's transaction (kept for that transaction only, refused outside it, nothing recorded when it fails), a savepoint derived from the transaction reaching its reading and never the reverse, a `where` with no leaf, the `ReadableIds` and `$or` positions, and no read on SQLite, MySQL or SQL Server. - The per-dialect compiled-statement pin now primes PostgreSQL through a stubbed catalog read first, and a sibling pin asserts an unprimed PostgreSQL compile is refused. <details><summary>Package suite and typecheck at 7c8cf753aa (code head; c9a3ef2d8f adds only the changeset and the anchor)</summary> ``` driver-sql pnpm --filter @objectstack/driver-sql test (OS_TEST_POSTGRES_URL set; PG server TimeZone Asia/Shanghai, process TZ America/New_York) Test Files 277 passed | 4 skipped (281) Tests 5747 passed | 133 skipped (5880) VERDICT command-exit 0 live-dialect block: sqlite RAN · live postgres RAN · live mysql NOT RUN typecheck pnpm --filter @objectstack/driver-sql typecheck VERDICT command-exit 0 (tsc --listFiles names both new files: 2) driver-turso vitest run src/turso-fixed-read-leaf-conformance.test.ts, against a rebuilt driver-sql dist Tests 54 passed (54) VERDICT command-exit 0 eslint --no-inline-config over the 12 changed .ts files: exit 0 ``` </details> <details><summary>Fix round, at 7f4974a (the F1 code; c7cc4e2 changes only the new pins' option typing)</summary> ``` driver-sql TZ=America/New_York OS_TEST_POSTGRES_URL=… pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2 Test Files 277 passed | 4 skipped (281) Tests 5767 passed | 133 skipped (5900) VERDICT command-exit 0 (a first run with the process at UTC failed only the four three-way-zone-skew assertions, which require a skewed process zone) at c7cc4e2: the two changed test files, live PG Tests 135 passed | 1 skipped (136) VERDICT command-exit 0 typecheck pnpm --filter @objectstack/driver-sql typecheck VERDICT command-exit 0 eslint --no-inline-config over the changed .ts files: exit 0 check:query-options-erasure: test surface 236 sites, at the ceiling (the 7f4974a head read 241; the five erased transaction bags are now typed DriverOptions) ``` </details> <details><summary>Delta-2 round (R1 / S2), at 1e61bf8</summary> ``` driver-sql TZ=America/New_York OS_TEST_POSTGRES_URL=… pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2 Test Files 277 passed | 4 skipped (281) Tests 5772 passed | 133 skipped (5905) VERDICT command-exit 0 the two changed test files, live PG: 140 passed | 1 skipped (141) typecheck, eslint --no-inline-config packages/drivers/driver-sql/src: exit 0 check:query-options-erasure: exit 0, test surface 236, at the ceiling ``` </details> <details><summary>S1 round, at 99e085e</summary> ``` driver-sql TZ=America/New_York OS_TEST_POSTGRES_URL=… pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2 Test Files 277 passed | 4 skipped (281) Tests 5769 passed | 133 skipped (5902) VERDICT command-exit 0 the two changed test files, live PG Tests 137 passed | 1 skipped (138) VERDICT command-exit 0 typecheck pnpm --filter @objectstack/driver-sql typecheck VERDICT command-exit 0 eslint --no-inline-config packages/drivers/driver-sql/src: exit 0 check:query-options-erasure: exit 0, test surface 236, at the ceiling ``` </details> **Ablation (round 1).** One mutation, made after the code was committed, through `scripts/ablation-replace.mjs`. The compile site's projection `cast === null ? read.column : castFixedReadLeafColumn(…)` was replaced with `read.column`, so no cast is emitted. The prediction was 29 failed: 5 of 9 in the unit file, and 24 PostgreSQL pins in the conformance file (four per non-text key, plus the nested, aggregate, malformed-id and read-count pins). The observed result was `29 failed | 86 passed | 1 skipped (116)`. The malformed-id pin's failure reads `expected '42883' to match /22P02…/`, which is step 3's error. The tool restored the file to the HEAD blob `f584fa2998e7`, `git diff HEAD` was empty, and `git hash-object` matched `git rev-parse HEAD:path`. **Ablations (fix round), each through `scripts/ablation-replace.mjs` after the commit, each restored to the HEAD blob with `git diff HEAD` empty.** | mutation | predicted red | observed | |---|---|---| | `count`'s prime removed | its door pin | 1 failed, 121 passed, 1 skipped (123) | | `updateMany`'s prime removed | its door pin | 1 failed, 121 passed, 1 skipped | | `deleteMany`'s prime removed | its door pin | 1 failed, 121 passed, 1 skipped | | `distinct`'s prime removed | its door pin | 1 failed, 121 passed, 1 skipped | | `aggregate`'s prime removed | its door pin | 1 failed, 121 passed, 1 skipped (the first attempt was a no-op: the replacement did not parse; redone) | | the aggregate's joined-parent prime removed | its door pin | 1 failed, 121 passed, 1 skipped | | `analyzeQuery`'s prime removed | its door pin | 1 failed, 121 passed, 1 skipped | | `findWithWindowFunctions`' prime removed | its door pin | 1 failed, 121 passed, 1 skipped | | `findRows`' prime removed | 15 (7 non-text keys x 2, plus the read-count pin) | 15 failed, 107 passed, 1 skipped | | the parent-chain walk removed (a savepoint sees only its own readings; R1, after commit `1e61bf84ed`) | 3: the unit derived-savepoint pin and live (d) text and `character(4)` | 3 failed, 137 passed, 1 skipped (141). Both (d) pins answered `INTERNAL_ERROR` / 500 (no reading) | | the catalog read moved back to the pool in a transaction (S1, after commit `99e085ec96`) | 4: the unit transaction pin and live (a), (b), (c) | 4 failed, 133 passed, 1 skipped (138). (a) and (b) answered `INTERNAL_ERROR` / 500 (no reading); (c) answered the rows instead of the refusal | | the no-reading refusal disabled (`fixedReadLeafSubquery` compiles uncast) | 5: two unit pins, the compiled-statement refusal, live (a) and (b) | 5 failed, 130 passed, 1 skipped (136). Unrefused, (a) answers `[k2 ]` where the list answers `[k1 , k2 ]`, and (b) answers `[]` where the list answers `[k1 ]`: the silent miss F1 names | The door ablations ran under the R1 round's commit `707ffb5cc2`, before the F1 refusal existed: a missed prime then compiled uncast and missed silently, which is what each door pin caught. ## Acceptance notes - **The dialects `driver-sql` ships (O2, per the seat note).** | dialect | how | result | |---|---|---| | PostgreSQL 16 | live, a private local cluster | the same rows as the list, for every key type in the table above | | SQLite | live | unchanged statement. The same rows by column affinity (step 3's INTEGER pin, still green) | | MySQL | compiled SQL pinned, unchanged | **left.** There is no server here, and the CI live cell runs on push only. By the documentation, an integer key compared with a string compares as double for the list and the subquery alike. A federated table whose collation differs from `sys_record_share`'s may raise "illegal mix of collations", which is loud | | SQL Server | compiled SQL pinned, unchanged | **left.** There is no server and no CI cell. By data-type precedence, `nvarchar` converts to `int` or `uniqueidentifier`, the same conversion the list's `nvarchar` binds get | | Oracle | compiled SQL pinned, unchanged | **left, and by reading not the same rows for a `RAW(16)` uuid key.** The list binds `HEXTORAW` over the undashed hex (`oracleUuidRawBinding`) and refuses a non-uuid with `INVALID_FILTER` / 400. The subquery's implicit conversion of a dashed uuid is expected to raise ORA-01465, which is loud. A `NUMBER` key converts the way the list's binds do. Ruling A applied to Oracle is filed as #35952 (seat 7, 2026-11-20T22:56Z), and #33787 is `Blocked-by: #35952`; this PR does not refuse it | - **The C-assumptions, measured.** - C1: the key type is not reachable at compile time without a read, so it is primed per door, on the MSSQL-GUID prime's precedent. The cache is per knex client, keyed by the physical table, and nothing invalidates it. The driver never retypes a key column, and DDL made elsewhere is not observable, as with the Oracle and SQL Server primes. - C2: the catalog read is `pg_attribute` plus `pg_type` with a recursive domain walk. An array key is cast to its array type (unmeasured, no consumer). A malformed id matches the list: 22P02, `DATABASE_ERROR` / 500. - C3: the pins are above. - C5: the new code lives in a sibling module, and `sql-driver.ts` stays at 10067. - C6: Turso is unaffected, confirmed by reading and by its conformance suite against the rebuilt dist (54/54). - C7: N3 is fixed. - **The step 3 changeset** (`.changeset/35872-shared-record-ids-sql-compile.md`, not yet released) still says the PostgreSQL non-text case "is open". This PR's changeset states the change. The old note was not edited. - **Not measured locally:** the live MySQL cell has no server here. - **What is left for step 6 (#33787).** The saturated pool and the table created in the caller's transaction now answer the list's rows (S1), so neither is a precondition any more. What remains: on PostgreSQL, a leaf statement whose catalog read itself fails (on the pool, or in the savepoint) or finds no such relation is refused with `INTERNAL_ERROR` / 500 where step 3 ran it uncast. That holds for text keys too, whose compiled statement is otherwise step 3's. Nothing writes the leaf yet, so no caller meets it. Also for step 6: each transaction pays one savepoint and one catalog read per table it compares a leaf against (a transaction's reading is never promoted), and a failed catalog read inside a caller's transaction rolls back any write the caller ran concurrently on that transaction during the read. - **Sweep: every place that compiles a `where` under transaction options other than the ones its door primed with.** `grep -n 'applyFilters('` over `driver-sql/src` (non-test) finds 12 call sites. All compile under the options their door primed with except `sql-driver-bulk-operations.ts:326` (`updateMany`'s `issue`, given a savepoint by `updateWithPresumedTimestamp`), which is R1 and is now covered. The composed-scope site (`sql-driver-internal-helpers.ts:145`) and `sql-driver-latest-per.ts:133` (reached only from `findRows` with its options) compile with the door's own options. `grep` for derived transaction options (`{ ...options, transaction: … }`, `.transaction(async`, `attemptWithoutPoisoning(`) finds four other sites: `bulkUpdate` (`sql-driver-bulk-operations.ts:268`, which goes to `update` by id), `upsert` (`sql-driver-sequence-semantics.ts:842`, `:853`) and the autonumber sequence (`sql-driver-autonumber.ts:193`). None of them calls `applyFilters`, so none can compile a leaf. ## Verification Two minutes, with a PostgreSQL URL: ``` OS_TEST_POSTGRES_URL=postgres://… pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2 src/fixed-read-leaf-key-type.test.ts src/sql-driver-fixed-read-leaf-conformance.test.ts ``` Expect `140 passed | 1 skipped (141)`, where the skip is the MySQL cell. Without the URL, the unit file still runs its 12 tests, and the live PostgreSQL pins report NOT RUN. <details><summary>Local gates at 1e61bf8: 80 derived families, each exit code captured before any pipe</summary> The list comes from `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`. `--ran` reconciles it as `80 derived famil(ies) accounted for — 80 run, 0 NOT-MEASURED`. - All 80 exited 0 on the first pass. (At c7cc4e2, `check:dts-closure` and `check:dual-build-cjs-loads` first exited 1 on a missing `packages/plugins/organizations/dist/index.d.ts`, because an overlapping earlier gate run of mine was rebuilding that package, which this PR does not touch; after a rebuild both exited 0.) Among them, `check:tenant-chokepoint` reported "every unscoped one is an insert or one of 1 EXEMPT entr(ies)". `check:facade-delegation-only` reported "4 file(s) within their line ceiling". Also green: `check:adr-anchors`, `check:nul-bytes`, `check:driver-conformance`, `check:test-source-alias`, `check:where-matcher`, `check:durability-log-level`, `check:doc-authoring` and `check:dts-closure`. - At the first head (c9a3ef2d8f), `check:dual-build-cjs-loads` and `check:lean-entry-closure` exited 3 (PREREQUISITE NOT MET); at c7cc4e2, 99e085e and 1e61bf8 both exit 0. - `node scripts/pm/overlap-check.mjs --branch=claude/project-thread-thptm0`: "origin/main (9ed18a5): merges cleanly", VERDICT clean, exit 0. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz <!-- signed: repo:objectstack#7 · os-tesla · session_01L9qibyXo4gSy8DJPNz4ANz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f9f45d3 commit 850bcec

14 files changed

Lines changed: 1217 additions & 14 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
feat(driver-sql): on PostgreSQL the share-grant subquery compares `record_id` as the outer key's own type (ADR-0155 O2)
6+
7+
Clause-②: yes
8+
Metadata-protocol: none
9+
10+
No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step, and this makes that step safe on PostgreSQL tables whose key is not text.
11+
12+
- **PostgreSQL, a key that is not text.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `record_id` cast to the base type of the column it is compared with: `CAST(NULLIF(record_id, '') AS <type>)`. A federated table keyed by `integer`, `bigint`, `smallint`, `numeric`, `uuid`, `character(n)` or a domain over one of them answers the same rows as the id list of the same grants: `07` names 7, an upper-case or braced uuid names its lower-case twin, and a padded grant names a `character(n)` key. Before, an integer or uuid key failed the statement with `DATABASE_ERROR` (42883), and a `character(n)` key silently missed a padded grant.
13+
- **A malformed grant id** (`abc` against an integer key) fails the statement with `DATABASE_ERROR` / 500, the same answer the id list gives for it.
14+
- **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and outside a transaction keeps the answer for the life of the driver (inside one, see the next bullet). A statement with no leaf reads nothing. A failed or empty catalog read records nothing and is asked again by the next statement.
15+
- **No reading, no statement.** On PostgreSQL a statement whose leaf is compared with a table the driver holds no catalog reading of is refused with `INTERNAL_ERROR` / 500 (logged once), and never runs uncast, which on a `character(n)` key would miss a padded grant silently. A table has no reading when the catalog read fails or finds no such relation; nothing is recorded, and the next statement reads the catalog again.
16+
- **Read where the statement runs.** A statement in the caller's transaction reads the catalog on that transaction's own connection, inside a savepoint: it needs no second pooled connection, it sees a table the transaction created, and a failed read rolls back the savepoint alone, so the caller's transaction stays usable. That reading is kept for that transaction only, and reaches every savepoint derived from it, so a write the driver itself retries in a savepoint (an `updateMany` on an object whose `updated_at` column is only presumed) compiles with it; a reading a savepoint takes never reaches its parent. Each transaction therefore pays one savepoint and one catalog read per table it compares a leaf against. A statement outside a transaction reads on the pool and the reading is kept for the life of the driver.
17+
- **Unchanged, and what text keys get.** A `text` or `varchar` key, which is every table the platform creates, compiles to exactly step 3's statement, with no cast. What is new for it: the first leaf statement on that table (once per driver, or once per transaction inside one) is preceded by the catalog read, and if that read fails, or finds no such relation, the statement is refused with `INTERNAL_ERROR` / 500 instead of being run. SQLite, MySQL, SQL Server and Oracle compile exactly as before and read no catalog; SQLite answers the list's rows by column affinity. MySQL and SQL Server keys are not measured against a live server yet. An Oracle `RAW(16)` uuid key is expected to fail the statement (ORA-01465, by reading: the subquery converts a dashed uuid grant to `RAW` implicitly, where the id list binds its undashed hex); it is not measured, and is tracked on #35952.
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0155 O2, ruled A] `fixed-read-leaf-key-type.ts` without a server: what
5+
* the catalog prime reads, what it records, and the statement the filter
6+
* compiler then emits. Each driver here is configured and never dialled; the
7+
* PostgreSQL catalog read is answered by a stub on the knex client. The live
8+
* pins per key type are in `sql-driver-fixed-read-leaf-conformance.test.ts`
9+
* (the PostgreSQL cell).
10+
*/
11+
12+
import { describe, it, expect, vi } from 'vitest';
13+
import type { Knex } from 'knex';
14+
import { ReadableIds, SharedRecordIds, type DriverOptions, type FilterCondition } from '@objectstack/spec/data';
15+
import { SqlDriver, type SqlDriverConfig } from './sql-driver.js';
16+
import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js';
17+
18+
const EXT = 'srid_ext';
19+
const CHILD = 'srid_child';
20+
21+
class Probe extends SqlDriver {
22+
/** The prime, through this driver's own `getBuilder`, as a door calls it. */
23+
prime(object: string, where: unknown, options?: DriverOptions): Promise<void> {
24+
return primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, object, where, options);
25+
}
26+
compile(object: string, where: unknown, options?: DriverOptions): { sql: string; bindings: readonly unknown[] } {
27+
const builder: Knex.QueryBuilder = this.getBuilder(object);
28+
this.applyFilters(builder, where, options);
29+
const native = builder.toSQL().toNative();
30+
return { sql: native.sql, bindings: native.bindings };
31+
}
32+
}
33+
34+
const PG: SqlDriverConfig = { client: 'pg', connection: {} } as unknown as SqlDriverConfig;
35+
36+
/** A never-dialled PostgreSQL probe whose catalog read answers `answer` (rows, or a thrown error). */
37+
function pgProbe(answer: () => unknown): { probe: Probe; raw: ReturnType<typeof vi.fn> } {
38+
const probe = new Probe(PG);
39+
const client = (probe as any).knex.client as { raw: (...args: unknown[]) => unknown };
40+
const original = client.raw.bind(client);
41+
// Only the catalog read is answered here; every other raw (the cast itself) is knex's own.
42+
const raw = vi.fn(async (..._args: unknown[]) => answer());
43+
client.raw = (...args: unknown[]) => (String(args[0]).includes('pg_attribute') ? raw(...args) : original(...args));
44+
return { probe, raw };
45+
}
46+
47+
/** The refusal envelope ADR-0139 D3 names: `INTERNAL_ERROR` / 500, the statement never compiled. */
48+
function expectRefused(run: () => unknown, why: string): void {
49+
let caught: unknown;
50+
try { run(); } catch (err) { caught = err; }
51+
expect(caught, 'refused').toBeInstanceOf(Error);
52+
expect((caught as { code?: unknown }).code).toBe('INTERNAL_ERROR');
53+
expect((caught as { status?: unknown }).status).toBe(500);
54+
expect((caught as Error).message).toContain(why);
55+
}
56+
57+
const row = (column_name: string, type_schema: string, type_name: string) => ({ column_name, type_schema, type_name });
58+
const leafWhere = (object = EXT) => ({ id: { $in: SharedRecordIds.read(object, 'u9') } });
59+
60+
describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read', () => {
61+
it('an integer key: one catalog read, then the inner read casts record_id to int4', async () => {
62+
const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4'), row('label', 'pg_catalog', 'text')] }));
63+
await probe.prime(EXT, leafWhere());
64+
expect(raw).toHaveBeenCalledTimes(1);
65+
expect(raw.mock.calls[0][1]).toEqual([EXT]);
66+
const { sql, bindings } = probe.compile(EXT, leafWhere());
67+
expect(sql).toBe(
68+
'select * from "srid_ext" where "id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."int4") from "sys_record_share" '
69+
+ 'where "object_name" = $1 and "recipient_type" = $2 and "recipient_id" = $3 and "record_id" is not null and "record_id" <> $4)',
70+
);
71+
// The cast adds no parameter: the inner read binds what step 3's does.
72+
expect(bindings).toEqual([EXT, 'user', 'u9', '']);
73+
// Recorded once per table: the next door reads nothing.
74+
await probe.prime(EXT, leafWhere());
75+
expect(raw).toHaveBeenCalledTimes(1);
76+
});
77+
78+
it('an external object with a remote schema and table is read and keyed by its physical name', async () => {
79+
const { probe, raw } = pgProbe(() => ({ rows: [row('ext_id', 'pg_catalog', 'uuid')] }));
80+
probe.registerExternalObject({ name: EXT, fields: {}, external: { remoteName: 'remote_t', remoteSchema: 'crm', columnMap: { ext_id: 'id' } } } as any);
81+
await probe.prime(EXT, leafWhere());
82+
expect(raw.mock.calls[0][0]).toContain("format('%I.%I', ?::text, ?::text)");
83+
expect(raw.mock.calls[0][1]).toEqual(['crm', 'remote_t']);
84+
expect(probe.compile(EXT, leafWhere()).sql).toContain(
85+
'"ext_id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."uuid") from "sys_record_share"',
86+
);
87+
});
88+
89+
it('a text or varchar key takes no cast: step 3\'s statement, byte for byte', async () => {
90+
for (const type of ['text', 'varchar']) {
91+
const { probe } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', type)] }));
92+
await probe.prime(EXT, leafWhere());
93+
expect(probe.compile(EXT, leafWhere()).sql).toContain('"id" in (select "record_id" from "sys_record_share"');
94+
}
95+
});
96+
97+
it('a type name knex cannot bind as one identifier is refused, never cast or left uncast', async () => {
98+
const { probe } = pgProbe(() => ({ rows: [row('id', 'odd.schema', 'int4')] }));
99+
await probe.prime(EXT, leafWhere());
100+
expectRefused(() => probe.compile(EXT, leafWhere()), 'cannot bind as one identifier');
101+
});
102+
103+
it('no reading is refused (INTERNAL_ERROR / 500, logged once), never compiled uncast; a failed or empty read records nothing and the next door asks again', async () => {
104+
let answer: () => unknown = () => { throw new Error('catalog unavailable'); };
105+
const { probe, raw } = pgProbe(() => answer());
106+
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() };
107+
(probe as any).logger = logger;
108+
// Never primed: no reading at all.
109+
expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading');
110+
// The catalog read failed (a pooled connection's acquire timeout is one).
111+
await probe.prime(EXT, leafWhere());
112+
expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading');
113+
// The relation is not visible to the pooled connection (an uncommitted CREATE).
114+
answer = () => ({ rows: [] });
115+
await probe.prime(EXT, leafWhere());
116+
expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading');
117+
// Logged at error once for this client; the caller saw all three.
118+
expect(logger.error).toHaveBeenCalledTimes(1);
119+
expect(String(logger.error.mock.calls[0][0])).toContain("[driver-sql] the $in of column 'id' of 'srid_ext' holds a SharedRecordIds leaf");
120+
expect(String(logger.error.mock.calls[0][0])).not.toContain('u9');
121+
answer = () => ({ rows: [row('id', 'pg_catalog', 'int8')] });
122+
await probe.prime(EXT, leafWhere());
123+
expect(raw).toHaveBeenCalledTimes(3);
124+
expect(probe.compile(EXT, leafWhere()).sql).toContain('AS "pg_catalog"."int8"');
125+
});
126+
127+
it('in a transaction the catalog is read in a savepoint on it, and the reading is kept for that transaction only', async () => {
128+
const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] }));
129+
const savepointRaw = vi.fn(async (..._args: unknown[]) => ({ rows: [row('id', 'pg_catalog', 'int8')] }));
130+
// A stand-in for the caller's knex transaction: `transaction(handler)` opens the savepoint.
131+
const savepoints = vi.fn(async (handler: (sp: { raw: typeof savepointRaw }) => unknown) => handler({ raw: savepointRaw }));
132+
const trx = Object.assign(() => undefined, { transaction: savepoints });
133+
const inTrx: DriverOptions = { transaction: trx };
134+
await probe.prime(EXT, leafWhere(), inTrx);
135+
expect(raw).not.toHaveBeenCalled();
136+
expect(savepoints).toHaveBeenCalledTimes(1);
137+
expect(savepointRaw.mock.calls[0][1]).toEqual([EXT]);
138+
// Read once per table for this transaction.
139+
await probe.prime(EXT, leafWhere(), inTrx);
140+
expect(savepoints).toHaveBeenCalledTimes(1);
141+
expect(probe.compile(EXT, leafWhere(), inTrx).sql).toContain('AS "pg_catalog"."int8"');
142+
// Outside that transaction there is no reading: refused, never the transaction's.
143+
expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading');
144+
// A failed savepoint read records nothing for the transaction either.
145+
const failing = Object.assign(() => undefined, { transaction: vi.fn(async () => { throw new Error('savepoint rolled back'); }) });
146+
const inFailing: DriverOptions = { transaction: failing };
147+
await probe.prime(EXT, leafWhere(), inFailing);
148+
expectRefused(() => probe.compile(EXT, leafWhere(), inFailing), 'holds no reading');
149+
});
150+
151+
it('a savepoint derived from the transaction reaches the transaction\'s reading; the transaction never reaches a savepoint\'s', async () => {
152+
const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] }));
153+
const fakeTrx = (rows: unknown[], parentTransaction?: unknown) => {
154+
const savepointRaw = vi.fn(async () => ({ rows }));
155+
return Object.assign(() => undefined, {
156+
transaction: vi.fn(async (handler: (sp: { raw: typeof savepointRaw }) => unknown) => handler({ raw: savepointRaw })),
157+
...(parentTransaction === undefined ? {} : { parentTransaction }),
158+
});
159+
};
160+
const parent = fakeTrx([row('id', 'pg_catalog', 'int8')]);
161+
const inParent: DriverOptions = { transaction: parent };
162+
await probe.prime(EXT, leafWhere(), inParent);
163+
// `attemptWithoutPoisoning`'s shape: a savepoint knex links to its parent.
164+
const derived = fakeTrx([row('id', 'pg_catalog', 'uuid')], parent);
165+
const inDerived: DriverOptions = { transaction: derived };
166+
expect(probe.compile(EXT, leafWhere(), inDerived).sql).toContain('AS "pg_catalog"."int8"');
167+
await probe.prime(EXT, leafWhere(), inDerived);
168+
expect(derived.transaction).not.toHaveBeenCalled();
169+
// A reading a savepoint took is never its parent's.
170+
const other = fakeTrx([row('id', 'pg_catalog', 'int8')]);
171+
const sibling = fakeTrx([row('id', 'pg_catalog', 'uuid')], other);
172+
await probe.prime(EXT, leafWhere(), { transaction: sibling });
173+
expect(sibling.transaction).toHaveBeenCalledTimes(1);
174+
expectRefused(() => probe.compile(EXT, leafWhere(), { transaction: other }), 'holds no reading');
175+
expect(raw).not.toHaveBeenCalled();
176+
});
177+
178+
it('a column the read table does not have takes no cast: the database names the missing column itself', async () => {
179+
const { probe } = pgProbe(() => ({ rows: [row('label', 'pg_catalog', 'text')] }));
180+
await probe.prime(EXT, leafWhere());
181+
expect(probe.compile(EXT, leafWhere()).sql).toContain('"id" in (select "record_id" from "sys_record_share"');
182+
});
183+
184+
it('a where with no leaf reads nothing', async () => {
185+
const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] }));
186+
await probe.prime(EXT, { id: { $in: ['7', '42'] }, label: 'x' });
187+
await probe.prime(EXT, undefined);
188+
expect(raw).not.toHaveBeenCalled();
189+
});
190+
191+
it('a leaf under a composed ReadableIds scope primes the parent object\'s table, and is cast there', async () => {
192+
const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] }));
193+
const where = { parent: { $in: ReadableIds.compose(ReadableIds.of(EXT), leafWhere() as unknown as FilterCondition) } };
194+
await probe.prime(CHILD, where);
195+
expect(raw).toHaveBeenCalledTimes(1);
196+
expect(raw.mock.calls[0][1]).toEqual([EXT]);
197+
const { sql } = probe.compile(CHILD, where);
198+
expect(sql).toContain('"parent" in (select "id" from "srid_ext" where "id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."int4")');
199+
});
200+
201+
it('a leaf in an $or group is cast too (the group compiles on a builder with no table of its own)', async () => {
202+
const { probe } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] }));
203+
const where = { $or: [leafWhere(), { label: 'x' }] };
204+
await probe.prime(EXT, where);
205+
expect(probe.compile(EXT, where).sql).toContain('"id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."int4")');
206+
});
207+
208+
it('every other dialect reads no catalog and compiles step 3\'s statement', async () => {
209+
const configs: Record<string, SqlDriverConfig> = {
210+
sqlite: { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as SqlDriverConfig,
211+
mysql: { client: 'mysql2', connection: {} } as unknown as SqlDriverConfig,
212+
mssql: { client: 'mssql', connection: {}, schemaMode: 'external' } as unknown as SqlDriverConfig,
213+
};
214+
for (const [dialect, config] of Object.entries(configs)) {
215+
const probe = new Probe(config);
216+
const client = (probe as any).knex.client as { raw: (...args: unknown[]) => unknown };
217+
const raw = vi.spyOn(client, 'raw');
218+
await probe.prime(EXT, leafWhere());
219+
expect(raw, dialect).not.toHaveBeenCalled();
220+
expect(probe.compile(EXT, leafWhere()).sql, dialect).not.toMatch(/CAST\(/);
221+
await probe.disconnect?.();
222+
}
223+
});
224+
});

0 commit comments

Comments
 (0)