Skip to content

Commit 1e61bf8

Browse files
committed
fix(driver-sql): a savepoint derived from the caller's transaction reaches its key-type reading (ADR-0155 D-0, O2)
updateMany on an object whose updated_at is only presumed issues its stamped attempt in a savepoint attemptWithoutPoisoning opens on the caller's transaction, so the leaf compiled under a transaction object the door never primed under and was refused (500) on every write, text keys included. The lookup and the prime now walk knex's parentTransaction chain: a savepoint sees what its parent sees, so the parent's reading holds there; a savepoint's own reading never reaches its parent. Live PG pin: on a fresh driver, a managed object in the presumed updated_at state, text and character(4) keys, a predicate updateMany with the write-form leaf in a caller transaction answers the list's rows and touches them. The changeset, the anchor and the prime's docblock say so, and the docblock names the savepoint's effect on concurrent statements on the same transaction. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude <noreply@anthropic.com>
1 parent 99e085e commit 1e61bf8

5 files changed

Lines changed: 116 additions & 7 deletions

File tree

‎.changeset/35906-pg-share-grant-key-type.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The s
1111

1212
- **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.
1313
- **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 keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed or empty catalog read records nothing and is asked again by the next statement.
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.
1515
- **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. A statement outside a transaction reads on the pool and the reading is kept for the life of the driver.
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.
1717
- **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.

