Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

PR 4 E round 2: keep page embedding leases out of activation and deactivation checks

garrytan6ca00c727fa4
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index ea99db6f64..af5a6b23be 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`. Wave B: a segmented page is embedded by `page-body/segmented-embedding.ts` (vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here, `gbrain embed` and the post-commit embedding effect (`data.occurrence_ids` limits an append's effect to the new occurrences).
- `src/core/content-drift-sweep.ts` — the content-drift sweep (#4246) as a resumable pass: `runContentDriftSweep(engine, { sourceId?, signal?, deadline?, stopped?, assertOwned?, timeBudgetMs?, batchRows? })` runs `engine-sql/chunks.ts` `invalidateContentDriftBatch` (5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config row `embed.content_drift_sweep.<column>.<all|source:id>` with the batch under a `FOR UPDATE` lock on that row, so concurrent runs share one pass. A run stops at its 60 s budget, the job deadline or an abort; a completed pass restarts after `embed.content_drift.pass_interval_hours` (default 24) unless it fit in one batch. A failed batch is returned as `state: 'failed'` with the error and recorded as `last_error` (cleared by the next committed batch); a missing v133/v221 column is `unsupported`; an `assertOwned` throw propagates. `embedAllStale` (`EmbedResult.content_drift`), `embedStaleForSource` (`contentDrift`) and the embed, embed-backfill and cycle embed results carry the status; doctor `content_drift_sweep` reads the saved rows.
-- `src/core/page-embedding-lease.ts` — one provider call per chunk content version (gbrain-evals#180, N14). Every path that embeds a page's vector-less chunks holds the page's embedding lease from reading which chunks lack a vector through its install: the post-write embedding effect (`persistence/effects.ts`, inline and segmented), the `gbrain embed --stale` drain (`src/commands/embed.ts`), `embedStaleForSource` and `embedStalePages` (`embed-stale.ts`), and every segmented install (`embedSegmentedRows` in `page-body/segmented-embedding.ts`). `acquirePageEmbeddingLease` takes a `gbrain_cycle_locks` row `embed-page:<page id>` with plain statements (TTL 2 minutes, refreshed every 30 s while held, no process-liveness takeover), waiting with backoff while another path holds it; an effect renews its claim in `whileWaiting`. The wait is bounded by the caller's `deadline` (`embedStaleForSource` passes its drain deadline) or one TTL, and then returns a busy lease (`{ busy: true }`): drains skip the page without counting a failure, the effect and the segmented effect throw `pageEmbeddingLeaseUnavailable` (`lock_busy`, retried with backoff), and `embedSegmentedPage` stops with `stopped: 'busy'`. A held lease's `assertHeld(tx)` renews the row inside every install transaction and throws `lock_busy` when it matches no row (the lease expired and another path took or deleted it), so a holder that stalled past the TTL installs nothing; a background refresh that matches no row marks the lease lost the same way. `embedStalePages` looks the page id up first and reads its snapshot under the lease. Callers bind it with `await using`, so leaving the scope releases it, error paths included; each release also deletes expired `embed-page:` rows (a crashed holder's), which keeps doctor `stale_locks` from listing them past the next embed. The holder then keeps only the chunks still without a vector (inline: `stillPendingChunks` over the fresh `getChunks` read; segmented: `vectorlessChunkIndexes`), so a drain whose listing predates an effect's install sends nothing for them. `pageEmbeddingLeaseProbe` (`contended`, `waitBoundMs`) is the test seam. Forced probes (effect first on a segmented page after `append_page`, drain first on an inline page; both engines): `test/embed-once-per-content-version.serial.test.ts`; bounded wait, lost lease, snapshot under the lease, expired-row sweep and release on throw (both engines): `test/page-embedding-lease.serial.test.ts`.
+- `src/core/page-embedding-lease.ts` — one provider call per chunk content version (gbrain-evals#180, N14). Every path that embeds a page's vector-less chunks holds the page's embedding lease from reading which chunks lack a vector through its install: the post-write embedding effect (`persistence/effects.ts`, inline and segmented), the `gbrain embed --stale` drain (`src/commands/embed.ts`), `embedStaleForSource` and `embedStalePages` (`embed-stale.ts`), and every segmented install (`embedSegmentedRows` in `page-body/segmented-embedding.ts`). `acquirePageEmbeddingLease` takes a `gbrain_cycle_locks` row `embed-page:<page id>` with plain statements (TTL 2 minutes, refreshed every 30 s while held, no process-liveness takeover), waiting with backoff while another path holds it; an effect renews its claim in `whileWaiting`. The wait is bounded by the caller's `deadline` (`embedStaleForSource` passes its drain deadline) or one TTL, and then returns a busy lease (`{ busy: true }`): drains skip the page without counting a failure, the effect and the segmented effect throw `pageEmbeddingLeaseUnavailable` (`lock_busy`, retried with backoff), and `embedSegmentedPage` stops with `stopped: 'busy'`. A held lease's `assertHeld(tx)` renews the row inside every install transaction and throws `lock_busy` when it matches no row (the lease expired and another path took or deleted it), so a holder that stalled past the TTL installs nothing; a background refresh that matches no row marks the lease lost the same way. `embedStalePages` looks the page id up first and reads its snapshot under the lease. Callers bind it with `await using`, so leaving the scope releases it, error paths included; each release also deletes expired `embed-page:` rows (a crashed holder's), which keeps doctor `stale_locks` from listing them past the next embed. `NOT_PAGE_EMBEDDING_LEASE` (on `PAGE_EMBEDDING_LEASE_PREFIX`) keeps these rows, live or expired, out of activation's legacy-lock inspection (`persistence/legacy-locks.ts`), deactivation's lease blockers and shared-skill activation's quiescence check: a lease dedupes provider calls and guards vector installs that ran unleased before it, its holders run inside a lock, job lease or effect claim those checks already see, and a crashed holder's expired row must not block them (the writer admin fingerprint in `admin-intent.ts` skips them too). The holder then keeps only the chunks still without a vector (inline: `stillPendingChunks` over the fresh `getChunks` read; segmented: `vectorlessChunkIndexes`), so a drain whose listing predates an effect's install sends nothing for them. `pageEmbeddingLeaseProbe` (`contended`, `waitBoundMs`) is the test seam. Forced probes (effect first on a segmented page after `append_page`, drain first on an inline page; both engines): `test/embed-once-per-content-version.serial.test.ts`; bounded wait, lost lease, snapshot under the lease, expired-row sweep and release on throw (both engines): `test/page-embedding-lease.serial.test.ts`.
- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete: an unsealed page only in the `reimport` class (`page-state/projection-class.ts`; `sealable`, `protected` and `archived` are counted, never candidates), a sealed one with no `embedding_image` chunk or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true` (`incomplete_sealed`); `ocr_required` counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root; a page with no recorded `source_path` is located by its slug, which is the lower-cased repo-relative path, and counted in `missingSourcePath`) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes through `importManagedFile` (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records `source_path`. Reports candidates, rebuilt, unchanged, missing source files (`missing_samples`: up to 5 `source:slug: no file at <path tried>` lines, the first printed) and failures; the explicit `--images` CLI (`runEmbedStaleImagesCli`) counts an all-missing, nothing-rebuilt sweep as failures (`sweepFoundNoFiles`), so it never exits 0 as a quiet success. `runStaleImageSweepFirst` is the sweep a plain `gbrain embed --stale` (no `--slugs`) runs before its text drain when multimodal embedding is on, and `foldImageSweep` folds it into the `EmbedResult` as `images`: import failures count toward the run's failures, fileless pages are reported once on stderr (`missingFile`, first sample) and leave the exit code to the text run; a text-only install skips it and keeps the `--images` hint. Pinned by `test/embed-stale-images.test.ts` and `test/embed-stale-images-managed-6529.test.ts` (both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.
- `src/core/embed-budget-stop.ts` — the loud time-budget stop for `gbrain embed --stale`. `noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})` counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, sets `reason: 'time_budget'`, `remaining_stale` and `resume_command` (`gbrain embed --stale --catch-up [--source X] [--include-null-signature]`) on the result; `skip` covers dry runs, `--catch-up` and caller aborts. `embedBudgetStopVerdict(result)` is the stdout verdict `runEmbed` prints; `src/cli/commands/embed.ts` maps the reason to `BUDGET_STOP_EXIT_CODE` (failures still win with 1). Called from every budget exit in `embedAllStale` (readiness-phase deadline returns and the main drain). Pinned by `test/embed.serial.test.ts` ("time-budget stop is loud").
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9669c0ea0e..01dabbc010 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1041,7 +1041,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.332.0', text: 'One search or query chunk row returns at most 8,000 characters of chunk text by default, ending with the marker that names the read for the rest (an old oversized chunk could return tens of thousands). Pass `snippet_chars: 0` for the full chunk. Evidence blocks (conversations, long-page units) keep their own budget and cap.' },
{ since: '0.60.332.0', text: '`gbrain search --explain` and `gbrain query --explain` now pass explain to the search, so `score_details` reports the arms, RRF and blend that ran; before, every row said `single_arm_path` / `no_query_embedding` even when both arms ran. A CLI search or query whose keyword or vector arm failed or timed out now prints the `degraded_recall` notice on stderr (the `--json` array stays bare), as MCP already did.' },
// PR 4 E (one provider call per chunk content version, gbrain-evals#180). `since` is stamped at the merge slot.
- { since: 'TBD', text: 'A page\'s new chunks now go to the embedding provider once per content version. The post-write embedding effect, `gbrain embed --stale`, the embed-backfill job and phase-end embeds each hold a per-page lease (a `gbrain_cycle_locks` row named `embed-page:<page id>`, refreshed while held, expiring within 2 minutes after a holder dies) from reading which chunks lack a vector through installing them; a path that reaches a page another path is embedding waits for it, then embeds only the chunks still missing a vector. The wait ends at the caller\'s deadline or after 2 minutes: a stale drain then skips the page (its chunks stay stale for the next run, not counted as a failure) and an embedding effect retries with `lock_busy`. A holder renews the lease inside its install transaction and installs nothing (`lock_busy`) when the lease expired and another path took it; every release deletes the expired `embed-page:` rows a crashed holder left, so doctor `stale_locks` stops listing them after the next embed. Before, a stale drain that ran while a write\'s embedding effect was in flight sent the same chunks twice (paid twice on a paid provider). Live `embed-page:` rows can show in the `gbrain status` lock list while an embed runs.' },
+ { since: 'TBD', text: 'A page\'s new chunks now go to the embedding provider once per content version. The post-write embedding effect, `gbrain embed --stale`, the embed-backfill job and phase-end embeds each hold a per-page lease (a `gbrain_cycle_locks` row named `embed-page:<page id>`, refreshed while held, expiring within 2 minutes after a holder dies) from reading which chunks lack a vector through installing them; a path that reaches a page another path is embedding waits for it, then embeds only the chunks still missing a vector. The wait ends at the caller\'s deadline or after 2 minutes: a stale drain then skips the page (its chunks stay stale for the next run, not counted as a failure) and an embedding effect retries with `lock_busy`. A holder renews the lease inside its install transaction and installs nothing (`lock_busy`) when the lease expired and another path took it; every release deletes the expired `embed-page:` rows a crashed holder left, so doctor `stale_locks` stops listing them after the next embed. Managed-persistence activation, deactivation and shared-skill activation no longer count `embed-page:` rows, live or expired, as legacy locks or blockers. Before, a stale drain that ran while a write\'s embedding effect was in flight sent the same chunks twice (paid twice on a paid provider). Live `embed-page:` rows can show in the `gbrain status` lock list while an embed runs.' },
// PR 4 recall (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
{ since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },
// PR 4 4e (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
diff --git a/src/core/page-embedding-lease.ts b/src/core/page-embedding-lease.ts
index 18504645a9..63c1c24f77 100644
--- a/src/core/page-embedding-lease.ts
+++ b/src/core/page-embedding-lease.ts
@@ -39,6 +39,14 @@ export const pageEmbeddingLeaseProbe: { contended?: (pageId: number) => void; wa
/** Every page embedding lease id starts with this; the writer admin fingerprint leaves these rows out (admin-intent.ts). */
export const PAGE_EMBEDDING_LEASE_PREFIX = 'embed-page:';
+/**
+ * SQL predicate on `gbrain_cycle_locks.id` that leaves page embedding leases out. Activation's legacy-lock inspection,
+ * deactivation's lease blockers and shared-skill activation's quiescence check use it: a lease only dedupes provider
+ * calls and guards vector installs, which ran unleased before it existed; its holders run inside a lock, job lease or
+ * effect claim those checks already see, and an expired row (a crashed holder's) must not block them.
+ */
+export const NOT_PAGE_EMBEDDING_LEASE = `id NOT LIKE '${PAGE_EMBEDDING_LEASE_PREFIX}%'`;
+
export function pageEmbeddingLeaseId(pageId: number): string {
return `${PAGE_EMBEDDING_LEASE_PREFIX}${pageId}`;
}
@@ -107,7 +115,7 @@ export async function acquirePageEmbeddingLease(engine: BrainEngine, pageId: num
[Symbol.asyncDispose]: async () => {
clearInterval(refresh);
await engine.executeRaw(`DELETE FROM gbrain_cycle_locks
- WHERE (id = $1 AND acquisition_token = $2::uuid) OR (id LIKE 'embed-page:%' AND ttl_expires_at < now())`, [id, token])
+ WHERE (id = $1 AND acquisition_token = $2::uuid) OR (id LIKE '${PAGE_EMBEDDING_LEASE_PREFIX}%' AND ttl_expires_at < now())`, [id, token])
.catch(() => { /* the TTL is the backstop */ });
},
};
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 2e724fca1f..45db7499d4 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -26,6 +26,7 @@
*/
import { randomUUID } from 'node:crypto';
import { DATABASE_ONLY_SOURCES_KEY } from './unbound-source.ts';
+import { NOT_PAGE_EMBEDDING_LEASE } from '../page-embedding-lease.ts';
import { existsSync, lstatSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
@@ -143,7 +144,7 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
: carry.state_file ? `move ${carry.state_file} aside, then rerun deactivate; or ${resolve}` : resolve });
}
const leases = await engine.executeRaw<{ id: string; holder_host: string; holder_pid: number }>(
- 'SELECT id, holder_host, holder_pid FROM gbrain_cycle_locks WHERE ttl_expires_at > now() ORDER BY id');
+ `SELECT id, holder_host, holder_pid FROM gbrain_cycle_locks WHERE ttl_expires_at > now() AND ${NOT_PAGE_EMBEDDING_LEASE} ORDER BY id`);
for (const l of leases) blockers.push({ kind: 'lease', id: l.id, detail: `held by host ${l.holder_host}, pid ${l.holder_pid}`,
exit: 'wait for that connector sync or maintenance run to finish (gbrain doctor shows live locks), then rerun deactivate' });
return blockers;
diff --git a/src/core/persistence/legacy-locks.ts b/src/core/persistence/legacy-locks.ts
index a3f1652c3e..9ba88ceccb 100644
--- a/src/core/persistence/legacy-locks.ts
+++ b/src/core/persistence/legacy-locks.ts
@@ -1,11 +1,12 @@
import { classifyHolderLiveness } from '../db-lock.ts';
+import { NOT_PAGE_EMBEDDING_LEASE } from '../page-embedding-lease.ts';
import type { SqlEngine } from './model.ts';
import { isWriteRequestId } from './types.ts';
export async function inspectLegacyWriterLocks(engine: SqlEngine) {
const rows = await engine.executeRaw<{ id: string; holder_pid: number; holder_host: string; acquisition_token: string; age_ms: number }>(
`SELECT id,holder_pid,holder_host,acquisition_token,EXTRACT(EPOCH FROM (now()-acquired_at))::double precision*1000 AS age_ms
- FROM gbrain_cycle_locks ORDER BY id`);
+ FROM gbrain_cycle_locks WHERE ${NOT_PAGE_EMBEDDING_LEASE} ORDER BY id`);
return rows.map(row => ({ id: row.id, holder_pid: row.holder_pid, holder_host: row.holder_host, acquisition_token: row.acquisition_token,
liveness: Number.isSafeInteger(row.holder_pid) && row.holder_pid > 0 && isWriteRequestId(row.acquisition_token)
? classifyHolderLiveness(row.holder_pid, row.holder_host, row.age_ms) : 'unknown' as const }));
diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.ts
index 086c7fa314..7c4dc0a84b 100644
--- a/src/core/persistence/skill-activation.ts
+++ b/src/core/persistence/skill-activation.ts
@@ -9,6 +9,7 @@ import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from '.
import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
import { notQuiescedError } from './blocking-effects.ts';
+import { NOT_PAGE_EMBEDDING_LEASE } from '../page-embedding-lease.ts';
export async function activateSharedSkillPersistence(engine: BrainEngine,
options: { confirmQuiesced?: boolean; dryRun?: boolean; expectedState?: string } = {}): Promise<{ activated: boolean; protocol_version: 2; filesystem_sources: number; drift_audit?: ActivationReport['drift_audit'] }> {
@@ -58,7 +59,7 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,
const identity = (rows: WorktreeBinding[]) => JSON.stringify(rows.map(row => [row.source_id, row.source_incarnation, row.worktree_id,
row.owner_host_id, String(row.owner_epoch), String(row.topology_generation), row.relative_path, row.local_path, row.coordination_path]));
if (identity(current) !== identity(initial)
- || (await tx.executeRaw('SELECT id FROM gbrain_cycle_locks LIMIT 1')).length) throw quiescence();
+ || (await tx.executeRaw(`SELECT id FROM gbrain_cycle_locks WHERE ${NOT_PAGE_EMBEDDING_LEASE} LIMIT 1`)).length) throw quiescence();
if ((await tx.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length
|| (await tx.executeRaw("SELECT id FROM persistence_effects WHERE state IN ('queued','running') OR recovery IS NOT NULL LIMIT 1")).length) {
throw await notQuiescedError(tx, quiescence().message, { queuedEffects: true });
diff --git a/test/page-embedding-lease.serial.test.ts b/test/page-embedding-lease.serial.test.ts
index 5beb8206e4..5493cc7d52 100644
--- a/test/page-embedding-lease.serial.test.ts
+++ b/test/page-embedding-lease.serial.test.ts
@@ -4,7 +4,8 @@
* 1. Protects: a path that finds a page's lease held gives up at its deadline (or after one TTL) with a busy lease
* instead of waiting forever; a holder whose lease was taken over during its provider call installs nothing;
* `embedStalePages` reads the page under the lease; a release deletes the expired `embed-page:` rows a dead
- * holder left (doctor `stale_locks` clears); and a holder that throws releases its lease.
+ * holder left (doctor `stale_locks` clears); a holder that throws releases its lease; and activation's legacy-lock
+ * inspection and deactivation's lease blockers leave page embedding leases out, live or expired.
* 2. Fails when: the wait loop has no bound, the install skips the lease renewal, the drain reads its snapshot before
* the lease, expired lease rows stay, or an error path skips the release. Each test holds the lease itself or
* steals it inside the provider call, so every contention is forced, never timed.
@@ -29,7 +30,9 @@ import { embedStaleForSource, embedStalePages } from '../src/core/embed-stale.ts
import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
-import { listStaleLocks } from '../src/core/db-lock.ts';
+import { listStaleLocks, tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { inspectLegacyWriterLocks } from '../src/core/persistence/legacy-locks.ts';
+import { deactivationBlockers } from '../src/core/persistence/deactivation.ts';
import { checkStaleLocks } from '../src/commands/doctor/checks/routing-federation.ts';
const CHUNKS = ['Alpha example chunk about the acme-example ledger.', 'Beta example chunk about the quarterly report.', 'Gamma example chunk about the roadmap.'];
@@ -67,7 +70,9 @@ for (const kind of testBackends()) {
dims = (await resolveActiveEmbeddingColumnFromEngine(brain.engine)).dimensions;
home = mkdtempSync(join(tmpdir(), 'gbrain-embed-lease-'));
}, 600_000);
- afterEach(() => {
+ afterEach(async () => {
+ // A stolen lease row carries a token no holder releases; it would outlive its test until the TTL.
+ await brain.engine.executeRaw("DELETE FROM gbrain_cycle_locks WHERE id LIKE 'embed-page:%'");
sent.length = 0;
pageEmbeddingLeaseProbe.contended = undefined;
pageEmbeddingLeaseProbe.waitBoundMs = undefined;
@@ -168,6 +173,24 @@ for (const kind of testBackends()) {
expect((await checkStaleLocks(brain.engine)).status).toBe('ok');
}, 30_000);
+ test('activation legacy locks and deactivation lease blockers leave page embedding leases out, live or expired; a writer lock still shows', async () => {
+ const { pageId } = await pending();
+ const expired = 'embed-page:987654322';
+ await brain.engine.executeRaw(`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)
+ VALUES ($1, 999999, 'host-a', now() - interval '2 hours', now() - interval '1 hour', now() - interval '1 hour', $2::uuid)`, [expired, randomUUID()]);
+ const writer = (await tryAcquireDbLock(brain.engine, `gbrain-sync:lease-test-${randomUUID()}`))!;
+ try {
+ await using _live = await acquirePageEmbeddingLease(brain.engine, pageId);
+ expect((await brain.engine.executeRaw<{ id: string }>("SELECT id FROM gbrain_cycle_locks WHERE id LIKE 'embed-page:%' ORDER BY id")).map(r => r.id))
+ .toEqual([pageEmbeddingLeaseId(pageId), expired].sort());
+ expect((await inspectLegacyWriterLocks(brain.engine)).map(l => l.id)).toEqual([writer.id]);
+ expect((await deactivationBlockers(brain.engine)).filter(b => b.kind === 'lease').map(b => b.id)).toEqual([writer.id]);
+ } finally {
+ await writer.release();
+ await brain.engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [expired]);
+ }
+ }, 30_000);
+
test('a holder that throws releases its lease: the drain, the effect and a bare holder', async () => {
const failing = async (): Promise<Float32Array[]> => { throw new Error('provider refused'); };
const drainPage = await pending();