Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/devdocs/__serial__/lifecycle.test.ts

Raw
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { afterEach, expect, it, vi } from "vitest";
import { countTokens, Devdocs } from "../src/engine.ts";
import type {
	Adapter,
	Candidate,
	Document,
	Options,
	Request,
	SearchResult,
} from "../src/types.ts";

const roots: string[] = [];
const engines: Devdocs[] = [];
afterEach(async () => {
	vi.restoreAllMocks();
	// Every worker sharing a store must exit before its owned directory is removed.
	const closed = await Promise.allSettled(
		engines.splice(0).map((engine) => engine.close()),
	);
	const failures = closed.filter((result) => result.status === "rejected");
	if (failures.length)
		throw new Error(`worker cleanup failed: ${JSON.stringify(failures)}`);
	await Promise.all(
		roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
	);
});

async function store() {
	const root = await mkdtemp(join(tmpdir(), "devdocs-lifecycle-"));
	roots.push(root);
	return root;
}
function open(
	root: string,
	adapter: Adapter,
	overrides: Partial<Options> = {},
) {
	const engine = new Devdocs(
		{
			databasePath: join(root, "cache.db"),
			enabledSources: [adapter.id],
			sources: [],
			offline: false,
			cacheBytes: 128 * 1024,
			ttlMs: 60000,
			...overrides,
		},
		[adapter],
	);
	engines.push(engine);
	return engine;
}
function request(cwd: string): Request {
	return {
		cwd,
		target: "Widget",
		query: "transactions",
		version: "3",
		signal: AbortSignal.timeout(5000),
	};
}
function hits(result: SearchResult) {
	expect(result.status, JSON.stringify(result)).toBe("ok");
	if (result.status !== "ok") throw new Error(JSON.stringify(result));
	expect(result.results.length).toBeGreaterThan(0);
	return result.results;
}
function fixture() {
	const candidate: Candidate = {
		id: "widget",
		target: "Widget",
		version: "3.2.1",
		origin: "https://docs.example/widget/3/transactions",
		title: "Widget transactions",
		source: "synthetic",
		scope: "public",
		evidence: "fixture release 3.2.1",
	};
	const state = {
		bodies: ["Transactions commit atomically. Revision one."],
		validator: "revision-1",
		unchanged: false,
		failure: false,
		gate: undefined as ReturnType<typeof barrier> | undefined,
	};
	const discover = vi.fn<Adapter["discover"]>(async (r) => {
		r.signal?.throwIfAborted();
		if (state.failure) throw new Error("synthetic provider unavailable");
		return [{ ...candidate }];
	});
	const retrieve = vi.fn<Adapter["retrieve"]>(async (c, r) => {
		if (state.gate) await state.gate.wait(r.signal);
		r.signal?.throwIfAborted();
		if (state.failure) throw new Error("synthetic provider unavailable");
		if (state.unchanged) return "unchanged";
		return {
			candidate: { ...c },
			sections: state.bodies.map((body, i) => ({
				locator: `section-${i}`,
				heading: `Transactions ${i}`,
				body,
			})),
			attribution: "Synthetic fixture, CC0",
			validator: state.validator,
		};
	});
	const adapter: Adapter = {
		id: candidate.source,
		rank: 2,
		formatVersion: 1,
		coverage: "corpus",
		discover,
		retrieve,
	};
	return { adapter, candidate, state, discover, retrieve };
}
function barrier() {
	let release!: () => void;
	let entered!: () => void;
	const ready = new Promise<void>((resolve) => {
		entered = resolve;
	});
	const released = new Promise<void>((resolve) => {
		release = resolve;
	});
	return {
		release,
		ready: () => bounded(ready),
		async wait(signal?: AbortSignal) {
			entered();
			await bounded(released, signal);
		},
	};
}
async function bounded<T>(
	promise: Promise<T>,
	signal?: AbortSignal,
): Promise<T> {
	const deadline = AbortSignal.any([
		AbortSignal.timeout(3000),
		...(signal ? [signal] : []),
	]);
	deadline.throwIfAborted();
	let abort!: () => void;
	const aborted = new Promise<never>((_resolve, reject) => {
		abort = () => reject(new Error("fixture wait aborted"));
		deadline.addEventListener("abort", abort, { once: true });
	});
	try {
		return await Promise.race([promise, aborted]);
	} finally {
		deadline.removeEventListener("abort", abort);
	}
}

