Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/33932-seal-lock-stalled-session.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/objectql': patch
'@objectstack/plugin-audit': patch
---

fix(objectql, plugin-audit): a database session lock whose connection stalls no longer hangs the audit sealer, `os migrate audit-* --apply` or a migrator's release

Clause-②: no
Metadata-protocol: none

A held database session lock (the audit seal lock, and the schema-migration lock) used to wait for its connection with no limit when it checked or let go of the lock. A connection stalled half-open, with no reply and no reset, never fails a statement, so the liveness probe (`select 1`), the unlock statement and the close of the raw connection could each wait for good. That hung a sealer pass checking its lock before a checkpoint, the `finish()` of an `os migrate audit-* --apply` run, and a migrator's release.

Each of the three steps now gives up after 10 seconds (`DATABASE_SESSION_LOCK_ANSWER_MS`). A live session answers each one in milliseconds and waits exactly as before.

- A probe the session does not answer in time reads as a lost lock. The session is not probed again, and the release sends it no unlock: it closes the connection, which releases the lock.
- An `--apply` run whose lock's session stopped answering reports the lock lost, as for a session that ended: it prints the line at error, names `os audit verify` and exits non-zero. The line now reads `(its database session ended, or stopped answering)`.
- A sealer pass whose lock's session stops answering reports that the audit seal lock lapsed and writes no checkpoint. The next pass tries again.
- The schema-migration lock runs the same statements. A release on a session that has stopped answering returns after the bound instead of hanging the migration or the boot. The lock then stays with the database session until that connection dies, as it would if the process had been killed.

Nothing an author writes, no exported signature and no statement changes.
109 changes: 108 additions & 1 deletion packages/objectql/src/database-session-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
* stage on demand; two sessions on one live Postgres are the CLI's live file.
*/

import { describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createHash } from 'node:crypto';
import {
acquireDatabaseSessionLock,
DATABASE_SESSION_LOCK_ANSWER_MS,
databaseSessionLockPgKey,
tryDatabaseSessionLock,
} from './database-session-lock.js';
Expand Down Expand Up @@ -235,3 +236,109 @@ describe('ownLocks: a run that locks several datasources never contends with its
expect(second.destroyed).toEqual([second.connection]);
});
});

describe('a stalled session never hangs its holder: the probe, the release and the close each time out (ADR-0154 D3 amended)', () => {
// A connection stalled half-open — no reply and no reset — never fails a statement: it never answers at all.
const NEVER = () => new Promise<never>(() => {});

/** A fake Knex whose session answers until `stall` names a step, and then never answers that step again. */
function stallingDriver(dialect: 'postgres' | 'mysql') {
const stall = { probe: false, unlock: false, close: false };
const statements: string[] = [];
const closes: unknown[] = [];
const connection = { id: 'raw-stall' };
const shape = (row: unknown) => (dialect === 'mysql' ? [[row], []] : { rows: [row] });
const knex = {
client: {
acquireRawConnection: async () => connection,
destroyRawConnection: (c: unknown) => { closes.push(c); return stall.close ? NEVER() : Promise.resolve(); },
},
raw: (sql: string) => ({
connection: (): Promise<unknown> => {
statements.push(sql);
if (sql === 'select 1 as held' && stall.probe) return NEVER();
if (/unlock|RELEASE_LOCK/.test(sql) && stall.unlock) return NEVER();
return Promise.resolve(shape({ locked: dialect === 'mysql' ? 1 : true, held: 1 }));
},
}),
};
return { driver: { dialectName: dialect, getKnex: () => knex }, stall, statements, closes, connection };
}

/** Settle `step` on a fake clock: what it answered by `ms` from now, or the string 'still waiting'. */
async function answerWithin<T>(step: Promise<T>, ms: number): Promise<T | 'still waiting'> {
let answer: T | 'still waiting' = 'still waiting';
void step.then((value) => { answer = value; });
await vi.advanceTimersByTimeAsync(ms);
return answer;
}

async function heldLock(dialect: 'postgres' | 'mysql') {
const f = stallingDriver(dialect);
const lock = await tryDatabaseSessionLock(f.driver, NAME);
if (lock === null || lock === 'held') throw new Error('expected a lock');
return { ...f, lock };
}

beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });

it('the bound is a few seconds: three orders of magnitude over a live session\'s answer, far short of a hang', () => {
expect(DATABASE_SESSION_LOCK_ANSWER_MS).toBe(10_000);
});

for (const dialect of ['postgres', 'mysql'] as const) {
it(`${dialect}: a probe the session never answers reads false — the lock is lost — once the bound runs out, and is never sent again`, async () => {
const f = await heldLock(dialect);
f.stall.probe = true;
const probe = f.lock.isHeld();
expect(await answerWithin(probe, DATABASE_SESSION_LOCK_ANSWER_MS - 1)).toBe('still waiting');
expect(await answerWithin(probe, 1)).toBe(false);
const sent = f.statements.length;
expect(await answerWithin(f.lock.isHeld(), 0)).toBe(false);
expect(f.statements).toHaveLength(sent);
});
}

it('a release after a probe that timed out sends no unlock to the stalled session: it closes it, and that close is bounded too', async () => {
const f = await heldLock('postgres');
f.stall.probe = true;
f.stall.close = true;
expect(await answerWithin(f.lock.isHeld(), DATABASE_SESSION_LOCK_ANSWER_MS)).toBe(false);
expect(await answerWithin(f.lock.release(), DATABASE_SESSION_LOCK_ANSWER_MS)).toBeUndefined();
expect(f.statements.filter((sql) => /unlock/.test(sql))).toEqual([]);
expect(f.closes).toEqual([f.connection]);
});

for (const dialect of ['postgres', 'mysql'] as const) {
it(`${dialect}: an unlock the session never answers gives up once the bound runs out, and the session is closed — closing releases the lock`, async () => {
const f = await heldLock(dialect);
f.stall.unlock = true;
const release = f.lock.release();
expect(await answerWithin(release, DATABASE_SESSION_LOCK_ANSWER_MS - 1)).toBe('still waiting');
expect(f.closes).toEqual([]);
expect(await answerWithin(release, 1)).toBeUndefined();
expect(f.statements.at(-1)).toBe(dialect === 'postgres' ? 'select pg_advisory_unlock(?::bigint)' : 'select RELEASE_LOCK(?)');
expect(f.closes).toEqual([f.connection]);
await expect(f.lock.isHeld()).resolves.toBe(false);
});
}

it('a close the connection never finishes gives up once the bound runs out: release resolves, and never throws', async () => {
const f = await heldLock('postgres');
f.stall.close = true;
const release = f.lock.release();
expect(await answerWithin(release, DATABASE_SESSION_LOCK_ANSWER_MS - 1)).toBe('still waiting');
expect(f.closes).toEqual([f.connection]);
expect(await answerWithin(release, 1)).toBeUndefined();
});

it('a live session is unchanged: the probe reads true, the release unlocks and closes, with no time passing', async () => {
const f = await heldLock('postgres');
expect(await answerWithin(f.lock.isHeld(), 0)).toBe(true);
expect(await answerWithin(f.lock.release(), 0)).toBeUndefined();
expect(f.statements).toEqual(['select pg_try_advisory_lock(?::bigint) as locked', 'select 1 as held', 'select pg_advisory_unlock(?::bigint)']);
expect(f.closes).toEqual([f.connection]);
expect(vi.getTimerCount()).toBe(0);
});
});
73 changes: 63 additions & 10 deletions packages/objectql/src/database-session-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,66 @@ interface LockKnex {
raw(sql: string, bindings?: readonly unknown[]): { connection(connection: unknown): Promise<unknown> };
}

/** A held database session lock. `release()` is idempotent and never throws. */
/**
* A held database session lock. `release()` is idempotent, never throws, and
* never waits on a stalled session past {@link DATABASE_SESSION_LOCK_ANSWER_MS}
* for its unlock, nor past it again for its close.
*/
export interface DatabaseSessionLock {
release(): Promise<void>;
/**
* Whether the lock still stands: its session answers a probe on the very
* connection it was taken on. A session that ended — a dropped connection,
* a terminated backend — took the lock with it, so a probe that fails reads
* `false`, never throws. Always `false` after `release()`.
* `false`, never throws. A probe the session does not answer within
* {@link DATABASE_SESSION_LOCK_ANSWER_MS} reads `false` too, and from then on
* the session is never probed again. Always `false` after `release()`.
*/
isHeld(): Promise<boolean>;
}

/**
* How long a HELD lock's session gets to answer each step of a holder's check
* and finish — the liveness probe ({@link DatabaseSessionLock.isHeld}), the
* unlock statement, and the close of the raw connection — before it is read as
* stalled.
*
* A connection stalled half-open — no reply and no reset — never FAILS a
* statement: it never answers at all, and a holder that waits on it waits for
* good (a sealer pass checking its lock, an `os migrate audit-* --apply` run's
* finish, a migrator's release). A session that has not answered in this long
* is one no holder can count on, so it is read as gone: the probe answers
* `false` (the lock is lost), the release stops waiting for its unlock and
* closes the connection, and the close stops waiting too — the database ends
* the session, and the lock with it, once the connection finally dies. A live
* session answers each of the three in milliseconds.
*
* Every holder is bounded alike, the schema-migration lock's release included;
* no statement either lock runs changes, and a live session waits exactly as
* long as before.
*/
export const DATABASE_SESSION_LOCK_ANSWER_MS = 10_000;

