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/3528-worktree-checkpoint-abort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": patch
---

A reference worktree's journal observer no longer keeps a checkpoint the native lease owner refused before recording its lease. An abort while the checkpoint was being recorded in the worktree ledger, or while the owner settled the worktree's interrupted release, left the identity retained, and the observer's shutdown then failed with "native checkpoint(s) remain retained after shutdown". The lease owner now acknowledges one release of an identity it refused before any lease existed, without asking the pool to delete anything, and a ledger record that fails never reaches the pool. A checkpoint whose lease was recorded keeps its retryable cleanup, and a pool identity with no recorded lease still cannot be deleted.
4 changes: 2 additions & 2 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1987,15 +1987,15 @@ brain and every managed worktree, has its own owner, and each owner keeps at
most `NATIVE_RELEASE_BACKLOG`, two, previous checkpoints retained, whether
queued or failed. An observation makes room before it takes its own
checkpoint (`async function reserveRelease`,
`packages/ui-server/src/brain/native-journal-observer.ts:356-362`): it waits
`packages/ui-server/src/brain/native-journal-observer.ts:361-369`): it waits
inside the hold for the oldest queued release, or, when failed releases fill
the bound, retries the oldest one inside the hold, as every release ran
before. If that retry fails, the observation is refused before it takes a
checkpoint, so the bound is never exceeded. Each retained checkpoint is charged with an upper bound of the file content
it holds that the live root no longer has: the bytes of every file version
replaced or removed since it was taken
(`releases(): NativeJournalReleaseAccounting`,
`packages/ui-server/src/brain/native-journal-observer.ts:512-516`).
`packages/ui-server/src/brain/native-journal-observer.ts:520-524`).
Directory and other metadata extents are not counted. The store's free space,
which the `free_space_floor` scope limit reads, counts the actual extents until
each release completes. Shutdown waits for every queued release, retries
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ until genuine settlement, rather than authorizing their replacement
`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1375-1425`).
The native lease manager retains its own pending operations and durable unknown
root outcomes through close (`return { client, writer, recoverDeadOwners`,
`packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline
`packages/ui-server/src/brain/native-brain-leases.ts:319-332`). A caller deadline
is not proof that native I/O stopped, cleanup succeeded or deletion completed.
Keep the proposed partial/unknown outcome and identity fence while that cleanup
remains owned; follow the existing [shutdown ownership contract](../decisions/sqlite-write-worker.md#bounded-caller-waits-retain-real-cleanup-ownership-3185).
Expand Down
31 changes: 27 additions & 4 deletions packages/ui-server/src/brain/native-brain-leases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,17 @@ export async function createNativeBrainLeaseManager(raw: Client, options: {
return opened;
}); },
poolCheckpoint(id, from, signal) { return operation(async () => {
signal?.throwIfAborted();
// A worktree whose release never committed is assessable again (#2431).
await settleRelease(from, signal);
// A concurrent release of this identity must not acknowledge it while this call can still record a lease.
unleased.delete(id);
try {
signal?.throwIfAborted();
// A worktree whose release never committed is assessable again (#2431).
await settleRelease(from, signal);
} catch (error) {
// Refused before any lease of this identity was recorded (#3528).
if (!poolRow(id)) unleased.set(id, from);
throw error;
}
await leases.call("poolCheckpointIntent", id, from, REFERENCE_POOL_CHECKPOINT_BYTES);
const record = await raw.poolCheckpoint(id, from, signal);
if (record.id !== id || record.purpose !== "checkpoint" || record.from !== from || record.state !== "sealed" || record.readOnly !== true)
Expand Down Expand Up @@ -229,7 +237,15 @@ export async function createNativeBrainLeaseManager(raw: Client, options: {
}); },
poolRelease(id, signal) { return operation(async () => {
const lease = poolRow(id);
if (!lease) throw new NativeBrainManagerError("unknown", "This reference pool identity has no recorded app lease; arbitrary pool roots cannot be deleted.");
if (!lease) {
// Nothing was created for a checkpoint this owner refused before its
// lease: the caller's cleanup ends without asking the pool to delete anything.
const from = unleased.get(id);
if (from !== undefined && unleased.delete(id))
return { id, purpose: "checkpoint", from, allowanceBytes: REFERENCE_POOL_CHECKPOINT_BYTES, state: "deleted", root: null, path: null, ownerBytes: null,
reason: "The checkpoint was refused before its lease was recorded; no root was created.", view: null, access: null };
throw new NativeBrainManagerError("unknown", "This reference pool identity has no recorded app lease; arbitrary pool roots cannot be deleted.");
}
if (db.query("SELECT 1 FROM native_pool_leases WHERE from_id=? AND state='creating' LIMIT 1").get(id))
throw new NativeBrainManagerError("unavailable", "A reference snapshot is still being created from this root.");
// Survives a lost reply; a retry continues the same identity's release.
Expand All @@ -250,6 +266,13 @@ export async function createNativeBrainLeaseManager(raw: Client, options: {
return releaseOwned(lease, signal);
}); },
};
/**
* Checkpoint identities, and their worktree, that this owner refused before
* recording any lease (#3528). Their caller still holds the identity, and
* one release of each acknowledges that no root exists. Any other identity
* without a lease stays undeletable.
*/
const unleased = new Map<string, string>();
/** Releases in flight per pool identity in this owner; a settled intent never overrides a newer one. */
const releases = new Map<string, number>();
async function poolRecord(id: string, signal?: AbortSignal): Promise<NativePoolRecord | null> {
Expand Down
5 changes: 5 additions & 0 deletions packages/ui-server/src/brain/native-journal-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ export interface NativeJournalManager {
delta(from: string, to: string, signal?: AbortSignal): Promise<{
stream: ReadableStream<Uint8Array>; completed: Promise<{ exitCode: 0; bytes: number }>;
}>;
/**
* Also called for an identity whose `checkpoint` was refused. A manager
* that refused it before recording any lease acknowledges that nothing
* remains to release (#3528); otherwise the observer keeps the identity.
*/
release(id: string, signal?: AbortSignal): Promise<unknown>;
readCheckpoint?: ReturnType<typeof createNativeBrainManagerClient>["readCheckpoint"];
statCheckpoint?: ReturnType<typeof createNativeBrainManagerClient>["statCheckpoint"];
Expand Down
10 changes: 8 additions & 2 deletions packages/ui-server/src/brain/reference-worktree-journal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,21 @@ export const REFERENCE_WORKTREE_JOURNAL_SCOPE = "reference_worktree";
export interface ReferenceWorktreeCheckpointLedger { record(id: string, worktreeId: string): void; forget(id: string): void }

export function referenceWorktreeJournalManager(pool: ReferenceWorktreeJournalPool, worktreeId: string, ledger?: ReferenceWorktreeCheckpointLedger): NativeJournalManager {
// Identities whose ledger record failed: the pool never saw them, so their
// release only forgets whatever of the record may have committed (#3528).
const unsent = new Set<string>();
return {
async checkpoint(id, signal) {
await ledger?.record(id, worktreeId);
try { await ledger?.record(id, worktreeId); } catch (error) { unsent.add(id); throw error; }
const checkpoint = await pool.poolCheckpoint(id, worktreeId, signal);
if (checkpoint.from !== worktreeId || !checkpoint.path || !checkpoint.root) throw new Error("Worktree checkpoint reply does not name its worktree.");
return { id: checkpoint.id, path: checkpoint.path, uuid: checkpoint.root.uuid, transaction: checkpoint.transaction, readOnly: true };
},
delta: (from, to, signal) => pool.poolDelta(from, to, signal),
async release(id, signal) { const result = await pool.poolRelease(id, signal); await ledger?.forget(id); return result; },
async release(id, signal) {
if (unsent.has(id)) { await ledger?.forget(id); unsent.delete(id); return { id, state: "deleted" }; }
const result = await pool.poolRelease(id, signal); await ledger?.forget(id); return result;
},
readCheckpoint: (id, path, maximum, workerUid, signal) => pool.poolReadCheckpoint(id, path, maximum, workerUid, signal),
statCheckpoint: (id, path, workerUid, signal) => pool.poolStatCheckpoint(id, path, workerUid, signal),
listCheckpoint: (id, path, workerUid, signal) => pool.poolListCheckpoint(id, path, workerUid, signal),
Expand Down
105 changes: 105 additions & 0 deletions packages/ui-server/tests/native-brain-leases.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { createNativeBrainLeaseManager } from "../src/brain/native-brain-leases.js";
import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js";
import { createNativeJournalObserver } from "../src/brain/native-journal-observer.js";
import { referenceWorktreeJournalManager, type ReferenceWorktreeCheckpointLedger } from "../src/brain/reference-worktree-journal.js";

const ID = "11111111-1111-4111-8111-111111111790", OTHER = "22222222-2222-4222-8222-222222221790";
async function fixture() {
Expand Down Expand Up @@ -355,6 +357,109 @@ test("pool leases recorded before checkpoints migrate without losing a row", asy
} finally { state.close(); await owner.close().catch(() => {}); await native.close(); rmSync(root, { recursive: true, force: true }); }
});

/**
* One held worktree under the real lease owner, observed through the real
* worktree journal manager and observer (#3528). The raw pool records every
* request it receives; by default it creates and deletes nothing.
*/
async function worktreeObservation() {
const f = await fixture(), calls: string[] = [];
const SOURCE = "33333333-3333-4333-8333-333333333528", WORKTREE = "44444444-4444-4444-8444-444444443528";
const record = (id: string, purpose: string, from: string | null, state: string) =>
({ id, purpose, from, allowanceBytes: 4096, state, root: null, path: null, ownerBytes: null, reason: null, view: null, access: null }) as never;
f.native.client.poolCreate = async (id, purpose, from) => record(id, purpose, from, "writable");
f.native.client.poolCheckpoint = async id => { calls.push(`checkpoint:${id}`); throw new Error("the pool created no checkpoint"); };
f.native.client.poolRelease = async id => { calls.push(`release:${id}`); return record(id, "checkpoint", WORKTREE, "reclaimed"); };
await f.owner.client.poolCreate(SOURCE, "source", null, 4096);
await f.owner.client.poolCreate(WORKTREE, "worktree", SOURCE, 4096);
const recorded = new Set<string>();
const ledger: ReferenceWorktreeCheckpointLedger = { record: id => { recorded.add(id); }, forget: id => { recorded.delete(id); } };
const observer = createNativeJournalObserver(referenceWorktreeJournalManager(f.owner.client, WORKTREE, ledger));
const checkpointLeases = () => f.state.query("SELECT id,state FROM native_pool_leases WHERE purpose='checkpoint'").all();
return { ...f, calls, WORKTREE, ledger, recorded, observer, checkpointLeases };
}
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done; }); return { promise, resolve }; };
const abortable = (signal?: AbortSignal) => new Promise<never>((_, reject) => {
if (signal?.aborted) reject(signal.reason); else signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
});

test("a worktree observation aborted while its checkpoint is being recorded closes with nothing retained (#3528)", async () => {
const w = await worktreeObservation(), entered = deferred(), resume = deferred();
let id = "";
w.ledger.record = async checkpointId => { id = checkpointId; w.recorded.add(checkpointId); entered.resolve(); await resume.promise; };
try {
const controller = new AbortController(), reason = new Error("the turn was cancelled");
const initialized = w.observer.initialize(controller.signal).then(() => null, error => error);
await entered.promise;
controller.abort(reason); resume.resolve();
expect(await initialized, "WORKTREE_LEDGER_WAIT_ABORT_REFUSES_INITIALIZATION").toBe(reason);
await w.observer.close();
expect(w.recorded.size, "WORKTREE_LEDGER_WAIT_ABORT_FORGETS_ITS_RECORD").toBe(0);
expect(w.calls, "WORKTREE_LEDGER_WAIT_ABORT_ASKS_THE_POOL_NOTHING").toEqual([]);
expect(w.checkpointLeases(), "WORKTREE_LEDGER_WAIT_ABORT_RECORDS_NO_LEASE").toEqual([]);
// The acknowledgment is spent: the identity is again one no lease covers.
await expectRejection(w.owner.client.poolRelease(id), "no recorded app lease", "WORKTREE_REFUSED_CHECKPOINT_ACKNOWLEDGED_ONCE");
await expectRejection(w.owner.client.poolRelease(OTHER), "no recorded app lease", "WORKTREE_UNLEASED_ROOT_STAYS_UNDELETABLE");
expect(w.calls).toEqual([]);
} finally { resume.resolve(); await w.close(); }
});

test("a worktree observation aborted while the owner settles the worktree's release closes with nothing retained (#3528)", async () => {
const w = await worktreeObservation(), listing = deferred();
// An interrupted release of the worktree makes the owner ask the pool before recording the checkpoint's lease.
w.state.query("UPDATE native_pool_leases SET state='releasing' WHERE id=?").run(w.WORKTREE);
w.native.client.listPoolRecovery = async (_after, signal) => { listing.resolve(); return abortable(signal); };
try {
const controller = new AbortController(), reason = new Error("the turn was cancelled");
const initialized = w.observer.initialize(controller.signal).then(() => null, error => error);
await listing.promise;
controller.abort(reason);
expect(await initialized, "WORKTREE_SETTLE_WAIT_ABORT_REFUSES_INITIALIZATION").toBe(reason);
await w.observer.close();
expect(w.recorded.size, "WORKTREE_SETTLE_WAIT_ABORT_FORGETS_ITS_RECORD").toBe(0);
expect(w.calls, "WORKTREE_SETTLE_WAIT_ABORT_ASKS_THE_POOL_NOTHING").toEqual([]);
expect(w.checkpointLeases(), "WORKTREE_SETTLE_WAIT_ABORT_RECORDS_NO_LEASE").toEqual([]);
expect(w.state.query("SELECT state FROM native_pool_leases WHERE id=?").get(w.WORKTREE), "WORKTREE_SETTLE_WAIT_ABORT_KEEPS_THE_RELEASE_INTENT").toEqual({ state: "releasing" });
} finally { await w.close(); }
});

test("a worktree checkpoint ledger record that fails asks the pool nothing and leaves nothing retained (#3528)", async () => {
const w = await worktreeObservation();
w.ledger.record = async id => { w.recorded.add(id); throw new Error("the ledger write was lost"); };
try {
await expectRejection(w.observer.initialize(), "the ledger write was lost");
await w.observer.close();
expect(w.recorded.size, "WORKTREE_LEDGER_FAILURE_FORGETS_ITS_RECORD").toBe(0);
expect(w.calls, "WORKTREE_LEDGER_FAILURE_ASKS_THE_POOL_NOTHING").toEqual([]);
} finally { await w.close(); }
});

test("a worktree checkpoint aborted after its lease is recorded keeps retryable cleanup ownership (#3528)", async () => {
const w = await worktreeObservation(), creating = deferred();
w.native.client.poolCheckpoint = async (id, _from, signal) => { w.calls.push(`checkpoint:${id}`); creating.resolve(); return abortable(signal); };
w.native.client.listPoolRecovery = async () => ({ records: [], next: null });
let failRelease = true;
w.native.client.poolRelease = async id => {
w.calls.push(`release:${id}`);
if (failRelease) throw new Error("the manager connection dropped");
return { id, purpose: "checkpoint", from: w.WORKTREE, allowanceBytes: 4096, state: "reclaimed", root: null, path: null, ownerBytes: 0, reason: null, view: null, access: null } as never;
};
try {
const controller = new AbortController(), reason = new Error("the turn was cancelled");
const initialized = w.observer.initialize(controller.signal).then(() => null, error => error);
await creating.promise;
controller.abort(reason);
expect(await initialized).toBe(reason);
await expectRejection(w.observer.close(), "remain retained after shutdown", "WORKTREE_LEASED_CHECKPOINT_STAYS_RETAINED");
const [id] = [...w.recorded];
expect(w.checkpointLeases(), "WORKTREE_LEASED_CHECKPOINT_KEEPS_ITS_LEASE").toEqual([{ id, state: "releasing" }]);
expect(w.calls, "WORKTREE_LEASED_CHECKPOINT_RELEASE_REACHES_THE_POOL").toEqual([`checkpoint:${id}`, `release:${id}`, `release:${id}`]);
failRelease = false;
expect((await w.owner.client.poolRelease(id)).state, "WORKTREE_LEASED_CHECKPOINT_RELEASE_RETRIES").toBe("reclaimed");
expect(w.checkpointLeases()).toEqual([]);
} finally { await w.close(); }
});

/** A manager double that records turn-tree calls (#2911); `refuse` makes the next release fail, as a live reader does. */
function treeManager(f: Awaited<ReturnType<typeof fixture>>) {
const calls: string[] = [], before: unknown[] = [];
Expand Down
Loading