it.each(
	["3", undefined].flatMap((version) =>
		["3.2.2", "3.9.0", null].map((served) => ({ version, served })),
	),
)(
	"retains discovered version when request $version retrieves $served",
	async ({ version, served }) => {
		const root = await store(),
			f = fixture(),
			engine = open(root, f.adapter);
		const r = { ...request(root), version };
		const before = hits(await engine.search(r));
		f.retrieve.mockResolvedValueOnce({
			candidate: { ...f.candidate, version: served },
			sections: [
				{
					locator: "wrong-release",
					heading: "Transactions",
					body: "Transactions from another release.",
				},
			],
			attribution: "Synthetic fixture, CC0",
			validator: "wrong-release",
		});
		const after = hits(await engine.search(r, true));
		expect(after.map((hit) => hit.ref)).toEqual(before.map((hit) => hit.ref));
		expect(
			after.every(
				(hit) => hit.version === "3.2.1" && hit.freshness === "stale",
			),
		).toBe(true);
		expect((await engine.status()).cache.revisions).toBe(1);
		expect((await engine.status()).cache.refreshing).toBe(0);
		expect(
			(await engine.read([before[0]!.ref], 2000, root)).sections[0]?.content,
		).toBe(f.state.bodies[0]);
	},
);

it("caps broad searches at ten ranked hits while narrower queries reach other retained sections", async () => {
	const root = await store(),
		f = fixture(),
		engine = open(root, f.adapter);
	f.state.bodies = Array.from(
		{ length: 20 },
		(_, i) => `Transactions witness${i}.`,
	);
	const broad = hits(await engine.search(request(root)));
	expect(broad).toHaveLength(10);
	const refs = new Set(broad.map((hit) => hit.ref));
	const revision = broad[0]!.ref.split(":")[0];
	const omitted = f.state.bodies.findIndex(
		(_, i) => !refs.has(`${revision}:${i}`),
	);
	expect(omitted).toBeGreaterThanOrEqual(0);
	const narrow = hits(
		await engine.search({ ...request(root), query: `witness${omitted}` }),
	);
	expect(narrow).toHaveLength(1);
	expect(refs.has(narrow[0]!.ref)).toBe(false);
	expect(
		(await engine.read([narrow[0]!.ref], 2000, root)).sections[0]?.content,
	).toBe(f.state.bodies[omitted]);
});

it("rejects embedded NUL before document publication while ordinary content remains searchable", async () => {
	const root = await store(),
		f = fixture(),
		docs = open(root, f.adapter);
	f.state.bodies = ["Transactions contain an embedded \u0000 character."];
	expect((await docs.search(request(root))).status).toBe("unavailable");
	expect((await docs.status()).cache.revisions).toBe(0);
	f.state.bodies = ["Transactions commit ordinary content safely."];
	f.state.validator = "ordinary";
	const found = hits(await docs.search(request(root), true));
	expect(
		(await docs.read([found[0]!.ref], 2000, root)).sections[0]?.content,
	).toBe(f.state.bodies[0]);
	expect((await docs.status()).cache.revisions).toBe(1);
});

it("reports saturated refresh slots without silently losing local docs or exceeding the job bound", async () => {
	const root = await store(),
		localFixture = fixture(),
		remoteFixture = fixture(),
		gate = barrier();
	remoteFixture.state.gate = gate;
	const local: Adapter = {
		...localFixture.adapter,
		id: "local",
		rank: 1,
		discover: async (r) =>
			r.target === "Widget"
				? [{ ...localFixture.candidate, source: "local" }]
				: [],
	};
	const remote: Adapter = {
		...remoteFixture.adapter,
		id: "remote",
		discover: async (r) =>
			r.target === "Widget"
				? []
				: [
						{
							...remoteFixture.candidate,
							id: r.target,
							target: r.target,
							source: "remote",
							origin: "https://docs.example/" + r.target,
						},
					],
	};
	const engine = new Devdocs(
		{
			databasePath: join(root, "cache.db"),
			enabledSources: ["local", "remote"],
			sources: [],
			offline: false,
			cacheBytes: 128 * 1024,
			ttlMs: 60000,
		},
		[local, remote],
	);
	engines.push(engine);
	const pending = Promise.all(
		["remote-first", "remote-second"].map((target) =>
			engine.search({ ...request(root), target }),
		),
	);
	try {
		await vi.waitFor(async () =>
			expect((await engine.status()).cache.refreshing).toBe(2),
		);
		const result = await engine.search(request(root));
		expect(result.status).toBe("unavailable");
		if (result.status !== "unavailable")
			throw new Error("expected saturated sources");
		expect(
			result.reasons.some(
				(reason) => reason.startsWith("local:") && reason.includes("busy"),
			),
		).toBe(true);
		expect(localFixture.retrieve).not.toHaveBeenCalled();
		expect((await engine.status()).cache.refreshing).toBe(2);
	} finally {
		gate.release();
		await pending;
	}
	const recovered = hits(await engine.search(request(root)));
	expect(recovered[0]?.source).toBe("local");
	expect(
		(await engine.read([recovered[0]!.ref], 2000, root)).sections[0]?.content,
	).toBe(localFixture.state.bodies[0]);
	expect((await engine.status()).cache.refreshing).toBe(0);
});

it("cancels a caller's wait without cancelling the shared bounded refresh job", async () => {
	const root = await store(),
		f = fixture(),
		docs = open(root, f.adapter),
		gate = barrier();
	f.state.gate = gate;
	const controller = new AbortController();
	const pending = docs.search({ ...request(root), signal: controller.signal });
	await gate.ready();
	controller.abort();
	await expect(pending).rejects.toThrow(/abort/i);
	expect((await docs.status()).cache.refreshing).toBe(1);
	gate.release();
	await vi.waitFor(
		async () => expect((await docs.status()).cache.refreshing).toBe(0),
		{ timeout: 3000, interval: 10 },
	);
	expect(hits(await docs.search(request(root)))[0]?.version).toBe("3.2.1");
});

it("keeps the installed version when falling back from irrelevant local help", async () => {
	const root = await store(),
		f = fixture();
	const local: Adapter = {
		...f.adapter,
		id: "local",
		rank: 1,
		discover: async () => [
			{ ...f.candidate, source: "local", version: "3.2.1" },
		],
		retrieve: async (c) => ({
			candidate: c,
			sections: [
				{
					locator: "help",
					heading: "Installation",
					body: "Unrelated installation reference.",
				},
			],
			attribution: "Installed",
			validator: null,
		}),
	};
	const network: Adapter = {
		...f.adapter,
		discover: vi.fn(async (r) => [
			{ ...f.candidate, version: r.version ?? "9.0.0" },
		]),
	};
	const docs = new Devdocs(
		{
			databasePath: join(root, "cache.db"),
			enabledSources: ["local", network.id],
			sources: [],
			offline: false,
			cacheBytes: 128 * 1024,
			ttlMs: 60000,
		},
		[local, network],
	);
	engines.push(docs);
	const found = hits(
		await docs.search({ ...request(root), version: undefined }),
	);
	expect(found[0]?.version).toBe("3.2.1");
	expect(found[0]?.requestedVersion).toBeNull();
	expect(
		(await docs.read([found[0]!.ref], 2000, root)).sections[0]
			?.requestedVersion,
	).toBeNull();
});

it("keeps content fragments and continuations stable while live freshness metadata changes", async () => {
	const root = await store(),
		f = fixture(),
		docs = open(root, f.adapter);
	f.state.bodies = ["Transactions " + "Unicode α😀 text ".repeat(300)];
	const ref = hits(await docs.search(request(root)))[0]!.ref;
	const fresh = await docs.read([ref], 1000, root);
	const db = new DatabaseSync(join(root, "cache.db"));
	db.prepare("UPDATE docs SET checked=?").run(Date.now() - 120000);
	db.close();
	const stale = await docs.read([ref], 1000, root);
	expect(fresh.sections[0]?.freshness).toBe("fresh");
	expect(stale.sections[0]?.freshness).toBe("stale");
	expect(stale.sections[0]?.checkedAt).not.toBe(fresh.sections[0]?.checkedAt);
	expect(stale.sections.map((s) => s.content)).toEqual(
		fresh.sections.map((s) => s.content),
	);
	expect(stale.continuation).toEqual(fresh.continuation);
	expect([...JSON.stringify(stale)].length).toBeLessThanOrEqual(1000);
});

it("restarts offline with warmed discovery and sections without any adapter calls", async () => {
	const root = await store();
	const f = fixture();
	const online = open(root, f.adapter);
	const found = hits(await online.search(request(root)));
	const original = await online.read([found[0]!.ref], 2000, root);
	expect(original.sections[0]?.content).toBe(f.state.bodies[0]);
	await online.close();
	f.discover.mockClear();
	f.retrieve.mockClear();
	f.state.failure = true;
	const offline = open(root, f.adapter, { offline: true, ttlMs: 0 });
	const cached = hits(await offline.search(request(root)));
	expect(cached[0]?.ref).toBe(found[0]?.ref);
	expect(cached[0]?.freshness).toBe("stale");
	const read = await offline.read([cached[0]!.ref], 2000, root);
	expect(read.sections[0]?.content).toBe(original.sections[0]?.content);
	expect(read.sections[0]?.freshness).toBe("stale");
	expect(f.discover).not.toHaveBeenCalled();
	expect(f.retrieve).not.toHaveBeenCalled();
});

it.each(["unchanged", "replacement"] as const)(
	"serves stale refs during background %s and retains the previous revision",
	async (mode) => {
		const root = await store();
		const f = fixture();
		const engine = open(root, f.adapter);
		const initial = hits(await engine.search(request(root)))[0]!;
		const original = f.state.bodies[0];
		f.state.unchanged = mode === "unchanged";
		f.state.bodies = ["Transactions commit atomically. Revision two."];
		f.state.validator = "revision-2";
		const gate = barrier();
		f.state.gate = gate;
		const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 120000);
		try {
			const stale = hits(await engine.search(request(root)))[0]!;
			expect(stale.ref).toBe(initial.ref);
			expect(stale.freshness).toBe("stale");
			await gate.ready();
			expect(
				(await engine.read([initial.ref], 2000, root)).sections[0]?.content,
			).toBe(original);
			expect(f.retrieve.mock.calls[1]?.[2]).toBe("revision-1");
		} finally {
			clock.mockRestore();
			gate.release();
		}
		await vi.waitFor(
			async () => expect((await engine.status()).cache.refreshing).toBe(0),
			{ timeout: 3000, interval: 10 },
		);
		await engine.close();
		const restarted = open(root, f.adapter, { offline: true });
		const current = hits(await restarted.search(request(root)))[0]!;
		expect(current.freshness).toBe("fresh");
		if (mode === "unchanged") expect(current.ref).toBe(initial.ref);
		else expect(current.ref).not.toBe(initial.ref);
		expect(
			(await restarted.read([current.ref], 2000, root)).sections[0]?.content,
		).toBe(mode === "unchanged" ? original : f.state.bodies[0]);
		expect(
			(await restarted.read([initial.ref], 2000, root)).sections[0]?.content,
		).toBe(original);
	},
);

