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
5 changes: 5 additions & 0 deletions .changeset/4176-writer-clock-expiry.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 5 additions & 1 deletion packages/ui-server/src/activity/push-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion packages/ui-server/src/inbox/hygiene-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 4 additions & 1 deletion packages/ui-server/src/storage/notify-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 10 additions & 4 deletions packages/ui-server/src/ws/session-profile-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand All @@ -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.");
Expand Down
56 changes: 56 additions & 0 deletions packages/ui-server/tests/app-writes-offloop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 {
Expand Down
66 changes: 66 additions & 0 deletions packages/ui-server/tests/helpers/held-writer.ts
Original file line number Diff line number Diff line change
@@ -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<unknown> | 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<void> {
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "postMessage")!, send = Worker.prototype.postMessage;
const waiting = new Set(names);
let seen!: () => void;
const sent = new Promise<void>(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<number> {
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();
},
};
}
19 changes: 19 additions & 0 deletions packages/ui-server/tests/inbox-writes-offloop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-"));
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading