From 3164ec215c98b15904e6ccb2915bbdf0ae70a1de Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 11:34:56 +0000 Subject: [PATCH] fix(ui-server): check login expiry against the clock inside the writer for profile, push, storage-notice and hygiene writes (#4176) Session worker-profile save and bind, push subscription binding, storage notice dispatch and the hygiene review's worker procedures checked a login's expiry against a time the caller stamped before waiting for the write worker, so a login that expired while queued still passed. Each check now reads the clock inside the writer; the stamp still records updated_at, created_at and attempted_at, drives the draft cleanup and orders the storage notifier's time windows. Co-Authored-By: Claude Opus 5.5 --- .changeset/4176-writer-clock-expiry.md | 5 ++ .../ui-server/src/activity/push-writes.ts | 6 +- .../ui-server/src/inbox/hygiene-writes.ts | 4 +- .../ui-server/src/storage/notify-writes.ts | 5 +- .../src/ws/session-profile-writes.ts | 14 ++-- .../tests/app-writes-offloop.test.ts | 56 ++++++++++++++++ .../ui-server/tests/helpers/held-writer.ts | 66 +++++++++++++++++++ .../tests/inbox-writes-offloop.test.ts | 19 ++++++ packages/ui-server/tests/push.test.ts | 48 ++++++++++++++ .../ui-server/tests/storage-offloop.test.ts | 32 +++++++++ 10 files changed, 248 insertions(+), 7 deletions(-) create mode 100644 .changeset/4176-writer-clock-expiry.md create mode 100644 packages/ui-server/tests/helpers/held-writer.ts diff --git a/.changeset/4176-writer-clock-expiry.md b/.changeset/4176-writer-clock-expiry.md new file mode 100644 index 0000000000..8ad46f2c7b --- /dev/null +++ b/.changeset/4176-writer-clock-expiry.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Four more write-worker procedures now refuse a login that expires while the request waits for the write worker (#4176). Each stamped the request's time before that wait and checked the login's expiry against the stamp inside the writer, so a login that expired in the meantime still passed. Saving or binding a session worker profile now refuses it with `401`. A push subscription binds no device and answers `false`. A storage notice attempt returns no attempt and records nothing. A hygiene review command refuses it as `HygieneAuthorityError`. Each check now reads the clock inside the writer. The stamp still records `updated_at`, `created_at` and `attempted_at`, drives the draft-preference cleanup, and judges the storage notifier's reversed-clock guard, eligibility windows and quiet hours. Revocation is unchanged, because it was already read from the row inside the transaction. diff --git a/packages/ui-server/src/activity/push-writes.ts b/packages/ui-server/src/activity/push-writes.ts index d5f7cafc4b..15393045f2 100644 --- a/packages/ui-server/src/activity/push-writes.ts +++ b/packages/ui-server/src/activity/push-writes.ts @@ -18,13 +18,17 @@ export function setup(db: Database) { .run(generated.publicKey, generated.privateKey, Date.now()); return readKeys()!; }, + /** + * `now` was stamped before the request waited for the writer and records + * `created_at`; the login is checked against the clock here (#4176). + */ subscribe(sub: Subscription, principalId: string, label: string | undefined, now: number) { return db.query(`INSERT INTO push_subscriptions (endpoint, p256dh, auth, label, created_at, principal_id) SELECT ?, ?, ?, ?, ?, id FROM principals WHERE id = ? AND revoked_at IS NULL AND typeof(expires_at) = 'integer' AND expires_at > ? ON CONFLICT(endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth, label = excluded.label, principal_id = excluded.principal_id`) - .run(sub.endpoint, sub.keys.p256dh, sub.keys.auth, label ?? null, now, principalId, now).changes > 0; + .run(sub.endpoint, sub.keys.p256dh, sub.keys.auth, label ?? null, now, principalId, Date.now()).changes > 0; }, unsubscribe(endpoint: string, principalId: string) { return db.query("DELETE FROM push_subscriptions WHERE endpoint = ? AND principal_id = ?").run(endpoint, principalId).changes > 0; diff --git a/packages/ui-server/src/inbox/hygiene-writes.ts b/packages/ui-server/src/inbox/hygiene-writes.ts index c9fbf7e720..8b779cf3a4 100644 --- a/packages/ui-server/src/inbox/hygiene-writes.ts +++ b/packages/ui-server/src/inbox/hygiene-writes.ts @@ -33,9 +33,11 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP let at = 0; const now = () => at, store = createInboxStore(db, { now }); const resolver = createInboxResolver(db, { now, timeZone, allowedOperations: () => [], applyHygiene: async () => { throw new Error("Effects run on the host"); } }); + // Authority is the clock's, read where the procedure runs (#4176): `at` was + // stamped before the review waited for the writer, and records times only. function authority(principalId: string) { const p = resolvePrincipal(db, principalId); - if (!p || !isUsablePrincipal(p, now()) || !["owner", "ambient"].includes(p.kind)) throw new HygieneAuthorityError("Human review authority is required"); + if (!p || !isUsablePrincipal(p, Date.now()) || !["owner", "ambient"].includes(p.kind)) throw new HygieneAuthorityError("Human review authority is required"); } function state(): HygieneReviewState { const row = db.query("SELECT data_json FROM hygiene_review WHERE singleton = 1").get() as { data_json: string } | null; diff --git a/packages/ui-server/src/storage/notify-writes.ts b/packages/ui-server/src/storage/notify-writes.ts index 19fafe38bf..56bacf1244 100644 --- a/packages/ui-server/src/storage/notify-writes.ts +++ b/packages/ui-server/src/storage/notify-writes.ts @@ -55,7 +55,10 @@ export function setup(db: Database, { brain, self: SELF }: { brain: string; self const lastAttempt = db.query("SELECT MAX(attempted_at) AS at FROM storage_notice_receipts WHERE brain = ?").get(brain) as { at: number | null }; if (state.lastPersistedAt > now || lastAttempt.at !== null && lastAttempt.at > now) return null; const sub = db.query("SELECT principal_id, time_zone, p256dh, auth FROM push_subscriptions WHERE endpoint = ?").get(endpoint) as { principal_id: string | null; time_zone: string | null; p256dh: string; auth: string } | null; - if (!sub?.principal_id || !owner(sub.principal_id, now)) return null; + // Authority is the clock's, read here (#4176): `now` was stamped before + // the attempt waited for the writer. It still orders time, judges the + // eligibility windows and quiet hours and records `attempted_at`. + if (!sub?.principal_id || !owner(sub.principal_id, Date.now())) return null; const eligible = state.pressures.filter(row => row.severity === "critical" && row.episode && !row.scopeChanged && row.supportAt !== null && row.supportAt <= now && now - row.supportAt <= RECENT && !state.suppressedEpisodes.includes(row.episode)); for (const row of eligible) db.query("INSERT OR IGNORE INTO storage_notice_receipts (brain, episode, endpoint, principal_id, state) VALUES (?, ?, ?, ?, 'pending')").run(brain, row.episode!, endpoint, sub.principal_id); if (status.pending || status.paused && status.paused !== "collection-unavailable") return null; diff --git a/packages/ui-server/src/ws/session-profile-writes.ts b/packages/ui-server/src/ws/session-profile-writes.ts index 2d2b32135c..d2928e875b 100644 --- a/packages/ui-server/src/ws/session-profile-writes.ts +++ b/packages/ui-server/src/ws/session-profile-writes.ts @@ -28,10 +28,14 @@ export function draftProfile(db: Database, principalId: string, id: string) { return db.query("SELECT preference FROM draft_worker_profiles WHERE principal_id = ? AND draft_id = ?").get(principalId, id) as { preference: Profile } | null; } -/** A new session takes its draft's preference; the draft is consumed. */ +/** + * A new session takes its draft's preference; the draft is consumed. `now` + * was stamped before the request waited for the writer, so the login is + * checked against the clock here instead (#4176); `now` records `updated_at`. + */ export function bindDraftProfile(db: Database, principalId: string, draftId: string, sessionId: string, now: number) { db.transaction(() => { - authorizeProfile(db, principalId, now); + authorizeProfile(db, principalId, Date.now()); if (!db.query("SELECT 1 FROM sessions WHERE id = ?").get(sessionId)) throw new SessionProfileError(404, "This chat is not known to the host."); const row = draftProfile(db, principalId, draftId); if (!row) throw new SessionProfileError(409, "This draft preference is unavailable."); @@ -51,12 +55,14 @@ export function recordSessionProfile(db: Database, sessionId: string, origin: "i /** * A principal's saved preference for a session or a draft, checked and * stored in one transaction. `policyProfiles` is the brain's policy profile - * for each origin, resolved where the request arrived. + * for each origin, resolved where the request arrived. The login is checked + * against the clock inside the transaction (#4176); `now`, stamped before the + * wait for the writer, records `updated_at` and drives the draft cleanup. */ export function saveProfile(db: Database, principalId: string, kind: "session" | "draft", id: string, preference: Profile, policyProfiles: Record<"interactive" | "voice", Profile>, now: number) { db.transaction(() => { - authorizeProfile(db, principalId, now); + authorizeProfile(db, principalId, Date.now()); let origin: "interactive" | "voice" = "interactive"; if (kind === "session") { if (!db.query("SELECT 1 FROM sessions WHERE id = ?").get(id)) throw new SessionProfileError(404, "This chat is not known to the host."); diff --git a/packages/ui-server/tests/app-writes-offloop.test.ts b/packages/ui-server/tests/app-writes-offloop.test.ts index 929a97557d..b6bc9bb0ed 100644 --- a/packages/ui-server/tests/app-writes-offloop.test.ts +++ b/packages/ui-server/tests/app-writes-offloop.test.ts @@ -21,6 +21,7 @@ import { createSessionCatalog } from "../src/ws/session-catalog.js"; import { TurnCoordinator } from "../src/ws/turns.js"; import { createSessionProfiles, SessionProfileError } from "../src/ws/session-profiles.js"; import { expectRejection } from "./helpers/expect-rejection.js"; +import { heldWriter } from "./helpers/held-writer.js"; import { createPolicyProposals } from "../src/brain/policy-proposal.js"; import { createSessionRoutes } from "../src/routes/sessions.js"; import { createStaticBackendRegistry } from "../src/agent/backend.js"; @@ -343,6 +344,61 @@ test("a saved worker preference commits on the write worker, and its refusals ke } finally { await f.close(); } }); +for (const write of ["save", "bind"] as const) test(`a login that expires while a profile ${write} waits for the writer is refused by the current time (#4176)`, async () => { + const f = fixture(), held = await heldWriter(f.writer, f.path); + try { + const athena = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + f.db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES ('troy','Troy',0,0)").run(); + f.db.query("INSERT INTO draft_worker_profiles (principal_id, draft_id, preference, updated_at) VALUES (?, 'troy-draft', 'strict', 0)").run(athena.id); + const profiles = createSessionProfiles(f.db, profileFacts, undefined, undefined, { writer: f.writer }); + await held.hold(); + const submitted = held.posted(write); + // The request stamps its time before the wait; the login is usable at that stamp. + const pending = write === "save" ? profiles.save(athena.id, "session", "troy", "strict") : profiles.bind(athena.id, "troy-draft", "troy"); + await submitted; + await held.expireWhileQueued(athena.id); + held.release(); + const refusal = await expectRejection(pending, SessionProfileError, `PROFILE_${write.toUpperCase()}_EXPIRY_CHECKED_AT_COMMIT`) as SessionProfileError; + expect(refusal.status, "PROFILE_EXPIRED_LOGIN_IS_401").toBe(401); + expect(f.db.query("SELECT COUNT(*) AS n FROM session_worker_profiles WHERE session_id = 'troy'").get(), "NO_PROFILE_RECORDED").toEqual({ n: 0 }); + expect(f.db.query("SELECT COUNT(*) AS n FROM draft_worker_profiles WHERE draft_id = 'troy-draft'").get(), "DRAFT_NOT_CONSUMED").toEqual({ n: 1 }); + } finally { await held.close(); await f.close(); } +}); + +test("profile writes behind a held writer still record the stamped time and clean up drafts by it (#4176)", async () => { + const f = fixture(), held = await heldWriter(f.writer, f.path); + try { + const athena = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const penelope = createPrincipal(f.db, { authMethod: "password", label: "Penelope's loom", ttlSeconds: 3600 }); + f.db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES ('troy','Troy',0,0)").run(); + f.db.query("INSERT INTO draft_worker_profiles (principal_id, draft_id, preference, updated_at) VALUES (?, 'troy-draft', 'strict', 0)").run(athena.id); + f.db.query("INSERT INTO draft_worker_profiles (principal_id, draft_id, preference, updated_at) VALUES (?, 'loom-draft', 'strict', 0)").run(penelope.id); + const profiles = createSessionProfiles(f.db, profileFacts, undefined, undefined, { writer: f.writer }); + // A saved draft preference: Penelope's login is live at the request's stamp and expired when the writer runs. + await held.hold(); + let submitted = held.posted("save"); + const saved = profiles.save(athena.id, "draft", "voyage-draft", "strict"); + await submitted; + let stamped = await held.expireWhileQueued(penelope.id); + held.release(); + await saved; + const draftAt = (f.db.query("SELECT updated_at AS at FROM draft_worker_profiles WHERE draft_id = 'voyage-draft'").get() as { at: number }).at; + expect(draftAt, "PROFILE_SAVE_UPDATED_AT_IS_THE_STAMP").toBeLessThanOrEqual(stamped); + expect(f.db.query("SELECT draft_id FROM draft_worker_profiles WHERE principal_id = ?").get(penelope.id), "PROFILE_DRAFT_CLEANUP_USES_THE_STAMP").toEqual({ draft_id: "loom-draft" }); + // A bound draft: the session's row records the request's stamp, not the writer's clock. + await held.hold(); + submitted = held.posted("bind"); + const bound = profiles.bind(athena.id, "troy-draft", "troy"); + await submitted; + stamped = Date.now(); + while (Date.now() <= stamped) await Bun.sleep(1); + held.release(); + await bound; + const sessionAt = (f.db.query("SELECT updated_at AS at FROM session_worker_profiles WHERE session_id = 'troy'").get() as { at: number }).at; + expect(sessionAt, "PROFILE_BIND_UPDATED_AT_IS_THE_STAMP").toBeLessThanOrEqual(stamped); + } finally { await held.close(); await f.close(); } +}); + test("a replayed history waits for the classified blocks submitted before it (#2850)", async () => { const f = fixture(); try { diff --git a/packages/ui-server/tests/helpers/held-writer.ts b/packages/ui-server/tests/helpers/held-writer.ts new file mode 100644 index 0000000000..b0d62f09e1 --- /dev/null +++ b/packages/ui-server/tests/helpers/held-writer.ts @@ -0,0 +1,66 @@ +/** + * Hold the real `ui.db` write worker, see when a named procedure has been + * posted to it behind the hold, and change rows from another connection while + * it waits, as a concurrent request would (#4169, #4176). + */ +import { spyOn } from "bun:test"; +import { Database } from "bun:sqlite"; +import type { SqliteWriter } from "../../src/db/write-worker.js"; +import * as controls from "./dialogue-test-writes.js"; + +export async function heldWriter(writer: SqliteWriter, path: string) { + const control = writer.channel({ url: controls.url, setup: controls.setup }, {}); + const gate = new Int32Array(new SharedArrayBuffer(8)); + const restores: (() => void)[] = []; + let held: Promise | undefined; + const release = () => { Atomics.store(gate, 0, 1); Atomics.notify(gate, 0); }; + return { + /** Resolves once the worker is inside the hold; a released hold can be taken again. */ + async hold() { + await held; + Atomics.store(gate, 0, 0); Atomics.store(gate, 1, 0); + held = control.call("holdUntilReleased", gate); + const deadline = Date.now() + 2000; + while (!Atomics.load(gate, 1)) { if (Date.now() > deadline) throw Error("Ithaca writer did not hold"); await Bun.sleep(1); } + }, + /** Resolves once every one of `names` has been posted to the worker, where they queue behind the hold. */ + posted(...names: string[]): Promise { + const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "postMessage")!, send = Worker.prototype.postMessage; + const waiting = new Set(names); + let seen!: () => void; + const sent = new Promise(resolve => { seen = resolve; }); + let restored = false; + const restore = () => { if (restored) return; restored = true; spy.mockRestore(); Object.defineProperty(Worker.prototype, "postMessage", descriptor); }; + const spy = spyOn(Worker.prototype, "postMessage").mockImplementation(function (this: Worker, ...args: [message: unknown, options?: StructuredSerializeOptions | Transferable[]]) { + const message = args[0] as { kind?: string; name?: string }; + const result = Reflect.apply(send, this, args); + if (message.kind === "call" && message.name !== undefined && waiting.delete(message.name) && waiting.size === 0) { restore(); seen(); } + return result; + }); + restores.push(restore); + return sent; + }, + /** Change rows from another connection while the writer is held. */ + elsewhere(change: (other: Database) => void) { + const other = new Database(path); other.exec("PRAGMA busy_timeout = 5000"); + try { change(other); } finally { other.close(); } + }, + /** + * Expire `principalId` one millisecond after the latest stamp the request + * could have taken, then let the clock pass it: usable at the stamp, expired + * when the held writer takes its turn. Returns that latest possible stamp. + */ + async expireWhileQueued(principalId: string): Promise { + const stamped = Date.now(); + this.elsewhere(other => other.query("UPDATE principals SET expires_at = ? WHERE id = ?").run(stamped + 1, principalId)); + while (Date.now() <= stamped + 1) await Bun.sleep(1); + return stamped; + }, + release, + async close() { + release(); + for (const restore of restores.splice(0).reverse()) restore(); + await held; await control.close(); + }, + }; +} diff --git a/packages/ui-server/tests/inbox-writes-offloop.test.ts b/packages/ui-server/tests/inbox-writes-offloop.test.ts index 6568b19958..22ef880521 100644 --- a/packages/ui-server/tests/inbox-writes-offloop.test.ts +++ b/packages/ui-server/tests/inbox-writes-offloop.test.ts @@ -24,6 +24,8 @@ import * as probe from "./fixtures/write-worker-probe.js"; import { registerInboxWrites } from "../src/inbox/write-runtime.js"; import { watchWriteSites } from "./helpers/write-sites.js"; import { expectRejection } from "./helpers/expect-rejection.js"; +import { heldWriter } from "./helpers/held-writer.js"; +import { HygieneAuthorityError } from "../src/inbox/hygiene-writes.js"; function fixture() { const root = mkdtempSync(join(tmpdir(), "inbox-writes-odysseus-")); @@ -182,6 +184,23 @@ test("hygiene review admission preview and completion commit on the write worker } finally { await f.close(); } }); +test("a reviewer login that expires while a hygiene command waits for the writer is refused by the current time (#4176)", async () => { + const f = fixture(), held = await heldWriter(f.writer, join(f.root, "ui.db")); + try { + const brain = { hygiene: async () => ({ finding: null, counts: { eligibleRemaining: 0, fixed: 0, dismissed: 0, snoozed: 0, nextSnoozeDueAt: null, informationalNotShown: 0 } }) } as unknown as BrainClient; + const review = createHygieneReview(f.db, { brain }); + await held.hold(); + const submitted = held.posted("command"); + // The review stamps the command's time before the wait; the reviewer is usable at that stamp. + const pending = review.command(f.principal.id, "pause"); + await submitted; + await held.expireWhileQueued(f.principal.id); + held.release(); + await expectRejection(pending, HygieneAuthorityError, "HYGIENE_AUTHORITY_EXPIRY_CHECKED_AT_COMMIT"); + expect(review.read().review.status, "HYGIENE_PAUSE_NOT_RECORDED").not.toBe("paused"); + } finally { await held.close(); await f.close(); } +}); + test("concurrent inbox submissions keep gap-free sequences and commit order through a rollback", async () => { const f = fixture(), store = createInboxStore(f.db); try { diff --git a/packages/ui-server/tests/push.test.ts b/packages/ui-server/tests/push.test.ts index e8b1048047..3b68d78456 100644 --- a/packages/ui-server/tests/push.test.ts +++ b/packages/ui-server/tests/push.test.ts @@ -7,6 +7,9 @@ */ import { describe, expect, spyOn, test } from "bun:test"; import { Hono } from "hono"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { createStaticBackendRegistry } from "../src/agent/backend"; import { createActivityStore } from "../src/activity/store"; @@ -16,11 +19,13 @@ import { createActivityStream } from "../src/activity/stream"; import type { AppEnv } from "../src/app-env"; import { createPushRoutes } from "../src/routes/push"; import { createUiDb } from "../src/db/client"; +import { openSqliteWriter } from "../src/db/write-worker"; import { createPrincipal, revokePrincipal, type Principal } from "../src/db/principals"; import { applyPrincipalRevocation } from "../src/middleware/auth"; import { WsHost } from "../src/ws/host"; import { createSessionCatalog } from "../src/ws/session-catalog"; import { makeFakeBackend } from "./helpers/fake-backend"; +import { heldWriter } from "./helpers/held-writer"; function setup(sendImpl?: (sub: any, payload?: any) => Promise) { const db = createUiDb(":memory:"); @@ -342,3 +347,46 @@ describe("push routes", () => { expect(res.status).toBe(400); }); }); + +describe("push subscription behind a held writer", () => { + async function hosted() { + const root = mkdtempSync(join(tmpdir(), "odysseus-push-writer-")), path = join(root, "ui.db"); + const db = createUiDb(path), writer = openSqliteWriter(db), held = await heldWriter(writer, path); + const sender = createPushSender(db, { writer, send: async () => {} }); + const principal = createOwner(db, "Telemachus' phone"); + return { db, sender, principal, held, async close() { await held.close(); await sender.close(); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }; + } + const device = { endpoint: "https://push.example.test/ithaca", keys: { p256dh: "opaque-key", auth: "opaque-auth" } }; + + test("a login that expires while the subscription waits for the writer binds nothing (#4176)", async () => { + const f = await hosted(); + try { + await f.held.hold(); + const submitted = f.held.posted("subscribe"); + // The sender stamps the request's time before the wait; the login is usable at that stamp. + const pending = f.sender.subscribe(device, f.principal.id, "Telemachus"); + await submitted; + await f.held.expireWhileQueued(f.principal.id); + f.held.release(); + expect(await pending, "PUSH_SUBSCRIBE_EXPIRY_CHECKED_AT_COMMIT").toBe(false); + expect(f.db.query("SELECT COUNT(*) AS n FROM push_subscriptions").get(), "NO_DEVICE_BOUND").toEqual({ n: 0 }); + } finally { await f.close(); } + }); + + test("a subscription behind a held writer still records the stamped time (#4176)", async () => { + const f = await hosted(); + try { + await f.held.hold(); + const submitted = f.held.posted("subscribe"); + const pending = f.sender.subscribe(device, f.principal.id, "Telemachus"); + await submitted; + const stamped = Date.now(); + while (Date.now() <= stamped) await Bun.sleep(1); + f.held.release(); + expect(await pending).toBe(true); + const row = f.db.query("SELECT created_at AS at, principal_id AS principal FROM push_subscriptions").get() as { at: number; principal: string }; + expect(row.principal).toBe(f.principal.id); + expect(row.at, "PUSH_SUBSCRIBE_CREATED_AT_IS_THE_STAMP").toBeLessThanOrEqual(stamped); + } finally { await f.close(); } + }); +}); diff --git a/packages/ui-server/tests/storage-offloop.test.ts b/packages/ui-server/tests/storage-offloop.test.ts index a0f60461ee..af3a07d059 100644 --- a/packages/ui-server/tests/storage-offloop.test.ts +++ b/packages/ui-server/tests/storage-offloop.test.ts @@ -16,6 +16,7 @@ import { watchWriteSites } from "./helpers/write-sites.js"; import * as probe from "./fixtures/write-worker-probe.js"; import { watchRetainedErrors } from "./helpers/retained-errors.js"; import { rejection } from "./helpers/expect-rejection.js"; +import { heldWriter } from "./helpers/held-writer.js"; const start = Date.UTC(2026, 6, 12, 9, 41), scope = hashScope("Odysseus stores"); function observation(at: number): Aggregate { @@ -61,6 +62,37 @@ test("storage initialization, flush, begin, finish and sweep commit on the worke } finally { await f.close(); } }); +for (const expiring of [true, false]) test(expiring + ? "an owner login that expires while a storage notice waits for the writer records no attempt (#4176)" + : "a storage notice behind a held writer still records its attempt at the stamped time (#4176)", async () => { + const f = fixture(), held = await heldWriter(f.writer, join(f.root, "ui.db")); + try { + const owner = createPrincipal(f.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 365 * 24 * 3600 }); + const endpoint = "https://push.example.test/Ithaca"; + f.db.query("INSERT INTO push_subscriptions (endpoint, p256dh, auth, principal_id, time_zone, created_at) VALUES (?, 'opaque-key', 'opaque-auth', ?, 'UTC', ?)").run(endpoint, owner.id, start); + const history = createStorageHistory(f.db, f.root, { now: f.now, writer: f.writer }); + history.offer(observation(start)); + expect(await history.flush()).toBe(true); + const notices = createStorageNotifier(f.db, history, f.writer); + await held.hold(); + const submitted = held.posted("begin"); + // The attempt's stamp is a fixed daytime one, so quiet hours and the + // eligibility windows are judged deterministically; the owner is usable at it. + const pending = notices.begin(endpoint, start); + await submitted; + if (expiring) await held.expireWhileQueued(owner.id); + held.release(); + const attempt = await pending; + if (expiring) { + expect(attempt, "STORAGE_NOTICE_OWNER_EXPIRY_CHECKED_AT_COMMIT").toBeNull(); + expect(f.db.query("SELECT COUNT(*) AS n FROM storage_notice_receipts").get(), "NO_STORAGE_ATTEMPT_RECORDED").toEqual({ n: 0 }); + } else { + expect(attempt).not.toBeNull(); + expect(f.db.query("SELECT attempted_at AS at FROM storage_notice_receipts").all(), "STORAGE_NOTICE_ATTEMPTED_AT_IS_THE_STAMP").toEqual([{ at: start }]); + } + } finally { await held.close(); await f.close(); } +}); + test("a held worker keeps flush off the loop and coalesces requests after the in-flight commit", async () => { const f = fixture(); try {