it("failed refresh retains stale content and refs across restart", async () => {
	const root = await store();
	const f = fixture();
	const engine = open(root, f.adapter, { ttlMs: 0 });
	const initial = hits(await engine.search(request(root)))[0]!;
	f.state.failure = true;
	const failed = await engine.search(request(root), true);
	const retained = hits(failed)[0]!;
	expect(retained.ref).toBe(initial.ref);
	expect(retained.freshness).toBe("stale");
	if (failed.status === "ok")
		expect(failed.reasons.join(" ")).toMatch(/fail|unavailable/i);
	expect(f.retrieve).toHaveBeenCalledTimes(2);
	await engine.close();
	const restarted = open(root, f.adapter, { offline: true, ttlMs: 0 });
	expect(hits(await restarted.search(request(root)))[0]?.ref).toBe(initial.ref);
	expect(
		(await restarted.read([initial.ref], 2000, root)).sections[0]?.content,
	).toBe(f.state.bodies[0]);
});

it("bounds aggregate serialized reads and reconstructs every Unicode code point through advancing continuations", async () => {
	const root = await store();
	const f = fixture();
	f.state.bodies = [
		"Transactions " + 'A😀e\u0301漢\n"\\'.repeat(500),
		"Transactions " + "β🧑‍💻\r\nZ".repeat(400),
	];
	const engine = open(root, f.adapter);
	const refs = hits(await engine.search(request(root))).map((hit) => hit.ref);
	expect(refs).toHaveLength(2);
	const full = await engine.read(refs, 64000, root);
	// Search relevance, not fixture insertion order, determines ref ordering.
	expect(full.sections.map((section) => section.content).sort()).toEqual(
		[...f.state.bodies].sort(),
	);
	const expected = new Map(
		full.sections.map((section) => [section.ref, section.content]),
	);
	const reconstructed = new Map(refs.map((ref) => [ref, ""]));
	const seen = new Set<string>();
	let pending = refs;
	for (let page = 0; page < 40; page++) {
		const cursor = JSON.stringify(pending);
		expect(seen.has(cursor), "continuation repeated").toBe(false);
		seen.add(cursor);
		const read = await engine.read(pending, 2000, root);
		expect([...JSON.stringify(read)].length).toBeLessThanOrEqual(2000);
		expect(read).toEqual(await engine.read(pending, 2000, root));
		expect(read.sections.length).toBeGreaterThan(0);
		for (const section of read.sections) {
			expect(section.content.length).toBeGreaterThan(0);
			const prior = reconstructed.get(section.ref);
			expect(prior).toBeDefined();
			const combined = prior! + section.content;
			expect(expected.get(section.ref)?.startsWith(combined)).toBe(true);
			reconstructed.set(section.ref, combined);
		}
		expect(read.truncated).toBe(read.continuation.length > 0);
		if (!read.truncated) {
			pending = [];
			break;
		}
		const next = read.continuation[0]!;
		const base = next.split(":").slice(0, 2).join(":");
		expect(Number(next.split(":")[2] ?? 0)).toBe(
			[...(reconstructed.get(base) ?? "")].length,
		);
		pending = read.continuation;
	}
	expect(pending, "continuations exceeded bounded page count").toEqual([]);
	expect(reconstructed).toEqual(expected);
});

it.each([
	["", 0],
	["ASCII", 5],
	["A😀B", 3],
	["e\u0301", 2],
	["\ud800", 1],
	["\udc00", 1],
	["\ud800\udc00", 1],
	['\u0000\b\t\n\f\r\u001f"\\', 9],
] as const)("counts Unicode code points in %j", (text, expected) => {
	expect(countTokens(text)).toBe(expected);
});

it.each([1, 2, 20])(
	"preserves ordered %i-ref reads at aggregate budget boundaries",
	async (count) => {
		const root = await store();
		const f = fixture();
		f.state.bodies = Array.from(
			{ length: count },
			(_, i) => `Transactions ${i} ` + 'A😀e\u0301漢\n"\\\t'.repeat(20),
		);
		const engine = open(root, f.adapter);
		const revision = hits(await engine.search(request(root)))[0]!.ref.split(
			":",
		)[0];
		// Section ordinals follow the fixture's published document order.
		const refs = Array.from(
			{ length: count },
			(_, i) => `${revision}:${count - i - 1}`,
		);
		const full = await engine.read(refs, 64000, root);
		expect(full.sections.map((section) => section.ref)).toEqual(refs);
		expect(full.sections.map((section) => section.content)).toEqual(
			[...f.state.bodies].reverse(),
		);
		expect(full.truncated).toBe(false);
		expect(full.continuation).toEqual([]);
		const fullSize = [...JSON.stringify(full)].length;
		for (const budget of [fullSize - 1, fullSize, fullSize + 100]) {
			const read = await engine.read(refs, budget, root);
			expect([...JSON.stringify(read)].length).toBeLessThanOrEqual(budget);
			expect(read.sections.map((section) => section.ref)).toEqual(
				refs.slice(0, read.sections.length),
			);
			expect(read.truncated).toBe(read.continuation.length > 0);
			for (const section of read.sections) {
				const ordinal = Number(section.ref.split(":")[1]);
				expect(section.content.length).toBeGreaterThan(0);
				expect(f.state.bodies[ordinal]?.startsWith(section.content)).toBe(true);
			}
			if (budget === fullSize + 100) expect(read).toEqual(full);
		}
	},
);

it("rejects too-small budgets before opening storage and explicitly rejects metadata-only budgets", async () => {
	const root = await store();
	const f = fixture();
	const engine = open(root, f.adapter);
	const call = vi.spyOn(engine.cache, "call");
	await expect(engine.read(["not-a-ref"], 511, root)).rejects.toThrow(
		/budget/i,
	);
	expect(call).not.toHaveBeenCalled();
	// Valid provenance can itself exceed the minimum accepted budget.
	f.state.bodies = ["Transactions commit."];
	f.candidate.origin += "/" + "long-provenance".repeat(80);
	const ref = hits(await engine.search(request(root)))[0]!.ref;
	await expect(engine.read([ref], 512, root)).rejects.toThrow(
		/budget.*insufficient/i,
	);
});

it("rejects disabled-source refs without discovery or retrieval", async () => {
	const root = await store();
	const f = fixture();
	const engine = open(root, f.adapter);
	const ref = hits(await engine.search(request(root)))[0]!.ref;
	await engine.close();
	f.discover.mockClear();
	f.retrieve.mockClear();
	const disabled = open(root, f.adapter, { enabledSources: [] });
	await expect(disabled.read([ref], 2000, root)).rejects.toThrow(
		/source-disabled/,
	);
	expect((await disabled.search(request(root))).status).toBe("unavailable");
	expect(f.discover).not.toHaveBeenCalled();
	expect(f.retrieve).not.toHaveBeenCalled();
});