/** What {@link withinAnswerTime} answers for a step the session did not answer in time. */
const STALLED = Symbol('stalled');

/**
* `step`'s own outcome, or {@link STALLED} once
* {@link DATABASE_SESSION_LOCK_ANSWER_MS} pass without it settling. Its timer
* is cleared as soon as either settles, so it never outlives the step.
*/
async function withinAnswerTime<T>(step: Promise<T>): Promise<T | typeof STALLED> {
let timer: ReturnType<typeof setTimeout> | undefined;
const stalled = new Promise<typeof STALLED>((resolve) => {
timer = setTimeout(() => resolve(STALLED), DATABASE_SESSION_LOCK_ANSWER_MS);
});
try {
return await Promise.race([step, stalled]);
} finally {
clearTimeout(timer);
}
}

/**
* The options of a lock that one run takes on several datasources under one
* name ({@link tryDatabaseSessionLock}, {@link acquireDatabaseSessionLock}).
Expand Down Expand Up @@ -177,7 +225,8 @@ async function openLockSession(driver: unknown, name: string): Promise<LockSessi
const run = async (sql: string, bindings: readonly unknown[]): Promise<Record<string, unknown> | undefined> =>
lockRow(await knex.raw(sql, bindings).connection(connection));
const close = async (): Promise<void> => {
try { await knex.client.destroyRawConnection(connection); } catch { /* closing releases the lock anyway */ }
// Bounded: closing a stalled connection waits on the same silent transport (see DATABASE_SESSION_LOCK_ANSWER_MS).
try { await withinAnswerTime(knex.client.destroyRawConnection(connection)); } catch { /* closing releases the lock anyway */ }
};
return {
pg,
Expand Down Expand Up @@ -215,21 +264,25 @@ async function openLockSession(driver: unknown, name: string): Promise<LockSessi
},
held(marker) {
let held = true;
// The session left a probe unanswered past the bound: the lock reads lost, and no statement waits on it again.
let stalled = false;
const lock: DatabaseSessionLock = {
release: async () => {
if (!held) return;
held = false;
try {
if (pg) await run('select pg_advisory_unlock(?::bigint)', [pgKey]);
else await run('select RELEASE_LOCK(?)', [name]);
} catch { /* closing the session below releases it */ }
if (!stalled) {
try {
// An unlock that does not answer in time is given up on: the close below ends the session, and the lock with it.
await withinAnswerTime(pg ? run('select pg_advisory_unlock(?::bigint)', [pgKey]) : run('select RELEASE_LOCK(?)', [name]));
} catch { /* closing the session below releases it */ }
}
await close();
},
isHeld: async () => {
if (!held) return false;
if (!held || stalled) return false;
try {
await run('select 1 as held', []);
return true;
if ((await withinAnswerTime(run('select 1 as held', []))) === STALLED) stalled = true;
return !stalled;
} catch {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AUDIT_SEAL_LOCK_NAME, AUDIT_SEAL_LOCK_WAIT_MS, AUDIT_SEAL_PG_LOCK_KEY, holdAuditSealLock, type AuditSealLockEngine } from './seal-lock.js';
import { AuditSealer } from './sealer.js';
import { LocalCheckpointSigner } from './signer.js';
Expand Down Expand Up @@ -310,3 +310,83 @@ describe('B: where the database offers no session lock, an --apply run on a seal
await expect(hold.finish()).resolves.toEqual({ lost: false });
});
});

