Skip to content

Commit 972c3ec

Browse files
committed
fix(plugin-audit, objectql): a run or sealer pass locks a shared database once and never waits on itself
Two datasources can reach one lock namespace: one Postgres database, or two schemas of one MySQL server, whose GET_LOCK names are server-wide. The audit seal lock opened one session per driver, so the second session found the lock held by the first: every sealer pass skipped for good, and an --apply run waited ten minutes on itself and refused. A lock taken with `ownLocks` now marks its session with a lock under a name no other session knows, taken before the named lock. A later session of the same run that finds the named lock held asks the database whether the session holding it there is the marked one (pg_locks in the current database; on MySQL, IS_USED_LOCK of the marker against the name), and if so answers that lock. A holder it cannot prove its own stays contention, as before. holdAuditSealLock now tries every database once before any wait, so a database that offers no session lock is refused before a wait on another. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq
1 parent fbdc0b8 commit 972c3ec

7 files changed

Lines changed: 393 additions & 44 deletions

File tree

‎.changeset/31908-p4b3-audit-seal-lock.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
feat(plugin-audit, cli)!: an `os migrate audit-* --apply` run holds the audit seal lock for its whole run, each sealer pass skips while it is held, and where the database offers no session lock a run on a sealed object needs `--sealer-stopped`
88

9-
Clause-②: yes (narrowing) — narrowed: `os migrate audit-key-material`, `os migrate audit-mail-bodies` and `os migrate audit-metadata-bodies` with `--apply` now refuse a run that rewrites an object declaring `lifecycle.seal` when that object's database offers no session lock (SQLite, Turso) unless `--sealer-stopped` is passed, and on Postgres or MySQL refuse when a sealer pass or another run still holds the audit seal lock after ten minutes; 18.4.0 ran both. `os migrate audit-side-copies`, new in this release, holds the lock and takes the flag from its first release. Widened: the `--sealer-stopped` flag, and new exports — `@objectstack/objectql` `acquireDatabaseSessionLock`, `tryDatabaseSessionLock`, `databaseSessionLockPgKey` and the types `DatabaseSessionLock`, `DatabaseSessionLockWait`; `@objectstack/plugin-audit` `holdAuditSealLock`, `AUDIT_SEAL_LOCK_NAME`, `AUDIT_SEAL_LOCK_WAIT_MS`, `STORED_METADATA_BODY_REWRITTEN_OBJECTS` and the types `AuditSealLockEngine`, `AuditSealLockFinish`, `AuditSealLockHold`.
9+
Clause-②: yes (narrowing) — narrowed: `os migrate audit-key-material`, `os migrate audit-mail-bodies` and `os migrate audit-metadata-bodies` with `--apply` now refuse a run that rewrites an object declaring `lifecycle.seal` when that object's database offers no session lock (SQLite, Turso) unless `--sealer-stopped` is passed, and on Postgres or MySQL refuse when a sealer pass or another run still holds the audit seal lock after ten minutes; 18.4.0 ran both. `os migrate audit-side-copies`, new in this release, holds the lock and takes the flag from its first release. Widened: the `--sealer-stopped` flag, and new exports — `@objectstack/objectql` `acquireDatabaseSessionLock`, `tryDatabaseSessionLock`, `databaseSessionLockPgKey` and the types `DatabaseSessionLock`, `DatabaseSessionLockRunOptions`, `DatabaseSessionLockWait`; `@objectstack/plugin-audit` `holdAuditSealLock`, `AUDIT_SEAL_LOCK_NAME`, `AUDIT_SEAL_LOCK_WAIT_MS`, `STORED_METADATA_BODY_REWRITTEN_OBJECTS` and the types `AuditSealLockEngine`, `AuditSealLockFinish`, `AuditSealLockHold`.
1010
Metadata-protocol: none
1111

1212
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the moved answer is whether an os migrate audit-* --apply run may proceed while a sealer could be sealing the rows it rewrites. The one-line fix for a refused run is in the body: stop the servers that seal the database and pass --sealer-stopped, or let the sealer pass finish. -->
@@ -18,6 +18,7 @@ Metadata-protocol: none
1818
- Each sealer pass takes it beside the cluster lock `audit.sealer`. While another session holds it, the pass seals nothing and says so at `info`, once an hour while it lasts; the next pass tries again. A checkpoint is written only while both locks still stand: a lock whose database session ended fails the object's pass, and the seed it had sealed is dropped.
1919
- An `--apply` rewrite (`os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies`) holds it from before its first write to after its last, archive runs included. A run whose lock's database session ended before it finished says so, names `os audit verify`, and exits non-zero.
2020
- Two replicas with no cluster service now also keep their passes apart through this lock on Postgres and MySQL.
21+
- Two datasources that reach one lock namespace — one Postgres database, or two schemas of one MySQL server — share one lock: a pass or a run takes it once there and never waits on itself.
2122
- On MySQL, lock names are server-wide: a rewrite on one database of a server makes the sealer of another database on that server skip its passes while it runs.
2223

