Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(status): per-source applied-through watermark on write receipts, sources status and sync results (#7190)

garrytan5d3f0c6c46b2
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 95057afd0d..6fc1f8e78f 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -47,5 +47,8 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.
- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error.
- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.
+- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and write receipts; `gbrain pages status` (#7181) can compose it with its Git view.
+- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (receipts): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).
+- `src/core/persistence/write-applied.ts` — #7190 `readWriteApplied` / `withWriteApplied`: the `applied` block on page-write, `remember` and `get_write_request` receipts (`searchable_yet`, state, gap, sequence, write watermark). A failed read omits the block and never fails the write.
- `src/core/persistence/landing-gaps.ts` — GBRA-150 `readLandingGaps`: committed managed_sync receipts of the last 24 h (at most 2,000, newest first through the watermark index, 2 s statement probe; a timeout reads `unknown`, never ok) whose page is still missing, has chunks waiting for vectors, has no chunks, or is quarantined past `sync.freshness_target_seconds`; one row per page with reason and fix. Consumers: `sync status --detail` `landing` / `landing_read` (`sync-status.ts`) and doctor `sync_landing_gaps`. Tests: `test/sync-landing-gaps.test.ts`.
- `src/commands/doctor/checks/landing-gaps.ts` — GBRA-150 doctor `sync_landing_gaps` (registered after `partial_embedding`, one of `CHEAP_INCIDENT_CHECKS`): warns per source with the gap count by reason and the first fix from `readLandingGaps`; `unknown` read stays a warning, never ok. Tests: `test/doctor-sync-landing-gaps.test.ts`.
diff --git a/docs/guides/resolve-paths.md b/docs/guides/resolve-paths.md
index f853578649..a903eda952 100644
--- a/docs/guides/resolve-paths.md
+++ b/docs/guides/resolve-paths.md
@@ -64,3 +64,31 @@ committed sync receipts of the last 24 h and says `unknown`, never `ok`, when it
`gbrain sync status` reads `blocked` only when the source cannot advance without a person or an operator, the same meaning as a
sync run's drain outcome and a sync job's `blocked` progress. A file hold that waits on a person while the rest of the source
keeps syncing reads `synced` with reason `held_needs_human`; `needs_human` and `next` still carry that decision.
+
+## Is my write searchable yet?
+
+Every page write receipt (`put_page`, `capture`, `remember`, `edit_page` and the other page writes, and `get_write_request`) carries `applied`, read when the reply is built:
+
+| Field | Meaning |
+|---|---|
+| `searchable_yet` | `true` only when search finds the page by keyword and by vector |
+| `searchable`, `state` | the vocabulary above: `searchable`, `pending_embedding`, `chunkless`, `keyword_only`, `quarantined`, `empty`, plus `pending_write` (the request has not settled), `not_written` (it settled without committing) and `deleted` |
+| `page` | `{ slug, chunks, unembedded }`; `unembedded` counts visible chunks with no vector in the active embedding column |
+| `embedding_hold` | a large page's held or capped embedding budget, which waits for approval |
+| `gap` | `requests_ahead` (unsettled requests of the source queued before this one) and `unembedded_chunks` |
+| `sequence` | the request's journal sequence; the write has settled once it is at or below `watermark.committed_through_request` |
+| `watermark` | `indexed_through`, `committed_through_request` and `requests_pending` of the source (indexed reads only) |
+
+A receipt whose watermark read fails leaves `applied` out; the write itself is unaffected.
+
+## The source watermark
+
+`gbrain sources status --json` (each source's `watermark`), MCP `sources_status` and `gbrain sync --json` (each synced source) carry the full watermark:
+
+- `indexed_through`: `{ commit, synced_at }`. The commit is the source's last synced commit, which only a finished sync pass moves. A pass stopped by its deadline, an abort or a page budget leaves it where it was. Files held at that commit are counted in `pending.held_files`.
+- `embedded_through`: `complete` (with `commit`) when every live page that is not `embed_skip` has a vector for each visible chunk; `partial` with `unembedded_pages`, `held_pages` (held and capped large pages count as not embedded) and `before`, the oldest `updated_at` among the pages still waiting, so every page written before it is embedded; or `embeddings_off`.
+- `committed_through_request`: a request sequence at or below which every request of the source has settled (committed, conflict, failed or cancelled): one below the oldest queued, running or recovering request, else the journal's newest sequence.
+- `pending`: `requests` (unsettled, with the oldest age), `commits_behind` and `files_behind` (on this host's checkout after the last synced commit), `held_files` and `deletes_withheld` (deletes a mass-delete cap withheld). `count` adds requests, files behind, held files and withheld deletes; `oldest_age_seconds` is the older of the oldest request and the oldest commit behind.
+- `writer_heartbeat`: the process holding the source's drain lease (`holder`: kind, id, host, PID), `heartbeat_age_seconds`, `last_progress_at` (its last committed sync write, cursor save or pass-row write), `progress_age_seconds` and `stalled` (no progress for 5 minutes). A remote caller sees the holder's kind and the times, never its host, PID or job id.
+
+A landing check that only needs "has this commit landed?" compares `indexed_through.commit` with its commit and reads `pending` for the rest.
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 6ba65150b6..3c0a6ac795 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1251,7 +1251,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
// #6317 (B4): whether managed sync data moves, beside sync_running (a live lock is not progress); the writer-status command rides along.
const movementView = await import('../core/persistence/sync-movement.ts');
const movement = new Map((await movementView.readSourceMovement(engine, { sourceIds: sources.map(source => source.id) }).catch(() => [])).map(m => [m.source_id, m]));
- const upstreamView = await import('../core/sync-upstream-rewrite.ts'), upstream = new Map((await upstreamView.readUpstreamDivergences(engine, sources.map(source => source.id))).map(u => [u.source_id, upstreamView.renderUpstreamDivergence(u)]));
+ const upstreamView = await import('../core/sync-upstream-rewrite.ts'), upstream = new Map((await upstreamView.readUpstreamDivergences(engine, sources.map(source => source.id))).map(u => [u.source_id, upstreamView.renderUpstreamDivergence(u)])); const watermarkView = await import('../core/persistence/applied-watermark.ts'), watermarks = new Map(await Promise.all(sources.map(async source => [source.id, await watermarkView.readAppliedWatermark(engine, source.id).catch(() => null)] as const)));
if (json) {
const enriched = metrics.map((m) => ({
...m,
@@ -1264,7 +1264,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
movement_state: movement.get(m.source_id)!.movement_state, movement: movement.get(m.source_id) } : {}),
...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}), ...(upstream.get(m.source_id) ? { upstream: upstream.get(m.source_id) } : {}),
...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),
- ...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}),
+ ...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}), ...(watermarks.get(m.source_id) ? { watermark: watermarks.get(m.source_id) } : {}),
}));
console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));
return;
@@ -1305,7 +1305,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
for (const [sourceId, status] of connectors) for (const line of statusView.connectorStatusLines(sourceId, status)) console.log(line);
for (const [sourceId, status] of gitHolds) for (const line of statusView.gitHoldStatusLines(sourceId, status)) console.log(line);
for (const b of backlog.values()) console.log(` ${drainMod.formatManagedSyncBacklog(b)}`);
- for (const m of movement.values()) { const line = movementView.formatSourceMovement(m); if (line) console.log(` ${line}`); }
+ for (const m of movement.values()) { const line = movementView.formatSourceMovement(m); if (line) console.log(` ${line}`); } for (const w of watermarks.values()) if (w) console.log(` ${watermarkView.formatAppliedWatermark(w)}`);
for (const [sourceId, notices] of uncommitted) for (const line of uncommittedView.uncommittedFenceRepairLines(sourceId, notices)) console.log(line);
for (const view of sharedSkills.values()) if (view && (only || view.configured === false || view.parked)) for (const line of sharedSkillsView.sharedSkillsStatusLines(view)) console.log(` ${line}`);
for (const m of metrics) {
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 4ff6f4d3d4..89efe1acba 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -609,7 +609,13 @@ async function runSyncAll(
const okCount = perSourceResults.filter((r) => r.status === 'ok').length;
const errCount = perSourceResults.filter((r) => r.status === 'error').length;
- if (jsonOut) emitSyncAllEnvelope({ perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate: embedPlan.costGate, resumeCommand });
+ if (jsonOut) {
+ // #7190: each synced source's applied-through watermark, read after the run.
+ const { readAppliedWatermark } = await import('../../core/persistence/applied-watermark.ts');
+ const watermarks = new Map(await Promise.all(perSourceResults.filter(r => r.status !== 'skipped_missing_path')
+ .map(async r => [r.sourceId, await readAppliedWatermark(engine, r.sourceId).catch(() => null)] as const)));
+ emitSyncAllEnvelope({ perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate: embedPlan.costGate, resumeCommand, watermarks });
+ }
// v0.42.7 (#1696): brain-wide extraction-lag nudge after the --all wave.
// Best-effort, stderr-only; skipped on dry-run.
@@ -732,8 +738,9 @@ function emitSyncAllEnvelope(input: {
errCount: number;
costGate: Record<string, unknown> | undefined;
resumeCommand: string;
+ watermarks: Map<string, unknown>;
}): void {
- const { perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate, resumeCommand } = input;
+ const { perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate, resumeCommand, watermarks } = input;
// Sort by source_id at emit time so the envelope is deterministic
// even though completion order is not (pMapAllSettled semantics).
const sortedSources = perSourceResults
@@ -769,6 +776,7 @@ function emitSyncAllEnvelope(input: {
...(embedBackfillBySource.has(r.sourceId)
? { embed_backfill: embedBackfillBySource.get(r.sourceId) }
: {}),
+ ...(watermarks.get(r.sourceId) ? { watermark: watermarks.get(r.sourceId) } : {}),
}));
emitJson(JSON.stringify({
schema_version: 1,
@@ -979,7 +987,8 @@ async function runSingleSourceSync(
const capacity = await syncCapacityNotices(engine, jsonOut, result);
const convergence = jsonOut && result.status === 'dry_run' && !companyPolicy ? await readConvergence() : undefined;
if (jsonOut) {
- emitJson(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate), ...(convergence ? { convergence } : {}),
+ const watermark = await (await import('../../core/persistence/applied-watermark.ts')).readAppliedWatermark(engine, sourceId).catch(() => null);
+ emitJson(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate), ...(convergence ? { convergence } : {}), ...(watermark ? { watermark } : {}),
...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId),
...(result.tail ? { tail: syncTailJsonFields(result).tail } : {}), ...capacity }));
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 57142f020b..d3fc492b39 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1049,6 +1049,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', id: 'sync_status_coherent_7189', text: '`gbrain sync status --json` no longer contradicts itself while a source falls behind (#7189). `freshness` adds `behind` (commits on the checkout HEAD after the last synced commit, and the oldest one\'s age), because its latency samples date only commits that already synced. The `notifier` block adds `drain_holder`: with no notifier running, the process holding the source\'s drain lease is named and no fix is offered while it makes progress, instead of "No resident … watches this source". A `last_error` the source\'s sync has committed a page past now carries `superseded: { at }` and no longer sets `needs_human`, `state` or `next`. New `needs_human_from` says whether `needs_human` comes from a hold or the last error. In `gbrain sources resolve-path`, a large page whose embedding budget is held or capped reads `pending_embedding` with `embedding_hold`, never `keyword_only`, which means `embed_skip`.' },
// GBRA-150 (nested typed metafiles become pages): Garry, "take all recommendations" (2026-10-20), answering the proposal to import typed non-root index.md/README.md. `since` is stamped at the merge slot.
{ since: 'TBD', text: 'Sync now imports a folder-scaffolding file below a source\'s root (`index.md`, `README.md`, `log.md`, `schema.md` or `RESOLVER.md`) as a page when its frontmatter has `type:` or `title:`, for example `projects/acme-example/index.md`. A bare one at any depth and every one at the source root stay skipped. The first sync after the upgrade imports the existing typed files once and deletes or rewrites nothing else; deleting such a file later soft-deletes its page. `gbrain config set sync.metafile_pages off` restores the old skip. Default change approved by Garry, "take all recommendations", 2026-10-20.' },
+ // #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.
+ { since: 'TBD', id: 'applied_watermark_7190', text: 'Page write receipts (`put_page`, `capture`, `remember`, `edit_page` and the other page writes) and `get_write_request` now carry `applied`: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`) and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`). Each reply costs a few indexed reads more. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.ts
index ee6154afd4..5656a1aa1b 100644
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@ -127,6 +127,7 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: W
...publicWriteReceipt(receiptFor(row, facts)),
operation: row.operation, source_id: row.source_id, slug: row.slug,
...await liveSearchable(ctx, { request_id: row.request_id, state: row.state, source_id: row.source_id, slug: row.slug, searchable: row.outcome?.searchable }),
+ ...await (await import('../persistence/write-applied.ts')).readWriteApplied(ctx.engine, row).then(applied => ({ applied }), () => ({})),
...(mismatch ? { owner_build: mismatch } : {}),
// #7112: the owner-side detail (an owner exception's class, errno, frame, redacted database error text and statement) for a trusted local reader only.
...(ctx.remote === false && row.error_detail ? { error_detail: row.error_detail } : {}),
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index aff9fa7053..a10e5af13d 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -300,7 +300,9 @@ const sources_status: Operation = {
const status = await getSourceStatus(ctx.engine, p.id as string);
const { readCompanyBrainSourceStatus } = await import('../company-brain/status.ts');
const ingestion = await readCompanyBrainSourceStatus(ctx.engine, p.id as string);
- return ingestion ? { ...status, ingestion } : status;
+ const { readAppliedWatermark } = await import('../persistence/applied-watermark.ts');
+ const watermark = await readAppliedWatermark(ctx.engine, p.id as string, { remote: ctx.remote !== false }).catch(() => null);
+ return { ...status, ...(ingestion ? { ingestion } : {}), ...(watermark ? { watermark } : {}) };
},
cliHints: { name: 'sources_status', hidden: true },
};
diff --git a/src/core/page-searchability.ts b/src/core/page-searchability.ts
new file mode 100644
index 0000000000..b7c2413bbe
--- /dev/null
+++ b/src/core/page-searchability.ts
@@ -0,0 +1,75 @@
+/**
+ * Whether search can find each live page of a source now, in the vocabulary `gbrain sources resolve-path` and
+ * `gbrain pages status` share: a page state, `searchable: true | 'keyword' | false`, its visible chunks, `unembedded`
+ * (visible chunks with no vector in the active embedding column), and `embedding_hold` (a large page whose embedding
+ * budget is held or capped: it reads `pending_embedding`, never `keyword_only`, which means `embed_skip`).
+ * Readers: resolve-path and write receipts (#7190). Indexed reads only.
+ */
+import type { BrainEngine } from './engine.ts';
+import { DELETED_PAGE_PURGE_WINDOW_HOURS, type EmbeddingState } from './embedding-state.ts';
+import { budgetRowAppliesFilter } from './page-size-policy.ts';
+import { chunkGenerationFilter } from './search/safe-chunks.ts';
+import { quoteIdentifier } from './search/embedding-column.ts';
+import { embeddingWriteTarget } from './page-state/projections.ts';
+
+export type PageSearchState = 'searchable' | 'pending_embedding' | 'chunkless' | 'keyword_only' | 'quarantined' | 'empty';
+
+export interface PageSearchability {
+ /** The page's worst embedding state, or null when it has no chunk rows at all. */
+ embedding_state: EmbeddingState | null;
+ state: PageSearchState;
+ searchable: true | 'keyword' | false;
+ chunks: number;
+ unembedded: number;
+ embedding_hold: { state: 'held' | 'capped'; reason: string; updated_at: string } | null;
+}
+
+export const PAGE_SEARCHABLE: Record<EmbeddingState, true | 'keyword' | false> = { embedded: true, pending: 'keyword', keyword_only: 'keyword', quarantined: false, empty: false,
+ deleted_page_chunks: false, chunkless_healable: false };
+const PAGE_STATE: Record<Exclude<EmbeddingState, 'deleted_page_chunks'>, PageSearchState> = { embedded: 'searchable', pending: 'pending_embedding',
+ keyword_only: 'keyword_only', quarantined: 'quarantined', empty: 'empty', chunkless_healable: 'chunkless' };
+/** Worst first: a page with some chunks embedded and some pending reads as pending. */
+export const PAGE_STATE_ORDER: EmbeddingState[] = ['quarantined', 'chunkless_healable', 'pending', 'keyword_only', 'empty', 'embedded'];
+
+/** The searchability of each live page of `sourceId` named in `slugs` (a slug with no live page is absent). */
+export async function readPageSearchability(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<Map<string, PageSearchability>> {
+ const out = new Map<string, PageSearchability>();
+ if (!slugs.length) return out;
+ const live = (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND slug = ANY($2::text[])', [sourceId, slugs])).map(row => row.slug);
+ if (!live.length) return out;
+ const rows = await engine.listEmbeddingStateRows({ sourceIds: [sourceId], slugs: live, states: PAGE_STATE_ORDER, limit: live.length * PAGE_STATE_ORDER.length,
+ purgeWindowHours: DELETED_PAGE_PURGE_WINDOW_HOURS });
+ const column = `cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)}`;
+ const unembedded = new Map((await engine.executeRaw<{ slug: string; unembedded: number | string }>(
+ `SELECT p.slug, count(cc.id) AS unembedded FROM pages p JOIN content_chunks cc ON cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')} AND ${column} IS NULL
+ WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND p.deleted_at IS NULL GROUP BY p.slug`, [sourceId, live])).map(row => [row.slug, Number(row.unembedded)]));
+ const folded = new Map<string, { state: EmbeddingState; chunks: number }>();
+ for (const row of rows) {
+ const prior = folded.get(row.slug);
+ const state = prior && PAGE_STATE_ORDER.indexOf(prior.state) < PAGE_STATE_ORDER.indexOf(row.state) ? prior.state : row.state;
+ folded.set(row.slug, { state, chunks: (prior?.chunks ?? 0) + Number(row.chunks) });
+ }
+ const keywordOnly = [...folded].filter(([, emb]) => emb.state === 'keyword_only').map(([slug]) => slug);
+ const holds = new Map<string, NonNullable<PageSearchability['embedding_hold']>>();
+ if (keywordOnly.length) {
+ for (const row of await engine.executeRaw<{ slug: string; state: 'held' | 'capped'; reason: string; updated_at: Date | string }>(
+ `SELECT p.slug, b.state, COALESCE(b.reason, 'awaiting_approval') AS reason, b.updated_at
+ FROM pages p JOIN page_embedding_budget b ON b.page_id = p.id
+ WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND p.deleted_at IS NULL AND ${budgetRowAppliesFilter('b', 'p')}
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`, [sourceId, keywordOnly])) {
+ holds.set(row.slug, { state: row.state, reason: row.reason, updated_at: new Date(row.updated_at).toISOString() });
+ }
+ }
+ for (const slug of live) {
+ const emb = folded.get(slug), hold = holds.get(slug) ?? null;
+ out.set(slug, {
+ embedding_state: emb?.state ?? null,
+ state: hold ? 'pending_embedding' : emb ? PAGE_STATE[emb.state as Exclude<EmbeddingState, 'deleted_page_chunks'>] ?? 'searchable' : 'chunkless',
+ searchable: emb ? PAGE_SEARCHABLE[emb.state] : false,
+ chunks: emb?.chunks ?? 0,
+ unembedded: unembedded.get(slug) ?? 0,
+ embedding_hold: hold,
+ });
+ }
+ return out;
+}
diff --git a/src/core/persistence/applied-watermark.ts b/src/core/persistence/applied-watermark.ts
new file mode 100644
index 0000000000..de3b9c8d6a
--- /dev/null
+++ b/src/core/persistence/applied-watermark.ts
@@ -0,0 +1,176 @@
+/**
+ * #7190: how far each source's writes have been applied, in one read, so an agent can tell whether a write
+ * is searchable yet without running git, SQL or a landing loop.
+ *
+ * - indexed_through.commit: `sources.last_commit`. Only a sync pass that finishes moves it: the checkpoint
+ * publication that writes it is reached only through the pass's stamp, so a deadline-stopped, aborted,
+ * selection-scoped or partial pass never advances it. Files held at that commit are counted in
+ * `pending.held_files`, and deletes a mass-delete cap withheld in `pending.deletes_withheld`.
+ * - embedded_through: `complete` when every live page of the source that is not `embed_skip` has a vector for each
+ * visible chunk in the active embedding column. Held and capped large pages count as not embedded. Otherwise
+ * `before` is the oldest `updated_at` among the pages still waiting: every page written before it is embedded.
+ * - committed_through_request: a `persistence_requests.sequence` at or below which every request of the source's
+ * current incarnation has settled (committed, conflict, failed or cancelled): one below the oldest queued, running
+ * or recovering request, else the journal's newest sequence. A receipt whose `sequence` is at or below it has settled.
+ * - pending: unsettled requests (count and oldest age), commits and changed files on this host's checkout after
+ * the last synced commit, held files and withheld deletes. `count` is requests + files behind + held files +
+ * withheld deletes.
+ * - writer_heartbeat: the source's drain-lease holder and its last progress (a committed sync write, a cursor
+ * save or a pass-row write); `stalled` after HOLDER_STALL_MS without progress. A remote caller sees the holder's
+ * kind and times, never its host, pid or job id.
+ *
+ * `readWriteWatermark` is the cheap subset a write receipt carries (indexed reads only, no git, no lease read).
+ * Read-only; nothing is scheduled or written.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { embeddingsDisabled } from '../embedding-disabled.ts';
+import { chunkGenerationFilter } from '../search/safe-chunks.ts';
+import { quoteIdentifier } from '../search/embedding-column.ts';
+import { embeddingWriteTarget } from '../page-state/projections.ts';
+import { budgetRowAppliesFilter } from '../page-size-policy.ts';
+import { execFileBounded } from '../bounded-child-exec.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { readGitBehind, type BehindReader } from './sync-freshness.ts';
+import { countGitHolds } from './sync-holds.ts';
+import { holderStalled, publicDrainHolder, readDrainHolder } from './sync-lease.ts';
+
+export interface WriteWatermark {
+ source_id: string;
+ indexed_through: { commit: string | null; synced_at: string | null };
+ committed_through_request: number | null;
+ requests_pending: { count: number; oldest_age_seconds: number | null };
+}
+
+export interface AppliedWatermark extends Omit<WriteWatermark, 'requests_pending'> {
+ read_at: string;
+ embedded_through: { state: 'complete' | 'partial' | 'embeddings_off'; commit: string | null; before: string | null; unembedded_pages: number; held_pages: number };
+ pending: {
+ count: number;
+ oldest_age_seconds: number | null;
+ requests: { count: number; oldest_age_seconds: number | null };
+ commits_behind: { count: number; oldest_age_seconds: number | null } | null;
+ files_behind: number | null;
+ held_files: number;
+ deletes_withheld: number;
+ };
+ writer_heartbeat: {
+ holder: { kind: string; id: string | null; host: string | null; pid: number | null } | null;
+ heartbeat_age_seconds: number | null;
+ last_progress_at: string | null;
+ progress_age_seconds: number | null;
+ stalled: boolean;
+ };
+}
+
+/** Changed paths between `from` and HEAD of the checkout at `root`, or null when git cannot say. */
+export type FilesBehindReader = (root: string, from: string) => Promise<number | null>;
+
+const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
+const ageSeconds = (at: unknown, now: number): number | null => {
+ if (at === null || at === undefined) return null;
+ const ms = at instanceof Date ? at.getTime() : Date.parse(String(at));
+ return Number.isFinite(ms) ? Math.max(0, Math.round((now - ms) / 1000)) : null;
+};
+const iso = (at: unknown): string | null => {
+ if (at === null || at === undefined) return null;
+ const ms = at instanceof Date ? at.getTime() : Date.parse(String(at));
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
+};
+
+export const readGitFilesBehind: FilesBehindReader = async (root, from) => {
+ if (!SHA.test(from)) return null;
+ const diff = await execFileBounded('git', ['-C', root, 'diff', '--name-only', '-z', `${from}..HEAD`], { timeout: 10_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
+ return diff.error ? null : diff.stdout.split('\0').filter(Boolean).length;
+};
+
+/** The cheap watermark every write receipt carries: the source row, and two reads on the request journal's indexes. */
+export async function readWriteWatermark(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, now = Date.now()): Promise<WriteWatermark> {
+ const [row] = await engine.executeRaw<{ last_commit: string | null; last_sync_at: unknown; pending_min: number | string | null;
+ pending_count: number | string; pending_since: unknown }>(`SELECT s.last_commit, s.last_sync_at, p.pending_min, p.pending_count, p.pending_since
+ FROM sources s LEFT JOIN LATERAL (SELECT min(r.sequence) AS pending_min, count(*) AS pending_count, min(r.created_at) AS pending_since FROM persistence_requests r
+ WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.state IN ('queued','running','recovering')) p ON true WHERE s.id=$1`, [sourceId]);
+ const [newest] = row?.pending_min == null ? await engine.executeRaw<{ sequence: number | string | null }>('SELECT max(sequence) AS sequence FROM persistence_requests') : [];
+ const through = row?.pending_min != null ? Number(row.pending_min) - 1 : newest?.sequence == null ? null : Number(newest.sequence);
+ return {
+ source_id: sourceId,
+ indexed_through: { commit: row?.last_commit ?? null, synced_at: iso(row?.last_sync_at) },
+ committed_through_request: through,
+ requests_pending: { count: Number(row?.pending_count ?? 0), oldest_age_seconds: ageSeconds(row?.pending_since, now) },
+ };
+}
+
+/** The full watermark of one source for `gbrain sources status --json` and MCP `sources_status`. */
+export async function readAppliedWatermark(engine: BrainEngine, sourceId: string,
+ opts: { remote?: boolean; now?: number; behind?: BehindReader; filesBehind?: FilesBehindReader } = {}): Promise<AppliedWatermark> {
+ const now = opts.now ?? Date.now();
+ const write = await readWriteWatermark(engine, sourceId, now);
+ const [source] = await engine.executeRaw<{ incarnation: string | null; root: string | null }>(`SELECT s.incarnation::text AS incarnation,
+ COALESCE((SELECT h.local_path FROM persistence_host_bindings h JOIN persistence_source_bindings b ON b.worktree_id=h.worktree_id
+ WHERE b.source_id=s.id AND h.host_id::text=$2 LIMIT 1), s.local_path) AS root FROM sources s WHERE s.id=$1`,
+ [sourceId, (await import('./identity.ts')).existingLocalHostId()]);
+ const commit = write.indexed_through.commit;
+ const root = !opts.remote && source?.root && commit ? source.root : null;
+ const lag = root ? await (opts.behind ?? readGitBehind)(root, commit!).catch(() => null) : null;
+ const filesBehind = root && lag?.commits ? await (opts.filesBehind ?? readGitFilesBehind)(root, commit!).catch(() => null) : lag ? 0 : null;
+ const heldFiles = source?.incarnation ? await countGitHolds(engine, sourceId, source.incarnation).catch(() => 0) : 0;
+ const { readPassReadings } = await import('./sync-pass-readers.ts');
+ const [pass] = await readPassReadings(engine, { sourceIds: [sourceId], head: false }).catch(() => []);
+ const deletesWithheld = pass?.row.value.obligations.deletes_withheld ? Number(pass.row.value.telemetry.classes?.deletes_withheld?.count ?? 0) : 0;
+ const commitsBehind = lag ? { count: lag.commits, oldest_age_seconds: lag.oldest === null ? null : Math.max(0, Math.round(now / 1000 - lag.oldest)) } : null;
+ const ages = [write.requests_pending.oldest_age_seconds, commitsBehind?.oldest_age_seconds ?? null].filter((age): age is number => age !== null);
+
+ let embedded: AppliedWatermark['embedded_through'];
+ if (await embeddingsDisabled(engine)) embedded = { state: 'embeddings_off', commit: null, before: null, unembedded_pages: 0, held_pages: 0 };
+ else {
+ const column = `cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)}`;
+ const [waiting] = await engine.executeRaw<{ pages: number | string; oldest: unknown; held: number | string }>(`WITH w AS (SELECT DISTINCT p.id, p.updated_at FROM content_chunks cc
+ JOIN pages p ON p.id=cc.page_id WHERE ${column} IS NULL AND p.source_id=$1 AND p.deleted_at IS NULL AND ${chunkGenerationFilter('p', 'cc')}
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip'))
+ SELECT count(*) AS pages, min(w.updated_at) AS oldest,
+ (SELECT count(*) FROM w JOIN page_embedding_budget b ON b.page_id=w.id JOIN pages p ON p.id=w.id WHERE ${budgetRowAppliesFilter('b', 'p')}) AS held FROM w`, [sourceId]);
+ const pages = Number(waiting?.pages ?? 0);
+ embedded = pages ? { state: 'partial', commit: null, before: iso(waiting?.oldest), unembedded_pages: pages, held_pages: Number(waiting?.held ?? 0) }
+ : { state: 'complete', commit, before: null, unembedded_pages: 0, held_pages: 0 };
+ }
+
+ const holder = await readDrainHolder(engine, sourceId).catch(() => null);
+ const shown = opts.remote ? publicDrainHolder(holder) : holder;
+ const lastProgress = holder?.progress?.last_progress_at ?? null;
+ return {
+ source_id: sourceId,
+ read_at: new Date(now).toISOString(),
+ indexed_through: write.indexed_through,
+ embedded_through: embedded,
+ committed_through_request: write.committed_through_request,
+ pending: {
+ count: write.requests_pending.count + (filesBehind ?? 0) + heldFiles + deletesWithheld,
+ oldest_age_seconds: ages.length ? Math.max(...ages) : null,
+ requests: write.requests_pending,
+ commits_behind: commitsBehind,
+ files_behind: filesBehind,
+ held_files: heldFiles,
+ deletes_withheld: deletesWithheld,
+ },
+ writer_heartbeat: {
+ holder: shown ? { kind: shown.kind, id: shown.id, host: shown.host, pid: shown.pid } : null,
+ heartbeat_age_seconds: ageSeconds(holder?.last_heartbeat_at, now),
+ last_progress_at: lastProgress,
+ progress_age_seconds: ageSeconds(lastProgress, now),
+ stalled: holderStalled(holder, now),
+ },
+ };
+}
+
+/** One status line: `<source>: indexed through <sha>, embedded <state>, N pending (oldest ...), writer ...`. */
+export function formatAppliedWatermark(w: AppliedWatermark): string {
+ const age = (seconds: number | null) => seconds === null ? '' : seconds < 120 ? `${seconds}s` : seconds < 7200 ? `${Math.round(seconds / 60)}m` : `${Math.round(seconds / 3600)}h`;
+ const embedded = w.embedded_through.state === 'complete' ? 'embedded through it'
+ : w.embedded_through.state === 'embeddings_off' ? 'embeddings off'
+ : `${w.embedded_through.unembedded_pages} page(s) wait for vectors${w.embedded_through.held_pages ? ` (${w.embedded_through.held_pages} held)` : ''}`;
+ const parts = [w.pending.requests.count && `${w.pending.requests.count} request(s)`, w.pending.files_behind && `${w.pending.files_behind} file(s) behind`,
+ w.pending.held_files && `${w.pending.held_files} held`, w.pending.deletes_withheld && `${w.pending.deletes_withheld} delete(s) withheld`].filter(Boolean);
+ const pending = parts.length ? `pending: ${parts.join(', ')}${w.pending.oldest_age_seconds !== null ? ` (oldest ${age(w.pending.oldest_age_seconds)})` : ''}` : 'nothing pending';
+ const holder = w.writer_heartbeat.holder;
+ const writer = holder ? `; writer ${holder.kind}${holder.pid ? ` PID ${holder.pid}` : ''}${w.writer_heartbeat.stalled ? ' stalled' : ''}${w.writer_heartbeat.progress_age_seconds !== null ? `, last progress ${age(w.writer_heartbeat.progress_age_seconds)} ago` : ''}` : '';
+ return `${w.source_id}: indexed through ${w.indexed_through.commit?.slice(0, 12) ?? '(never synced)'}, ${embedded}; ${pending}${writer}`;
+}
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index afd54b13d0..c3c985b4d1 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -8,8 +8,7 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { SCREENING_SHARED_READS, batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission,
- withLiveSearchable } from './page-mutations.ts';
+import { SCREENING_SHARED_READS, answerPageWrite, batchSharedReads, emitFenceNotice, initializeLocalPersistence, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';
import { admitBatch } from './page-batch.ts';
import { writeOutcomeUnknown } from './admission-retry.ts';
import { assertPersistenceAccepting, waitForWrites } from './service.ts';
@@ -273,7 +272,7 @@ async function submitManagedImports(ctx: OperationContext, batch: string, params
await Promise.all(rows.map(async (entry, position) => {
try {
// #7106: a new segmented page over 4 MiB replies at commit with `searchable: 'pending'`, read live here.
- const response = await withLiveSearchable(ctx, pendingAwareResponse(ctx, done[position]!));
+ const response = await answerPageWrite(ctx, done[position]!, { gateHold: false });
if (entry.admitted) emitFenceNotice(ctx, response, done[position]!.slug);
settled[entry.index] = { status: 'fulfilled', value: { ...response, ...(entry.typeWarning ? { type_warning: entry.typeWarning } : {}),
...(entry.slugAdvisory ? { slug_advisory: entry.slugAdvisory } : {}) } };
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index e19517ccf6..13ce959fb7 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -1,4 +1,5 @@
import { throwIfHeld } from '../trust/gate-outcomes.ts';
+import { withWriteApplied } from './write-applied.ts';
import { guardRemoteForget, remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { randomUUID } from 'node:crypto';
import type { OperationContext } from '../ops/contract.ts';
@@ -159,7 +160,10 @@ async function inferRememberTarget(ctx: OperationContext, sourceId: string, sour
export async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {
registerMutationPreparer('remember', prepareMemoryMutation);
const sub = await submission(ctx, 'remember', params);
- if (sub.prior) return throwIfHeld(writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs)));
+ if (sub.prior) {
+ const prior = await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs);
+ return withWriteApplied(ctx.engine, prior, () => throwIfHeld(writeResponse(prior)));
+ }
const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;
const [source] = await ctx.engine.executeRaw<RememberSource>(
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
@@ -192,7 +196,8 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),
session_id: ctx.sessionId ?? null },
authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
- const response = throwIfHeld(writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs)));
+ const settled = await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs);
+ const response = await withWriteApplied(ctx.engine, settled, () => throwIfHeld(writeResponse(settled)));
emitFenceNotice(ctx, response, row.slug);
return response;
}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 5b51925e9d..dd6b8cc781 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -31,6 +31,7 @@ import { claimWorktree, getWorktreeBinding } from './ownership.ts';
import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
import type { Principal, WriteRequest } from './model.ts';
+import { withWriteApplied } from './write-applied.ts';
import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarning } from './page-input.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { decideUnboundWrite, isUnboundSourcePage } from './unbound-source.ts';
@@ -198,6 +199,17 @@ export async function withLiveSearchable(ctx: OperationContext, response: Record
return { ...settle(response), ...(receipt ? { write_request: settle(receipt) } : {}) };
}
+/**
+ * #7190: the reply to a page write, with `applied` (write-applied.ts) in the reply and its `write_request`: whether the
+ * write is searchable yet and the gap. A pending write's error receipt carries it too. A failed read leaves it out.
+ */
+export async function answerPageWrite(ctx: OperationContext, row: WriteRequest, opts: { gateHold?: false } = {}): Promise<Record<string, unknown>> {
+ return withWriteApplied(ctx.engine, row, async () => {
+ const reply = pendingAwareResponse(ctx, row);
+ return withLiveSearchable(ctx, opts.gateHold === false ? reply : throwIfHeld(reply, false));
+ });
+}
+
/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice. */
export function emitFenceNotice(ctx: Pick<OperationContext, 'emitNotice'>, response: Record<string, unknown>, slug?: string): void {
const report = response.fences_normalized as FencesNormalized | undefined;
@@ -227,7 +239,7 @@ export async function submitPageMutation(ctx: OperationContext,
// cache could explain drops it and prepares the write once more, uncached, so it ends as it would without it.
const cached = await preadmitReads(ctx.engine);
let prepared = await preparePageAdmission(cached ? { ...ctx, engine: cached } : ctx, { ...input, params });
- if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));
+ if (prepared.prior) return answerPageWrite(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));
const brainId = cached ? cachedPreadmitBrain(ctx.engine) : undefined;
// Phase 4.4: the admission transaction runs on the warm single-write lane when it is free.
const admit = (admission: WriteAdmission) => onPersistenceLane(ctx.engine, transaction => admitWrite(ctx.engine, admission, undefined, transaction),
@@ -238,10 +250,10 @@ export async function submitPageMutation(ctx: OperationContext,
if (!cached || !preadmitRecheckFailed(error)) throw error;
dropPreadmitCache(ctx.engine);
prepared = await preparePageAdmission(ctx, { ...input, params: { ...params, request_id: prepared.admission.requestId } });
- if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));
+ if (prepared.prior) return answerPageWrite(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));
row = await admit(prepared.admission);
}
- const response = await withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs())), false));
+ const response = await answerPageWrite(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs()));
emitFenceNotice(ctx, response, row.slug);
return { ...response, ...(prepared.typeWarning ? { type_warning: prepared.typeWarning } : {}), ...(prepared.slugAdvisory ? { slug_advisory: prepared.slugAdvisory } : {}) };
}
diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.ts
index 6f067a75ad..f26644717c 100644
--- a/src/core/persistence/params.ts
+++ b/src/core/persistence/params.ts
@@ -122,5 +122,6 @@ export const WRITE_RECEIPT_SCHEMA = {
next_action: { type: 'string', enum: [...WRITE_HEALTH_ACTIONS] },
},
},
+ applied: { type: 'object', description: 'Whether the write is searchable yet (searchable_yet, searchable, state), the gap and the source write watermark.' },
},
};
diff --git a/src/core/persistence/resolve-paths.ts b/src/core/persistence/resolve-paths.ts
index 62c93bb4db..b713a06291 100644
--- a/src/core/persistence/resolve-paths.ts
+++ b/src/core/persistence/resolve-paths.ts
@@ -31,15 +31,12 @@ import { opError } from '../ops/contract.ts';
import { resolveSlugForPath, unsyncableReason, type SyncableReason } from '../sync.ts';
import { parseMarkdownHead } from '../markdown.ts';
import { embeddingsDisabled } from '../embedding-disabled.ts';
-import { embeddingStateFix, DELETED_PAGE_PURGE_WINDOW_HOURS, type EmbeddingState } from '../embedding-state.ts';
+import { embeddingStateFix, type EmbeddingState } from '../embedding-state.ts';
+import { PAGE_SEARCHABLE, readPageSearchability } from '../page-searchability.ts';
import { loadSyncEligibility, syncGit } from './sync-discovery.ts';
import { readBlobContents } from './sync-blobs.ts';
import { readGitHold } from './sync-holds.ts';
import { persistenceEnabledForHealth } from './ownership.ts';
-import { budgetRowAppliesFilter } from '../page-size-policy.ts';
-import { chunkGenerationFilter } from '../search/safe-chunks.ts';
-import { quoteIdentifier } from '../search/embedding-column.ts';
-import { embeddingWriteTarget } from '../page-state/projections.ts';
/** Paths one call resolves. */
export const RESOLVE_PATHS_MAX = 200;
@@ -84,12 +81,8 @@ export interface ResolvedPaths {
}
const DOCS = 'docs/guides/resolve-paths.md';
-const SEARCHABLE: Record<EmbeddingState, true | 'keyword' | false> = { embedded: true, pending: 'keyword', keyword_only: 'keyword', quarantined: false, empty: false,
- deleted_page_chunks: false, chunkless_healable: false };
const PAGE_STATE: Record<Exclude<EmbeddingState, 'deleted_page_chunks'>, ResolvePathState> = { embedded: 'searchable', pending: 'pending_embedding',
keyword_only: 'keyword_only', quarantined: 'quarantined', empty: 'empty', chunkless_healable: 'chunkless' };
-/** Worst first: a page with some chunks embedded and some pending reads as pending. */
-const PAGE_STATE_ORDER: EmbeddingState[] = ['quarantined', 'chunkless_healable', 'pending', 'keyword_only', 'empty', 'embedded'];
interface TreeRow { path: string; oid: string; size: number }
@@ -149,32 +142,9 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,
const owners = new Map((await engine.executeRaw<{ slug: string; source_path: string | null }>(
'SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND slug = ANY($2::text[])', [sourceId, slugs])).map(row => [row.slug, row]));
const liveSlugs = [...new Set([...byOrigin.values()].filter(page => !page.deleted).map(page => page.slug))];
- const rows = liveSlugs.length ? await engine.listEmbeddingStateRows({ sourceIds: [sourceId], slugs: liveSlugs, states: PAGE_STATE_ORDER, limit: liveSlugs.length * PAGE_STATE_ORDER.length,
- purgeWindowHours: DELETED_PAGE_PURGE_WINDOW_HOURS }) : [];
- const unembeddedBySlug = new Map<string, number>();
- if (liveSlugs.length) {
- const column = `cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)}`;
- for (const row of await engine.executeRaw<{ slug: string; unembedded: number | string }>(
- `SELECT p.slug, count(cc.id) AS unembedded FROM pages p JOIN content_chunks cc ON cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')} AND ${column} IS NULL
- WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND p.deleted_at IS NULL GROUP BY p.slug`, [sourceId, liveSlugs])) unembeddedBySlug.set(row.slug, Number(row.unembedded));
- }
- const embedding = new Map<string, { state: EmbeddingState; chunks: number; unembedded: number }>();
- for (const row of rows) {
- const prior = embedding.get(row.slug);
- const state = prior && PAGE_STATE_ORDER.indexOf(prior.state) < PAGE_STATE_ORDER.indexOf(row.state) ? prior.state : row.state;
- embedding.set(row.slug, { state, chunks: (prior?.chunks ?? 0) + Number(row.chunks), unembedded: unembeddedBySlug.get(row.slug) ?? 0 });
- }
- const keywordOnly = [...embedding].filter(([, emb]) => emb.state === 'keyword_only').map(([slug]) => slug);
- const budgetHolds = new Map<string, NonNullable<ResolvedPath['embedding_hold']>>();
- if (keywordOnly.length) {
- for (const row of await engine.executeRaw<{ slug: string; state: 'held' | 'capped'; reason: string; updated_at: Date | string }>(
- `SELECT p.slug, b.state, COALESCE(b.reason, 'awaiting_approval') AS reason, b.updated_at
- FROM pages p JOIN page_embedding_budget b ON b.page_id = p.id
- WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND p.deleted_at IS NULL AND ${budgetRowAppliesFilter('b', 'p')}
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`, [sourceId, keywordOnly])) {
- budgetHolds.set(row.slug, { state: row.state, reason: row.reason, updated_at: new Date(row.updated_at).toISOString() });
- }
- }
+ const searchability = await readPageSearchability(engine, sourceId, liveSlugs);
+ const embedding = new Map([...searchability].filter(([, page]) => page.embedding_state).map(([slug, page]) => [slug, { state: page.embedding_state!, chunks: page.chunks, unembedded: page.unembedded }]));
+ const budgetHolds = new Map([...searchability].filter(([, page]) => page.embedding_hold).map(([slug, page]) => [slug, page.embedding_hold!]));
const sync = ['gbrain', 'sync', '--source', sourceId, '--no-pull'];
const syncStatus = ['gbrain', 'sync', 'status', '--source', sourceId, '--json'];
const verify = (path: string) => ['gbrain', 'sources', 'resolve-path', sourceId, path, '--json'];
@@ -198,7 +168,7 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,
skipped: null as ResolvedPath['skipped'], hold: null as ResolvedPath['hold'], embedding_hold: null as ResolvedPath['embedding_hold'] };
const push = (state: ResolvePathState, searchable: ResolvedPath['searchable'], why: string, fix: Action | null, extra: Partial<ResolvedPath> = {}) =>
out.push({ ...base, state, searchable, why, fix, ...extra });
- const liveSearch: ResolvedPath['searchable'] = emb ? SEARCHABLE[emb.state] : false;
+ const liveSearch: ResolvedPath['searchable'] = emb ? PAGE_SEARCHABLE[emb.state] : false;
if (atHead && (current?.oid ?? null) !== (committed?.oid ?? null)) {
push('not_synced_yet', live ? liveSearch : false, `The file at HEAD ${current ? (committed ? 'changed' : 'was added') : 'was removed'} after the last synced commit ${source.last_commit?.slice(0, 12) ?? '(none)'}; the next sync of the source takes it.`,
readFix('Syncs the checkout as it is.', sync, verify(p.input)));
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index cbfbea5f24..6a065ce647 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -56,6 +56,8 @@ export interface WriteReceipt {
created_at?: string;
updated_at?: string;
diagnostic?: WriteDiagnostic;
+ /** #7190: whether the write is searchable yet, the gap and the source's write watermark (write-applied.ts). */
+ applied?: import('./write-applied.ts').WriteApplied;
}
/** Wire names stay separate from the engine's camelCase precondition. */
@@ -149,6 +151,7 @@ export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {
} } : {}),
...(receipt.created_at !== undefined ? { created_at: receipt.created_at } : {}),
...(receipt.updated_at !== undefined ? { updated_at: receipt.updated_at } : {}),
+ ...(receipt.applied !== undefined ? { applied: receipt.applied } : {}),
...(!isTerminalWriteState(receipt.state) && isWriteDiagnostic(receipt.diagnostic) ? { diagnostic: {
age_ms: receipt.diagnostic.age_ms, assessment: receipt.diagnostic.assessment,
reason: receipt.diagnostic.reason, next_action: receipt.diagnostic.next_action,
diff --git a/src/core/persistence/write-applied.ts b/src/core/persistence/write-applied.ts
new file mode 100644
index 0000000000..4279e7e640
--- /dev/null
+++ b/src/core/persistence/write-applied.ts
@@ -0,0 +1,67 @@
+/**
+ * #7190: the answer a write receipt gives to "is this write searchable yet?": the written page's state and
+ * `searchable` (the resolve-path vocabulary), the gap when it is not, and the source's write watermark.
+ *
+ * - pending_write: the request has not settled; `gap.requests_ahead` counts the source's unsettled requests queued before it.
+ * - not_written: it settled without committing (conflict, failed, cancelled).
+ * - deleted: it committed and the page is gone (a delete).
+ * - otherwise the page's state from `page-searchability.ts`; `gap.unembedded_chunks` counts chunks still waiting for a
+ * vector and `embedding_hold` names a budget hold that waits for approval.
+ * `searchable_yet` is true only when search finds the page by keyword and vector.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { isTerminalWriteState } from './types.ts';
+import { readPageSearchability, type PageSearchState } from '../page-searchability.ts';
+import { readWriteWatermark, type WriteWatermark } from './applied-watermark.ts';
+
+export interface WriteApplied {
+ sequence: number;
+ searchable_yet: boolean;
+ searchable: true | 'keyword' | false;
+ state: PageSearchState | 'pending_write' | 'not_written' | 'deleted';
+ page: { slug: string; chunks: number; unembedded: number } | null;
+ embedding_hold: { state: 'held' | 'capped'; reason: string; updated_at: string } | null;
+ gap: { requests_ahead: number; unembedded_chunks: number };
+ watermark: WriteWatermark;
+}
+
+const UNSETTLED = ['queued', 'running', 'recovering'];
+
+export async function readWriteApplied(engine: BrainEngine, row: { source_id: string; source_incarnation: string; slug: string; sequence: string | number; state: string }): Promise<WriteApplied> {
+ const sequence = Number(row.sequence);
+ const watermark = await readWriteWatermark(engine, row.source_id);
+ const base = { sequence, watermark, page: null, embedding_hold: null, searchable_yet: false, searchable: false as const };
+ if (UNSETTLED.includes(row.state)) {
+ const [ahead] = await engine.executeRaw<{ count: number | string }>(`SELECT count(*) AS count FROM persistence_requests
+ WHERE source_id=$1 AND source_incarnation=$2::uuid AND state IN ('queued','running','recovering') AND sequence < $3::bigint`, [row.source_id, row.source_incarnation, sequence]);
+ return { ...base, state: 'pending_write', gap: { requests_ahead: Number(ahead?.count ?? 0), unembedded_chunks: 0 } };
+ }
+ if (row.state !== 'committed') return { ...base, state: 'not_written', gap: { requests_ahead: 0, unembedded_chunks: 0 } };
+ const page = (await readPageSearchability(engine, row.source_id, [row.slug])).get(row.slug);
+ if (!page) return { ...base, state: 'deleted', gap: { requests_ahead: 0, unembedded_chunks: 0 } };
+ return { sequence, watermark, searchable_yet: page.searchable === true && !page.embedding_hold, searchable: page.searchable, state: page.state,
+ page: { slug: row.slug, chunks: page.chunks, unembedded: page.unembedded }, embedding_hold: page.embedding_hold,
+ gap: { requests_ahead: 0, unembedded_chunks: page.unembedded } };
+}
+
+/**
+ * The reply `reply()` builds for `row`, with `applied` in it and in its `write_request`; a pending write's error receipt
+ * carries it too. A failed watermark read leaves it out and never fails the write's reply.
+ */
+export async function withWriteApplied(engine: BrainEngine, row: Parameters<typeof readWriteApplied>[1],
+ reply: () => Record<string, unknown> | Promise<Record<string, unknown>>): Promise<Record<string, unknown>> {
+ const read = () => readWriteApplied(engine, row).catch(() => null);
+ let response: Record<string, unknown>;
+ try { response = await reply(); } catch (error) {
+ if (error instanceof OperationError && error.writeRequest && !isTerminalWriteState(error.writeRequest.state)) {
+ const pending = await read();
+ if (pending) error.writeRequest = { ...error.writeRequest, applied: pending };
+ }
+ throw error;
+ }
+ const applied = await read();
+ if (!applied) return response;
+ const receipt = response.write_request as Record<string, unknown> | undefined;
+ return { ...response, applied, ...(receipt ? { write_request: { ...receipt, applied } } : {}) };
+}
diff --git a/test/applied-watermark-7190.test.ts b/test/applied-watermark-7190.test.ts
new file mode 100644
index 0000000000..2ed7481ff4
--- /dev/null
+++ b/test/applied-watermark-7190.test.ts
@@ -0,0 +1,114 @@
+/**
+ * #7190: a per-source applied-through watermark on write receipts, in `gbrain sources status --json` and in a sync
+ * result. Red on master (no watermark, no receipt `applied`):
+ * - indexed_through moves only when a pass finishes: a sliced pass that stops after one page leaves it where it was;
+ * - pending counts the commits and files on HEAD that have not synced yet;
+ * - a put_page receipt answers whether the write is searchable yet, with the gap, and get_write_request repeats it;
+ * - committed_through_request never passes an unsettled request.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { formatAppliedWatermark, readAppliedWatermark, readWriteWatermark } from '../src/core/persistence/applied-watermark.ts';
+import { readWriteApplied } from '../src/core/persistence/write-applied.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-watermark-7190-'));
+let engine: BrainEngine;
+const git = (root: string, args: string[], env?: Record<string, string>) =>
+ execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } }).trim();
+const commit = (root: string, message: string, at?: number) => {
+ const env = at ? { GIT_COMMITTER_DATE: `@${at} +0000`, GIT_AUTHOR_DATE: `@${at} +0000` } : undefined;
+ git(root, ['add', '.'], env);
+ git(root, ['-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message], env);
+ return git(root, ['rev-parse', 'HEAD']);
+};
+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;
+
+async function syncedSource(): Promise<{ id: string; root: string; head: string }> {
+ const id = `wm-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(root); git(root, ['init', '-q']);
+ writeFileSync(join(root, 'alice-example.md'), note('Alice one.'));
+ const head = commit(root, 'fixture', Math.floor(Date.now() / 1000) - 7200);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ return { id, root, head };
+}
+
+beforeAll(async () => { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }, 60_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+test('indexed_through is the last finished pass, and pending counts what HEAD has not synced', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { id, root, head } = await syncedSource();
+ const synced = await readAppliedWatermark(engine, id);
+ expect(synced.indexed_through.commit).toBe(head);
+ expect(synced.pending).toMatchObject({ count: 0, requests: { count: 0 }, commits_behind: { count: 0 }, files_behind: 0, held_files: 0, deletes_withheld: 0 });
+ expect(synced.writer_heartbeat.holder).toBeNull();
+ expect(synced.embedded_through.state).not.toBe('complete');
+ expect(synced.embedded_through.unembedded_pages + (synced.embedded_through.state === 'embeddings_off' ? 1 : 0)).toBeGreaterThan(0);
+
+ for (const name of ['bob-example', 'carol-example', 'dana-example']) writeFileSync(join(root, `${name}.md`), note(name));
+ const next = commit(root, 'three more', Math.floor(Date.now() / 1000) - 600);
+ const behind = await readAppliedWatermark(engine, id);
+ expect(behind.indexed_through.commit).toBe(head);
+ expect(behind.pending.commits_behind!.count).toBe(1);
+ expect(behind.pending.files_behind).toBe(3);
+ expect(behind.pending.count).toBe(3);
+ expect(behind.pending.oldest_age_seconds).toBeGreaterThanOrEqual(600);
+ expect(formatAppliedWatermark(behind)).toContain(`${id}: indexed through ${head.slice(0, 12)}`);
+
+ const sliced = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true }, { maxPages: 1, maxMs: 60_000 });
+ expect(sliced.status).not.toBe('synced');
+ expect((await readWriteWatermark(engine, id)).indexed_through.commit).toBe(head);
+
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('synced');
+ const done = await readAppliedWatermark(engine, id);
+ expect(done.indexed_through.commit).toBe(next);
+ expect(done.pending.files_behind).toBe(0);
+}), 240_000);
+
+test('a put_page receipt says whether the write is searchable yet, and get_write_request repeats it', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { id } = await syncedSource();
+ const ctx = { engine, config: { engine: engine.kind } as never, remote: false, sourceId: id } as never;
+ const reply = await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'erin-example', source_id: id, content: note('Erin wrote this.') } });
+ const applied = reply.applied as Awaited<ReturnType<typeof readWriteApplied>>;
+ expect(applied).toBeDefined();
+ expect((reply.write_request as { applied?: unknown }).applied).toEqual(applied);
+ expect(applied.state).not.toBe('pending_write');
+ expect(applied.page!.slug).toBe('erin-example');
+ expect(applied.searchable_yet).toBe(applied.searchable === true && !applied.embedding_hold);
+ expect(applied.gap.unembedded_chunks).toBe(applied.page!.unembedded);
+ expect(applied.watermark.committed_through_request).toBeGreaterThanOrEqual(applied.sequence);
+
+ const { operationsByName } = await import('../src/core/operations.ts');
+ const read = await operationsByName.get_write_request!.handler(ctx, { request_id: reply.request_id }) as { applied?: { sequence: number; state: string } };
+ expect(read.applied).toMatchObject({ sequence: applied.sequence, state: applied.state });
+}), 240_000);
+
+test('committed_through_request stops below an unsettled request, which counts the requests queued before it', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { id } = await syncedSource();
+ const [row] = await engine.executeRaw<{ id: string; source_incarnation: string; slug: string; sequence: string }>(
+ "SELECT id, source_incarnation::text AS source_incarnation, slug, sequence::text AS sequence FROM persistence_requests WHERE source_id=$1 AND state='committed' ORDER BY sequence DESC LIMIT 1", [id]);
+ await engine.executeRaw("UPDATE persistence_requests SET state='queued', completed_at=NULL WHERE id=$1", [row!.id]);
+ try {
+ const mark = await readWriteWatermark(engine, id);
+ expect(mark.committed_through_request).toBe(Number(row!.sequence) - 1);
+ expect(mark.requests_pending.count).toBe(1);
+ const pending = await readWriteApplied(engine, { source_id: id, source_incarnation: row!.source_incarnation, slug: row!.slug, sequence: row!.sequence, state: 'queued' });
+ expect(pending).toMatchObject({ state: 'pending_write', searchable: false, searchable_yet: false, gap: { requests_ahead: 0 } });
+ } finally {
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed', completed_at=now() WHERE id=$1", [row!.id]);
+ }
+}), 240_000);