it.each(["reconfigured", "private-cwd"] as const)(
	"denies same-ID refs outside their %s source context",
	async (mode) => {
		const root = await store();
		const f = fixture();
		const source = {
			id: f.adapter.id,
			target: "Widget",
			path: join(root, "registered.md"),
			version: "3.2.1",
			format: "markdown" as const,
			private: mode === "private-cwd",
		};
		const engine = open(root, f.adapter, { sources: [source] });
		const ref = hits(await engine.search(request(root)))[0]!.ref;
		expect((await engine.read([ref], 2000, root)).sections[0]?.content).toBe(
			f.state.bodies[0],
		);
		await engine.close();
		const changed = open(root, f.adapter, {
			offline: true,
			sources: [
				{
					...source,
					path:
						mode === "reconfigured"
							? join(root, "replacement.md")
							: source.path,
				},
			],
		});
		await expect(
			changed.read(
				[ref],
				2000,
				mode === "private-cwd" ? join(root, "unrelated-project") : root,
			),
		).rejects.toThrow(/source-access/);
		expect(
			(
				await changed.search(
					request(
						mode === "private-cwd" ? join(root, "unrelated-project") : root,
					),
				)
			).status,
		).toBe("unavailable");
	},
);

it("parallel engines share a refresh lease and publish just one complete new revision", async () => {
	const root = await store();
	const f = fixture();
	const first = open(root, f.adapter);
	const original = hits(await first.search(request(root)))[0]!.ref;
	const second = open(root, f.adapter);
	// Open both workers before contention, avoiding schema-open timing as the oracle.
	await second.status();
	f.retrieve.mockClear();
	f.state.bodies = ["Transactions complete revision two."];
	const gate = barrier();
	f.state.gate = gate;
	const publishing = first.search(request(root), true);
	try {
		await gate.ready();
		const concurrent = hits(await second.search(request(root), true))[0]!;
		expect(concurrent.ref).toBe(original);
		expect(
			(await second.read([original], 2000, root)).sections[0]?.content,
		).toBe("Transactions commit atomically. Revision one.");
		expect(f.retrieve).toHaveBeenCalledTimes(1);
	} finally {
		gate.release();
		await publishing;
	}
	const published = hits(await publishing)[0]!;
	expect(published.ref).not.toBe(original);
	expect(hits(await second.search(request(root)))[0]?.ref).toBe(published.ref);
	expect(
		(await second.read([published.ref], 2000, root)).sections[0]?.content,
	).toBe(f.state.bodies[0]);
	expect((await second.status()).cache.revisions).toBe(2);
	expect(f.retrieve).toHaveBeenCalledTimes(1);
});

it("repeated refresh stays within capacity, expires evicted refs, and preserves the head on oversized admission failure", async () => {
	const root = await store();
	const f = fixture();
	const capacity = 16 * 1024;
	const engine = open(root, f.adapter, { cacheBytes: capacity, ttlMs: 0 });
	let last = "";
	let first = "";
	for (let revision = 0; revision < 10; revision++) {
		f.state.bodies = [
			`Transactions revision ${revision}. ` + "bounded payload ".repeat(150),
		];
		const current = hits(await engine.search(request(root), true))[0]!;
		expect(current.ref).not.toBe(last);
		last = current.ref;
		if (revision === 0) first = last;
		expect((await engine.read([last], 64000, root)).sections[0]?.content).toBe(
			f.state.bodies[0],
		);
		const status = (await engine.status()).cache;
		expect(status.bytes).toBeLessThanOrEqual(capacity);
		expect(status.revisions).toBeLessThanOrEqual(3);
	}
	await expect(engine.read([first], 2000, root)).rejects.toThrow(/expired-ref/);
	const retained = f.state.bodies[0];
	const before = (await engine.status()).cache;
	f.state.bodies = ["Transactions " + "oversized ".repeat(2000)];
	const failed = await engine.search(request(root), true);
	expect(hits(failed)[0]?.ref).toBe(last);
	if (failed.status === "ok")
		expect(failed.reasons.join(" ")).toMatch(/capacity/);
	expect((await engine.read([last], 64000, root)).sections[0]?.content).toBe(
		retained,
	);
	const after = (await engine.status()).cache;
	expect(after.bytes).toBeLessThanOrEqual(capacity);
	expect(after.revisions).toBe(before.revisions);
	await engine.close();
	const offline = open(root, f.adapter, {
		cacheBytes: capacity,
		offline: true,
	});
	expect(hits(await offline.search(request(root)))[0]?.ref).toBe(last);
	expect((await offline.read([last], 64000, root)).sections[0]?.content).toBe(
		retained,
	);
});