23-
**`@objectstack/objectql`.** The schema-migration lock and the audit seal lock share one implementation of a named database session lock, now exported: `acquireDatabaseSessionLock` (wait, then refuse), `tryDatabaseSessionLock` (once, never waiting: the lock, `'held'`, or `null` where the database offers none) and `databaseSessionLockPgKey`. A held lock's `isHeld()` asks its own session whether it still stands. `acquireSchemaMigrationLock` takes the same statements, prints the same lines and refuses with the same message as before.
24+
**`@objectstack/objectql`.** The schema-migration lock and the audit seal lock share one implementation of a named database session lock, now exported: `acquireDatabaseSessionLock` (wait, then refuse), `tryDatabaseSessionLock` (once, never waiting: the lock, `'held'`, or `null` where the database offers none) and `databaseSessionLockPgKey`. A held lock's `isHeld()` asks its own session whether it still stands. With `ownLocks` (`DatabaseSessionLockRunOptions`), a run that locks several datasources marks each session it opens, and a lock it finds held by one of its own sessions in the same database answers that lock instead of `'held'` or a wait. `acquireSchemaMigrationLock` takes the same statements, prints the same lines and refuses with the same message as before.

‎packages/objectql/src/database-session-lock.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,67 @@ describe('acquireDatabaseSessionLock: a lock of another name waits and refuses i
171171
]);
172172
});
173173
});
174+
175+
describe('ownLocks: a run that locks several datasources never contends with itself (review 6894679963 M1)', () => {
176+
/** A key's `pg_locks` `classid` and `objid`: its high and low 32 bits, unsigned. */
177+
const halves = (key: string) => {
178+
const unsigned = BigInt.asUintN(64, BigInt(key));
179+
return [(unsigned >> 32n).toString(), (unsigned & 0xffffffffn).toString()];
180+
};
181+
const SEEN_PG = /^select exists \(select 1 from pg_locks m join pg_locks l on l\.pid = m\.pid and l\.database = m\.database where /;
182+
183+
it('without it, no marker: the schema-migration lock\'s statements are unchanged', async () => {
184+
const f = fakeDriver('postgres', () => ({ locked: false }));
185+
await expect(tryDatabaseSessionLock(f.driver, NAME)).resolves.toBe('held');
186+
expect(f.statements.map((s) => s.sql)).toEqual(['select pg_try_advisory_lock(?::bigint) as locked']);
187+
});
188+
189+
it('Postgres: the run\'s session takes a marker of its own before the lock; a later session finding the lock held asks whether the marked session holds it in THIS database, and answers that lock', async () => {
190+
const first = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : { locked: true }));
191+
const own = await tryDatabaseSessionLock(first.driver, NAME, { ownLocks: [] });
192+
const [mark, lock] = first.statements;
193+
expect([mark.sql, lock.sql]).toEqual(['select pg_try_advisory_lock(?::bigint) as marked', 'select pg_try_advisory_lock(?::bigint) as locked']);
194+
const markerKey = String(mark.bindings[0]);
195+
expect(markerKey).not.toBe(KEY);
196+
197+
const second = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : SEEN_PG.test(sql) ? { seen: true } : { locked: false }));
198+
await expect(tryDatabaseSessionLock(second.driver, NAME, { ownLocks: [own as never] })).resolves.toBe(own);
199+
const seen = second.statements.find((s) => SEEN_PG.test(s.sql))!;
200+
expect(seen.sql).toContain('m.database = (select oid from pg_database where datname = current_database())');
201+
expect(seen.bindings).toEqual([...halves(markerKey), ...halves(KEY)]);
202+
expect(second.destroyed).toEqual([second.connection]);
203+
});
204+
205+
it('⛔ a held lock the marked session does not hold is contention, as before: "held", and the wait for acquire', async () => {
206+
const first = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : { locked: true }));
207+
const own = await tryDatabaseSessionLock(first.driver, NAME, { ownLocks: [] });
208+
const other = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : SEEN_PG.test(sql) ? { seen: false } : { locked: false }));
209+
await expect(tryDatabaseSessionLock(other.driver, NAME, { ownLocks: [own as never] })).resolves.toBe('held');
210+
const timedOut = Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });
211+
const waiting = fakeDriver('postgres', (sql) =>
212+
sql.endsWith('as marked') ? { marked: true } : SEEN_PG.test(sql) ? { seen: false } : sql.startsWith('select pg_try') ? { locked: false } : sql.startsWith('select pg_advisory_lock') ? timedOut : {});
213+
const onWait = vi.fn();
214+
const refusal = new Error('refused');
215+
await expect(acquireDatabaseSessionLock(waiting.driver, { name: NAME, waitMs: 1_000, onWait, refuse: () => refusal, ownLocks: [own as never] }))
216+
.rejects.toBe(refusal);
217+
expect(onWait).toHaveBeenCalledTimes(1);
218+
});
219+
220+
it('MySQL: the connection holding the run\'s marker holds the name, server-wide — acquire answers the run\'s lock with no wait and no line', async () => {
221+
const first = fakeDriver('mysql', (sql) => (sql.endsWith('as marked') ? { marked: 1 } : { locked: 1 }));
222+
const own = await tryDatabaseSessionLock(first.driver, NAME, { ownLocks: [] });
223+
const markerName = String(first.statements[0].bindings[0]);
224+
expect(first.statements[0].sql).toBe('select GET_LOCK(?, 0) as marked');
225+
expect(markerName.length).toBeLessThanOrEqual(64);
226+
const second = fakeDriver('mysql', (sql) => (sql.endsWith('as marked') ? { marked: 1 } : sql.endsWith('as seen') ? { seen: 1 } : { locked: 0 }));
227+
const onWait = vi.fn();
228+
await expect(acquireDatabaseSessionLock(second.driver, { name: NAME, waitMs: 1_000, onWait, refuse: () => new Error('no'), ownLocks: [own as never] }))
229+
.resolves.toBe(own);
230+
expect(second.statements.map((s) => [s.sql, s.bindings]).slice(1)).toEqual([
231+
['select GET_LOCK(?, 0) as locked', [NAME]],
232+
['select IS_USED_LOCK(?) = IS_USED_LOCK(?) as seen', [markerName, NAME]],
233+
]);
234+
expect(onWait).not.toHaveBeenCalled();
235+
expect(second.destroyed).toEqual([second.connection]);
236+
});
237+
});