‎packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,33 @@ describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read
148148
expectRefused(() => probe.compile(EXT, leafWhere(), inFailing), 'holds no reading');
149149
});
150150

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+
151178
it('a column the read table does not have takes no cast: the database names the missing column itself', async () => {
152179
const { probe } = pgProbe(() => ({ rows: [row('label', 'pg_catalog', 'text')] }));
153180
await probe.prime(EXT, leafWhere());

‎packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@
5050
* transaction created, it needs no second pooled connection (a pool the
5151
* transaction holds cannot time it out), and a failed read rolls back the
5252
* savepoint alone, never the caller's transaction. That reading is kept
53-
* for that transaction only (it may describe a table that never commits).
53+
* for that transaction, and the savepoints derived from it, only (it may
54+
* describe a table that never commits).
5455
* A door with no transaction reads on the pool and keeps the reading for
5556
* the knex client's life.
5657
*
@@ -112,6 +113,24 @@ const castsByClient = new WeakMap<object, Map<string, ReadonlyMap<string, Column
112113
/** Per caller transaction: the readings taken on its own connection, which may describe tables it has not committed. */
113114
const castsByTransaction = new WeakMap<object, Map<string, ReadonlyMap<string, ColumnReading>>>();
114115

116+
/**
117+
* A transaction's reading of a table, or one an ENCLOSING transaction took:
118+
* a savepoint derived from the caller's transaction (knex's
119+
* `parentTransaction`, as `attemptWithoutPoisoning` opens for the presumed
120+
* `updated_at` write) runs on the same connection and sees what its parent
121+
* sees, so the parent's reading holds there. Never the reverse: a reading a
122+
* savepoint took may describe a table that rolls back with it.
123+
*/
124+
function transactionReading(trx: Knex.Transaction, key: string): ReadonlyMap<string, ColumnReading> | undefined {
125+
const seen = new Set<object>();
126+
for (let at: Knex.Transaction | undefined = trx; at !== undefined && !seen.has(at); at = at.parentTransaction) {
127+
seen.add(at);
128+
const columns = castsByTransaction.get(at)?.get(key);
129+
if (columns !== undefined) return columns;
130+
}
131+
return undefined;
132+
}
133+
115134
/** Per knex client: whether a no-reading refusal was logged (once per client, its own flag). */
116135
const refusalLogByClient = new WeakMap<object, { logged: boolean }>();
117136

@@ -194,7 +213,10 @@ function collectLeafKeyObjects(node: unknown, object: string, out: Set<string>,
194213
* cast `record_id` to the key's base type (see the module docblock). A no-op
195214
* on every dialect but PostgreSQL, and for a `where` holding no leaf.
196215
* `options.transaction`, when present, is where the catalog is read: on the
197-
* caller's connection, inside a savepoint.
216+
* caller's connection, inside a savepoint. While that savepoint is open, knex
217+
* runs the caller's other concurrent statements on the same transaction
218+
* inside it, so a catalog read that fails rolls back a concurrent write the
219+
* caller made on that transaction during the read.
198220
*/
199221
export async function primeFixedReadLeafKeyTypes(
200222
source: FixedReadLeafKeySource,
@@ -215,7 +237,7 @@ export async function primeFixedReadLeafKeyTypes(
215237
const schema = typeof builder._single?.schema === 'string' ? builder._single.schema : undefined;
216238
const key = tableKey(schema, table);
217239
if (cacheOf(client).has(key)) continue;
218-
if (trx !== undefined && castsByTransaction.get(trx)?.has(key)) continue;
240+
if (trx !== undefined && transactionReading(trx, key) !== undefined) continue;
219241
let rows: { column_name: string; type_schema: string; type_name: string }[];
220242
try {
221243
const relation = schema === undefined ? `format('%I', ?::text)` : `format('%I.%I', ?::text, ?::text)`;
@@ -274,7 +296,7 @@ export function fixedReadLeafKeyReading(
274296
): FixedReadLeafKeyReading {
275297
const key = tableKey(schema, table);
276298
const trx = savepointHost(transaction);
277-
const columns = castsByClient.get(client)?.get(key) ?? (trx === undefined ? undefined : castsByTransaction.get(trx)?.get(key));
299+
const columns = castsByClient.get(client)?.get(key) ?? (trx === undefined ? undefined : transactionReading(trx, key));
278300
if (columns === undefined) return { kind: 'unread' };
279301
const reading = columns.get(column);
280302
if (reading === undefined || reading === null) return { kind: 'uncast' };

‎packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,66 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo
757757
await fresh.disconnect?.();
758758
}
759759
});
760+
761+
/**
762+
* `updateMany` on a managed object whose `updated_at` is only presumed
763+
* issues its stamped attempt inside a savepoint DERIVED from the
764+
* caller's transaction (`updateWithPresumedTimestamp` →
765+
* `attemptWithoutPoisoning`), so the leaf compiles under a transaction
766+
* object the door did not prime under: the reading taken on the
767+
* caller's transaction must reach it.
768+
*/
769+
describe('(d) the presumed-updated_at write path compiles in a savepoint derived from the caller\'s transaction', () => {
770+
const PRESUMED = [
771+
{ table: 'srid_pk_presumed_text', ddl: 'text', grants: ['k1', 'k2'], expected: ['k1', 'k2'], cast: false },
772+
{ table: 'srid_pk_presumed_char', ddl: 'character(4)', grants: ['k1 ', 'k2'], expected: ['k1 ', 'k2 '], cast: true },
773+
] as const;
774+
775+
beforeAll(async () => {
776+
const driver = driverOf();
777+
const knex = knexOf();
778+
for (const p of PRESUMED) {
779+
await driver.execute(`drop table if exists ${p.table}`);
780+
await driver.execute(`create table ${p.table} (id ${p.ddl} primary key, label text, created_at timestamptz default now(), updated_at timestamptz default now())`);
781+
await knex(p.table).insert([{ id: 'k1', label: 'x' }, { id: 'k2', label: 'x' }, { id: 'k3', label: 'x' }]);
782+
await knex(GRANTS).insert(p.grants.map((g, i) => ({ id: `${p.table}_g${i}`, object_name: p.table, recipient_type: 'user', recipient_id: 'u9', record_id: g, access_level: 'lvl_edit', organization_id: 'org_a' })));
783+
}
784+
});
785+
786+
afterAll(async () => {
787+
const driver = driverOf();
788+
const knex = knexOf();
789+
for (const p of PRESUMED) {
790+
await knex(GRANTS).where('object_name', p.table).del().catch(() => {});
791+
await driver.execute(`drop table if exists ${p.table}`).catch(() => {});
792+
}
793+
});
794+
795+
for (const p of PRESUMED) {
796+
it(`${p.ddl} key: a predicate updateMany with the write-form leaf answers the list's rows and touches them`, async () => {
797+
const fresh = new SqlDriver(PG_CELL.config());
798+
// Managed metadata over a table this driver did not create: `updated_at` is presumed.
799+
fresh.registerObjectMetadata([{ name: p.table, fields: { label: { type: 'text' } } } as any]);
800+
expect((fresh as any).updatedAtStampIsPresumed(p.table)).toBe(true);
801+
const trx = await fresh.beginTransaction();
802+
try {
803+
const statements = grantStatementsOf(trx);
804+
const where = seamed({ id: { $in: SharedRecordIds.write(p.table, 'u9', ['lvl_edit', 'lvl_full']) } });
805+
expect(await fresh.updateMany(p.table, { where }, { label: 'touched' }, inTrx(trx))).toBe(p.expected.length);
806+
expect(sortedIds(await trx(p.table).where('label', 'touched').select('id'))).toEqual([...p.expected]);
807+
// The list's rows, read in the same transaction after the write.
808+
expect(sortedIds(await fresh.find(p.table, { where: seamed({ id: { $in: [...p.grants] } }) }, inTrx(trx)))).toEqual([...p.expected]);
809+
// The stamped attempt landed, so the presumption settled.
810+
expect((fresh as any).updatedAtStampIsPresumed(p.table)).toBe(false);
811+
expect(statements.length).toBeGreaterThanOrEqual(1);
812+
for (const sql of statements) expect(sql.includes(CAST)).toBe(p.cast);
813+
} finally {
814+
await trx.rollback();
815+
await fresh.disconnect?.();
816+
}
817+
});
818+
}
819+
});
760820
});
761821

762822
it('reads the catalog once per table: a second statement and another verb ask it nothing', async () => {

‎scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@
33
"adrs": [
44
"ADR-0155"
55
],
6-
"invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the catalog read failed or found no relation) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. A door in the caller's transaction reads the catalog on that transaction's connection inside a savepoint (so a held pool cannot time it out, a table the transaction created is read, and a failed read leaves the transaction usable) and keeps that reading for that transaction only; with no transaction it reads on the pool. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver."
6+
"invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the catalog read failed or found no relation) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. A door in the caller's transaction reads the catalog on that transaction's connection inside a savepoint (so a held pool cannot time it out, a table the transaction created is read, and a failed read leaves the transaction usable) and keeps that reading for that transaction and the savepoints derived from it (knex `parentTransaction`, as the presumed-`updated_at` write path's `attemptWithoutPoisoning` opens), never the reverse; with no transaction it reads on the pool. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver."
77
}

0 commit comments

Comments
 (0)