describe('a stalled connection cannot hang the hold\'s finish or a sealer pass: each lock step is bounded', () => {
// A connection stalled half-open — no reply and no reset — never fails a statement, nor finishes a close: it never
// answers. `stalls()` puts the database's every session in that state from then on.
const NEVER = () => new Promise<never>(() => {});
/** The bound, generously: a probe, then a close, each given up on after `DATABASE_SESSION_LOCK_ANSWER_MS` (10 s). */
const BOUNDED_MS = 60_000;

function stallingDatabase() {
const db = sessionLockDatabase();
let stalled = false;
const knex = db.face.getKnex() as {
client: { acquireRawConnection(): Promise<unknown>; destroyRawConnection(c: unknown): Promise<void> };
raw(sql: string, bindings?: readonly unknown[]): { connection(c: unknown): Promise<unknown> };
};
const stalling = {
client: {
acquireRawConnection: () => knex.client.acquireRawConnection(),
destroyRawConnection: (c: unknown) => (stalled ? NEVER() : knex.client.destroyRawConnection(c)),
},
raw: (sql: string, bindings: readonly unknown[] = []) => ({
connection: (c: unknown) => (stalled ? NEVER() : knex.raw(sql, bindings).connection(c)),
}),
};
return { ...db, face: { dialectName: db.face.dialectName, getKnex: () => stalling }, stall: () => { stalled = true; } };
}

/** What `step` answered by `ms` of fake time from now, or 'still waiting'. */
async function answerWithin<T>(step: Promise<T>, ms: number): Promise<T | 'still waiting'> {
let answer: T | 'still waiting' = 'still waiting';
void step.then((value) => { answer = value; });
await vi.advanceTimersByTimeAsync(ms);
return answer;
}

beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); });
afterEach(() => { vi.useRealTimers(); });

it('⛔ --apply: finish() on a session that stopped answering reports the lock lost, naming `os audit verify` — the line the command prints at error before it exits non-zero', async () => {
const db = stallingDatabase();
const hold = await holdAuditSealLock(engineOf([SEALED], { sys_audit_log: lockableStore(new MemoryStore(), db) }), {
objects: RUN, sealerStopped: false, warn: vi.fn(),
});
const sent = db.statements.length;
db.stall();
const finished = await answerWithin(hold.finish(), BOUNDED_MS);
expect(finished).not.toBe('still waiting');
expect(finished).toMatchObject({ lost: true });
expect(finished !== 'still waiting' && finished.lost && finished.line).toMatch(
/^The audit seal lock on the database of 'sys_audit_log' was lost during this run \(its database session ended, or stopped answering\).*Run `os audit verify`/,
);
// The stalled session got its probe and nothing more: no unlock waited on it; its close was given up on too.
expect(db.statements.length).toBe(sent);
});

it('a sealer pass whose lock\'s session stops answering mid-pass ends, writes no checkpoint, and says which lock lapsed', async () => {
const H = 60 * 60 * 1000;
const DAY0 = Date.UTC(2026, 10, 10);
const store = memoryEngine([SEALED]);
const db = stallingDatabase();
lockableStore(store.hot, db);
const crypto = bindingCrypto();
const logger = recordingLogger();
const sealer = new AuditSealer({
engine: store.engine, crypto, signer: () => new LocalCheckpointSigner({ engine: store.engine, crypto }), logger, now: () => DAY0 + 12 * H,
});
store.hot.table('sys_audit_log').push({ id: 'r1', created_at: new Date(DAY0 + 8 * H).toISOString(), tenant_id: 'org_a', new_value: '{}' });
const find = store.hot.find.bind(store.hot);
store.hot.find = async (object, query) => {
// The pass holds the lock and reads the window: the connection stalls now.
if (object === 'sys_audit_log' && query.limit === 500) db.stall();
return find(object, query);
};
expect(await answerWithin(sealer.runPass(), BOUNDED_MS)).toBe(0);
expect(store.hot.table('sys_audit_checkpoint')).toEqual([]);
expect(logger.lines.map((l) => l.message)).toContainEqual(
expect.stringMatching(/sealing 'sys_audit_log' FAILED .*the audit seal lock on the database of 'sys_audit_log' lapsed/),
);
});
});
9 changes: 7 additions & 2 deletions packages/plugins/plugin-audit/src/audit-seal/seal-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ export interface AuditSealLockHold {
* Let every lock of the hold go, once the run's last write is done, and say
* whether each one still stood at that moment: a lock whose session ended
* mid-run (a dropped connection) excluded nothing from then on.
*
* A stalled connection cannot hang it: the probe, the release and the close
* of each lock are bounded (`DATABASE_SESSION_LOCK_ANSWER_MS` in
* `@objectstack/objectql`), and a session that does not answer the probe in
* time is a lost lock, reported as one that ended is.
*/
finish(): Promise<AuditSealLockFinish>;
}
Expand Down Expand Up @@ -238,8 +243,8 @@ export async function holdAuditSealLock(engine: AuditSealLockEngine, options: Au
lost: true,
line:
`The audit seal lock on the database of ${named(lost)} was lost during this run (its database session ` +
'ended), so a sealer pass may have sealed a row this run rewrote. Run `os audit verify`: a row it reports ' +
'modified was rewritten under such a pass.',
'ended, or stopped answering), so a sealer pass may have sealed a row this run rewrote. Run ' +
'`os audit verify`: a row it reports modified was rewritten under such a pass.',
};
},
};
Expand Down
Loading