it("does not evict another target's prior revision while its refresh lease is active", async () => {
	const root = await store(),
		f = fixture(),
		docs = open(root, f.adapter);
	const first: Document = {
		candidate: f.candidate,
		sections: [
			{ locator: "one", heading: "Transactions", body: "A".repeat(1200) },
		],
		attribution: "Fixture",
		validator: "one",
	};
	const second: Document = {
		...first,
		candidate: { ...f.candidate, id: "other", target: "Other" },
		sections: [{ locator: "two", heading: "Other", body: "B".repeat(1200) }],
	};
	const revision = await docs.cache.call<string>("put", {
		key: "protected",
		document: first,
		capacity: 5000,
	});
	expect(
		await docs.cache.call("lease", {
			key: "protected",
			owner: "refresh-owner",
		}),
	).toBe(true);
	await expect(
		docs.cache.call("put", { key: "other", document: second, capacity: 5000 }),
	).rejects.toThrow(/capacity/);
	expect(await docs.cache.call("head", { key: "protected" })).toMatchObject({
		revision,
	});
	expect((await docs.cache.status()).revisions).toBe(1);
	await docs.cache.call("release", {
		key: "protected",
		owner: "refresh-owner",
	});
});

it("fences expired and superseded lease owners from publishing or validating at the Cache API", async () => {
	const root = await store();
	const f = fixture();
	const engine = open(root, f.adapter);
	// Explicit synthetic Cache key: independent of the engine's private key derivation.
	const key = "lifecycle-fencing-fixture";
	const document: Document = {
		candidate: f.candidate,
		sections: [
			{
				locator: "transactions",
				heading: "Transactions",
				body: "Original atomic transactions.",
			},
		],
		attribution: "CC0",
		validator: "one",
	};
	const cache = engine.cache;
	expect(await cache.call("lease", { key, owner: "old", now: 1000 })).toBe(
		true,
	);
	const revision = await cache.call<string>("put", {
		key,
		owner: "old",
		now: 1001,
		document,
		capacity: 128 * 1024,
	});
	expect(await cache.call("lease", { key, owner: "new", now: 1002 })).toBe(
		false,
	);
	await expect(
		cache.call("validate", { key, owner: "old", revision, now: 61000 }),
	).rejects.toThrow(/lease/);
	expect(await cache.call("lease", { key, owner: "new", now: 61000 })).toBe(
		true,
	);
	const replacement = {
		...document,
		sections: [
			{
				locator: "transactions",
				heading: "Transactions",
				body: "Replacement atomic transactions.",
			},
		],
		validator: "two",
	};
	await expect(
		cache.call("put", {
			key,
			owner: "old",
			now: 61001,
			document: replacement,
			capacity: 128 * 1024,
		}),
	).rejects.toThrow(/lease/);
	await expect(
		cache.call("validate", { key, owner: "old", revision, now: 61001 }),
	).rejects.toThrow(/lease/);
	expect(await cache.call("head", { key })).toMatchObject({
		revision,
		checked: 1001,
	});
	await cache.call("release", { key, owner: "old" });
	expect(
		await cache.call("lease", { key, owner: "intruder", now: 61002 }),
	).toBe(false);
	await cache.call("validate", { key, owner: "new", revision, now: 61003 });
	expect(await cache.call("head", { key })).toMatchObject({
		revision,
		checked: 61003,
	});
	const next = await cache.call<string>("put", {
		key,
		owner: "new",
		now: 61004,
		document: replacement,
		capacity: 128 * 1024,
	});
	expect(next).not.toBe(revision);
	expect(await cache.call("head", { key })).toMatchObject({
		revision: next,
		checked: 61004,
	});
});