‎packages/objectql/src/database-session-lock.ts‎

Lines changed: 125 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
* Its own module, importing nothing but `node:crypto`, so the pins on it load
2121
* the lock and not the engine around it.
2222
*/
23-
import { createHash } from 'node:crypto';
23+
import { createHash, randomUUID } from 'node:crypto';
2424

2525
/**
2626
* The Postgres advisory-lock key of a lock named `name`: the first 8 bytes of
@@ -57,6 +57,65 @@ export interface DatabaseSessionLock {
5757
isHeld(): Promise<boolean>;
5858
}
5959

60+
/**
61+
* The options of a lock that one run takes on several datasources under one
62+
* name ({@link tryDatabaseSessionLock}, {@link acquireDatabaseSessionLock}).
63+
*/
64+
export interface DatabaseSessionLockRunOptions {
65+
/**
66+
* The locks of the same name this run already holds on other datasources,
67+
* each taken with this option too. Passing it — empty for the run's first —
68+
* marks the new session as the run's, so that a later lock of the run can
69+
* tell it from another holder.
70+
*
71+
* Two datasources can reach one lock namespace: a Postgres advisory lock is
72+
* database-wide and a MySQL `GET_LOCK` name server-wide, so two datasources
73+
* on one Postgres database, or on two schemas of one MySQL server, share the
74+
* lock while each opens its own session. Without this, the run's second
75+
* session finds the lock held — by the run's first — and the run contends
76+
* with itself for good. With it, a lock found held is first checked against
77+
* these: when one of them holds it in the same namespace, the new session is
78+
* closed and THAT lock is answered, the database already being under it.
79+
* The check proves the namespace and never guesses it (see `heldAmong`), so
80+
* a holder it cannot prove its own is contention, as before.
81+
*/
82+
readonly ownLocks?: readonly DatabaseSessionLock[];
83+
}
84+
85+
/**
86+
* The marker a session of a run holds beside its named lock: a second session
87+
* lock under a name no other session can know. Seen held from another
88+
* session, it proves that session shares the marked session's namespace.
89+
*/
90+
interface LockMarker {
91+
readonly name: string;
92+
readonly pgKey: string;
93+
}
94+
95+
/** The marker of each lock taken with {@link DatabaseSessionLockRunOptions.ownLocks}. */
96+
const markers = new WeakMap<DatabaseSessionLock, LockMarker>();
97+
98+
/** A Postgres key's `classid` and `objid` in `pg_locks`: its high and low 32 bits, unsigned. */
99+
function pgLockHalves(pgKey: string): [string, string] {
100+
const unsigned = BigInt.asUintN(64, BigInt(pgKey));
101+
return [(unsigned >> 32n).toString(), (unsigned & 0xffffffffn).toString()];
102+
}
103+
104+
/**
105+
* Whether the session that holds a marker (its key's two halves, granted in
106+
* the CURRENT database) also holds the named lock (its two halves) there.
107+
*/
108+
const PG_HELD_BY_MARKED =
109+
'select exists (select 1 from pg_locks m join pg_locks l on l.pid = m.pid and l.database = m.database ' +
110+
"where m.locktype = 'advisory' and m.granted and m.objsubid = 1 " +
111+
'and m.database = (select oid from pg_database where datname = current_database()) ' +
112+
'and m.classid::bigint = ?::bigint and m.objid::bigint = ?::bigint ' +
113+
"and l.locktype = 'advisory' and l.granted and l.objsubid = 1 " +
114+
'and l.classid::bigint = ?::bigint and l.objid::bigint = ?::bigint) as seen';
115+
116+
/** The same on MySQL, server-wide: the connection holding the marker holds the named lock (`NULL` when either is free). */
117+
const MYSQL_HELD_BY_MARKED = 'select IS_USED_LOCK(?) = IS_USED_LOCK(?) as seen';
118+
60119
/** The single row a lock statement answers, whichever client shaped the result. */
61120
function lockRow(result: unknown): Record<string, unknown> | undefined {
62121
// pg answers `{ rows }`; mysql2 answers `[rows, fields]`.
@@ -71,7 +130,17 @@ interface LockSession {
71130
close(): Promise<void>;
72131
/** Try once, without waiting. */
73132
tryLock(): Promise<boolean>;
74-
held(): DatabaseSessionLock;
133+
/**
134+
* Take this session's marker, BEFORE its named lock: a MySQL older than
135+
* 5.7.5 keeps one `GET_LOCK` per session and lets the earlier go, so there
136+
* the marker is the one dropped — the run then reads its own lock as
137+
* contention, as without markers — and never the named lock. `null` when
138+
* the marker could not be taken; the lock is then simply unmarked.
139+
*/
140+
mark(): Promise<LockMarker | null>;
141+
/** The lock of `own` whose session this session sees holding the named lock here: it already covers this namespace. */
142+
heldAmong(own: readonly DatabaseSessionLock[]): Promise<DatabaseSessionLock | undefined>;
143+
held(marker: LockMarker | null): DatabaseSessionLock;
75144
}
76145

77146
/**
@@ -120,9 +189,33 @@ async function openLockSession(driver: unknown, name: string): Promise<LockSessi
120189
: await run('select GET_LOCK(?, 0) as locked', [name]);
121190
return tried?.locked === true || Number(tried?.locked) === 1;
122191
},
123-
held() {
192+
async mark() {
193+
// A name of its own per session, the same length every time (MySQL caps a name at 64 characters).
194+
const marker = { name: `objectstack:lock-session:${randomUUID()}`, pgKey: '' };
195+
marker.pgKey = databaseSessionLockPgKey(marker.name);
196+
const tried = pg
197+
? await run('select pg_try_advisory_lock(?::bigint) as marked', [marker.pgKey])
198+
: await run('select GET_LOCK(?, 0) as marked', [marker.name]);
199+
return tried?.marked === true || Number(tried?.marked) === 1 ? marker : null;
200+
},
201+
async heldAmong(own) {
202+
// Exact, never a guess: the database itself answers that the session holding the named lock in
203+
// THIS namespace holds the marker only `lock`'s session took — on Postgres in this database
204+
// (`pg_locks` lists every database of the cluster), on MySQL on this server. Session ids are never
205+
// compared across sessions of the run: two servers number their sessions alike.
206+
for (const lock of own) {
207+
const marker = markers.get(lock);
208+
if (!marker) continue;
209+
const seen = pg
210+
? await run(PG_HELD_BY_MARKED, [...pgLockHalves(marker.pgKey), ...pgLockHalves(pgKey)])
211+
: await run(MYSQL_HELD_BY_MARKED, [marker.name, name]);
212+
if (seen?.seen === true || Number(seen?.seen) === 1) return lock;
213+
}
214+
return undefined;
215+
},
216+
held(marker) {
124217
let held = true;
125-
return {
218+
const lock: DatabaseSessionLock = {
126219
release: async () => {
127220
if (!held) return;
128221
held = false;
@@ -142,6 +235,8 @@ async function openLockSession(driver: unknown, name: string): Promise<LockSessi
142235
}
143236
},
144237
};
238+
if (marker) markers.set(lock, marker);
239+
return lock;
145240
},
146241
};
147242
}
@@ -150,28 +245,38 @@ async function openLockSession(driver: unknown, name: string): Promise<LockSessi
150245
* Take the lock named `name` on `driver`'s database if it is free, once,
151246
* never waiting and never printing: the lock, `'held'` when another session
152247
* holds it (this session is closed again), or `null` when the database offers
153-
* no session lock ({@link openLockSession}). A statement that fails is handed
248+
* no session lock ({@link openLockSession}). With `options.ownLocks`, a lock
249+
* found held by one of those in this database's namespace answers that lock
250+
* ({@link DatabaseSessionLockRunOptions}). A statement that fails is handed
154251
* on as it is, the session closed — never read as free or as held.
155252
*/
156-
export async function tryDatabaseSessionLock(driver: unknown, name: string): Promise<DatabaseSessionLock | 'held' | null> {
253+
export async function tryDatabaseSessionLock(
254+
driver: unknown,
255+
name: string,
256+
options: DatabaseSessionLockRunOptions = {},
257+
): Promise<DatabaseSessionLock | 'held' | null> {
157258
const session = await openLockSession(driver, name);
158259
if (!session) return null;
260+
let marker: LockMarker | null = null;
261+
let own: DatabaseSessionLock | undefined;
159262
let locked: boolean;
160263
try {
264+
if (options.ownLocks) marker = await session.mark();
161265
locked = await session.tryLock();
266+
if (!locked && options.ownLocks) own = await session.heldAmong(options.ownLocks);
162267
} catch (error) {
163268
await session.close();
164269
throw error;
165270
}
166271
if (!locked) {
167272
await session.close();
168-
return 'held';
273+
return own ?? 'held';
169274
}
170-
return session.held();
275+
return session.held(marker);
171276
}
172277

173278
/** How a waiting lock speaks: its one wait line and its refusal are the caller's words. */
174-
export interface DatabaseSessionLockWait {
279+
export interface DatabaseSessionLockWait extends DatabaseSessionLockRunOptions {
175280
/** The lock's name: MySQL's `GET_LOCK` name, and the source of its Postgres key. */
176281
readonly name: string;
177282
/** How long to wait for another session to let go before refusing. */
@@ -185,7 +290,9 @@ export interface DatabaseSessionLockWait {
185290
/**
186291
* Take the lock named `wait.name` on `driver`'s database, waiting up to
187292
* `wait.waitMs` for another session to let go, or `null` when the database
188-
* offers no session lock ({@link openLockSession}).
293+
* offers no session lock ({@link openLockSession}). With `wait.ownLocks`, a
294+
* lock found held by one of those in this database's namespace answers that
295+
* lock at once, with no wait and no line ({@link DatabaseSessionLockRunOptions}).
189296
*
190297
* Uncontended, it is silent: one statement, no output. Contended, it calls
191298
* `onWait` ONCE, then waits up to `waitMs` and throws `refuse()` on timeout.
@@ -196,8 +303,15 @@ export async function acquireDatabaseSessionLock(driver: unknown, wait: Database
196303
if (!session) return null;
197304
const { pg, run } = session;
198305
const { waitMs } = wait;
306+
let marker: LockMarker | null = null;
199307
try {
308+
if (wait.ownLocks) marker = await session.mark();
200309
if (!(await session.tryLock())) {
310+
const own = wait.ownLocks ? await session.heldAmong(wait.ownLocks) : undefined;
311+
if (own) {
312+
await session.close();
313+
return own;
314+
}
201315
wait.onWait();
202316
if (pg) {
203317
await run(`set lock_timeout = ${Math.max(1, Math.trunc(waitMs))}`, []);
@@ -218,5 +332,5 @@ export async function acquireDatabaseSessionLock(driver: unknown, wait: Database
218332
await session.close();
219333
throw error;
220334
}
221-
return session.held();
335+
return session.held(marker);
222336
}

0 commit comments

Comments
 (0)