Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): append links effect decides a busy page under its lock; inline range hash-checked at its own revision

garrytan8c0f857573a7
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 6b8026b10f..57bb33e4af 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -12,4 +12,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `rebaseStaleEffectRecovery` (the `--keep withdrawn` rebase), `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); the stuck-recovery preview (`recovery-resolve.ts` `scanStuckRecoveries`) lists such a record refused with that code and fix; `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code, or `withdrawal_mirror_failed` for the Git/embedding siblings parked behind the mirror (re-armed once it commits), once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).
-- `src/core/persistence/effect-links.ts` — the `links` effect of a remote page write (`mcp.remote_auto_links`, link_source `mcp-remote-mention`). `runLinksEffect` reconciles a put_page/capture/edit_page page's plain mention edges against its whole compiled truth at the published revision (a later revision skips it as `superseded`), keeping targets that exist in the source, are visible to the writer (`writableTargets`) and sit inside its slug grant, and records missing targets as wanted pages. #7122: an effect with `data.range` (a remote append_page to the compiled truth) is `runAppendLinksEffect`: it reads only those stored truth bytes with the writer's audience (`readBodyRange` with the remote audience on a segmented page, loading only the segments the range overlaps; on an inline page the raw stored truth (`inlineRegions`) with its protected regions cut out of the range, then `sanitizeRemoteBody`), applies the same target filter and adds edges only, never removing one or replacing wanted rows. At a later revision it still runs when the range's trusted bytes hash to `data.range.sha256` (two appends whose effects run after both link both) and is skipped as `superseded` otherwise; a revision that moves between its read and its transaction retries as `revision_conflict`. Tests: `test/persistence-links-effect.test.ts`, `test/large-pages/append-mention-links.test.ts` (both engines; readSegmentTexts spy).
+- `src/core/persistence/effect-links.ts` — the `links` effect of a remote page write (`mcp.remote_auto_links`, link_source `mcp-remote-mention`). `runLinksEffect` reconciles a put_page/capture/edit_page page's plain mention edges against its whole compiled truth at the published revision (a later revision skips it as `superseded`), keeping targets that exist in the source, are visible to the writer (`writableTargets`) and sit inside its slug grant, and records missing targets as wanted pages. #7122: an effect with `data.range` (a remote append_page to the compiled truth) is `runAppendLinksEffect`: it reads only those stored truth bytes with the writer's audience (`readBodyRange` with the remote audience on a segmented page, loading only the segments the range overlaps; on an inline page the raw stored truth (`inlineRegions`) with its protected regions cut out of the range, then `sanitizeRemoteBody`), applies the same target filter and adds edges only, never removing one or replacing wanted rows. At a later revision it still runs when the range's trusted bytes hash to `data.range.sha256` (two appends whose effects run after both link both) and is skipped as `superseded` otherwise (an inline range is hash-checked at its own revision too); a write that lands between its read and its page lock is decided the same way under the lock, by reading the range again at the live revision, so a busy page never makes it retry. Tests: `test/persistence-links-effect.test.ts`, `test/large-pages/append-mention-links.test.ts` (both engines; readSegmentTexts spy).
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 7efcf2ffa3..8436be63d1 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -42,7 +42,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
Writes that change part of a page in time proportional to the change (Wave B spec 6.1, 6.3): `append_page`, segmented `edit_page` and the splice engine both use. Tests: `test/large-pages/append-cost.test.ts`, `test/large-pages/append-concurrency.test.ts` and `test/large-pages/edit-segmented.test.ts`, PGLite and Postgres (helper `test/helpers/append-brain.ts`).
- `src/core/page-body/splice.ts` + `tail-digest.ts` — byte-range splices of a segmented body. `spliceSegmentedBody` replaces stored byte ranges of the live generation (`BodyReplacement`) and stages the next one from the touched segments only: segmentation resumes at the last clean entry point before the first replaced byte and stops at the first old boundary whose entry state the new run reproduces, so later segments keep their bytes, text and chunks and only move (new manifest rows under the same occurrence; content_hash midstate recomputed). An append is an insertion at its region's end: it re-segments the old tail plus the text and moves nothing; an insertion at the truth/timeline boundary belongs to truth (`replacementRegion`), so exactly one row owns it. New segments equal to a replaced one keep its occurrence; the rest are chunked with vectors reused by chunk text. A change that flips a region's fence trust restages the whole body (`rescanned`). `splicePage` reads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind); `spliceWork` counts segments segmented, bytes read and manifest rows (the cost tests' work counters). `tail-digest.ts` is the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (`inlineTailDigest`; segmented pages use `page-window/segmented.ts` `tailDigest`); a tail holding facts or takes text is withheld from a remote caller, since a hash of hidden text is a guessing oracle. The cost test pins that a 10 KB append to a 4 MB and a 16 MB page segments only the tail plus the text, and a forced full-rewrite probe (`appendProbe.fullRewrite`) fails the bound.
-- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a fence marker in it refuses `invalid_params`, and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write. A remote append to the compiled truth records the bytes it added (`PreparedMutation.mentionRange`: stored truth offsets and their SHA-256, from the splice or, inline, from the parsed new truth) and queues a `links` effect carrying them (`data.range`, #7122; see `effect-links.ts`); timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.
+- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a fence marker in it refuses `invalid_params`, and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write. A remote append to the compiled truth records the bytes it added (`PreparedMutation.mentionRange`: stored truth offsets and their SHA-256, from the splice or, inline, the parsed appended bytes placed at the end of the stored truth after publication, so a Tier 1 fence normalization before them cannot shift the range) and queues a `links` effect carrying them (`data.range`, #7122; see `effect-links.ts`); timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.
- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end (`read-range.ts` `hiddenBefore`).
Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.
diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.ts
index cf5f0b1e2f..c612aaee04 100644
--- a/src/core/persistence/effect-links.ts
+++ b/src/core/persistence/effect-links.ts
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import { unmanagedBeliefPoint } from '../belief/projection-point.ts';
import type { PageSnapshot } from '../page-state/types.ts';
-import { OperationError, opError } from '../ops/contract.ts';
+import { OperationError } from '../ops/contract.ts';
import { matchesSlugAllowList, slugUnderBoundPrefixes } from '../ops/context.ts';
import { extractPageLinks, isAutoLinkEnabled, isGlobalBasenameEnabled, makeResolver, type PageLinksResult } from '../link-extraction.ts';
import { protectedRegions } from '../fence-scan.ts';
@@ -145,7 +145,8 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEff
* inside its grant, exactly as runLinksEffect does. It never removes an edge or replaces wanted rows: the rest of the
* page was not read. A later write moves the revision but leaves the appended bytes in place unless it rewrote them, so
* at a later revision the effect still runs when those bytes hash as appended, and is skipped as superseded otherwise
- * (a remote rewrite's own effect reconciles the whole page).
+ * (a remote rewrite's own effect reconciles the whole page). A write that lands between the read and the page lock is
+ * decided the same way under the lock, once: the effect never retries because the page moved.
*/
async function runAppendLinksEffect(engine: BrainEngine, effect: PersistenceEffect, row: WriteRequest, range: AppendedRange, hostId: string): Promise<void> {
const skip = (tx: SqlEngine, reason: string) => completeEffect(tx, effect, { links: 'skipped', reason });
@@ -153,7 +154,8 @@ async function runAppendLinksEffect(engine: BrainEngine, effect: PersistenceEffe
const snapshot = await engine.readPageSnapshot(effect.data.slug!, { sourceId });
if (!snapshot || snapshot.page.id !== effect.data.page_id) return skip(engine, 'superseded');
if (!await isAutoLinkEnabled(engine) || !await isRemoteAutoLinksEnabled(engine)) return skip(engine, 'disabled');
- const text = await appendedText(engine, snapshot, range, snapshot.revision !== effect.revision, row.authority.remote ? 'remote' : 'trusted');
+ const audience: BodyAudience = row.authority.remote ? 'remote' : 'trusted';
+ const text = await appendedText(engine, snapshot, range, snapshot.revision !== effect.revision, audience);
if (text === null) return skip(engine, 'superseded');
const { page } = snapshot;
const { candidates } = await extractPageLinks(page.slug, text, {}, page.type, makeResolver(engine, { mode: 'live', sourceId }), await mentionOptions(engine));
@@ -162,9 +164,9 @@ async function runAppendLinksEffect(engine: BrainEngine, effect: PersistenceEffe
await engine.transaction(async tx => {
const live = await lockedPage(tx, effect, row, snapshot, targets, hostId);
if (!live) return;
- if (live.revision !== snapshot.revision) {
- throw opError('revision_conflict', `Page ${page.slug} changed while its appended mentions were read.`, 'The links effect retries against the current revision.');
- }
+ // Another write (on a busy log, another append) landed between the read and the page lock, which now holds writers off:
+ // the range is read again at the live revision and applies only when it still reads as before, so the effect never retries.
+ if (live.revision !== snapshot.revision && await appendedText(tx, live, range, true, audience) !== text) { await skip(tx, 'superseded'); return; }
const { wanted, owned } = await writableTargets(tx, row, live, targets, skipped);
const additions = mentionEdges(live.page.slug, sourceId, wanted, new Set(owned.map(link => link.slug)));
const added = await beliefs.run(tx, async () => additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0);
@@ -174,8 +176,9 @@ async function runAppendLinksEffect(engine: BrainEngine, effect: PersistenceEffe
}
/**
- * The appended truth bytes [start, end) as `audience` reads them; null when `verify` (the page moved since the append)
- * finds the stored bytes there no longer hash as appended. A segmented page is read through readBodyRange, which loads
+ * The appended truth bytes [start, end) as `audience` reads them; null when the stored bytes there no longer hash as
+ * appended. A segmented range is hash-checked only with `verify` (the page moved since the append: the splice's offsets
+ * are exact); an inline one always, since it is in memory and publication may have rewritten bytes before it. A segmented page is read through readBodyRange, which loads
* only the segments the range overlaps (the remote audience gets the read projection: protected, private and withdrawn
* text never reaches it). An inline truth (bounded by the inline threshold) is read raw, as the append stored it; its
* protected regions are found over the whole truth and cut out of the range before the remote sanitizer.
@@ -195,7 +198,7 @@ async function appendedText(engine: BrainEngine, snapshot: PageSnapshot, range:
return text;
}
const truth = Buffer.from((await inlineRegions(engine, Number(page.id))).truth, 'utf8');
- if (verify && sha256Hex(truth.subarray(range.start, range.end)) !== range.sha256) return null;
+ if (sha256Hex(truth.subarray(range.start, range.end)) !== range.sha256) return null;
if (audience === 'trusted') return truth.subarray(range.start, range.end).toString('utf8');
const text = truth.toString('utf8');
const from = truth.subarray(0, range.start).toString('utf8').length;
diff --git a/src/core/persistence/page-append.ts b/src/core/persistence/page-append.ts
index 4b8b200492..5aa99d7d4d 100644
--- a/src/core/persistence/page-append.ts
+++ b/src/core/persistence/page-append.ts
@@ -417,16 +417,19 @@ export async function prepareAppendMutation(engine: BrainEngine, row: WriteReque
const beforeBytes = Buffer.byteLength(page.compiled_truth ?? '', 'utf8') + Buffer.byteLength(page.timeline ?? '', 'utf8');
const prepared = await preparePageMutation(engine, row, config, { content, expectedRevision: stored.revision }, signal, { clock });
const apply = prepared.apply.bind(prepared);
- // The stored truth is the parsed one (trimmed); the append's bytes are what it adds after the old truth.
+ // The bytes the append adds to the stored truth: the parsed truth (trimmed) after the old one. Publication may still
+ // rewrite bytes before them (Tier 1 fence normalization), so their range is taken from the end of the stored truth.
const truth = region === 'truth' ? Buffer.from(parseMarkdown(content, row.slug).compiled_truth, 'utf8') : null;
const start = Buffer.byteLength(before, 'utf8');
- const mentionRange = truth && truth.length > start && truth.subarray(0, start).equals(Buffer.from(before, 'utf8'))
- ? { start, end: truth.length, sha256: sha256Hex(truth.subarray(start)) } : undefined;
- return { ...prepared, ...(mentionRange ? { mentionRange } : {}), apply: async (tx, preimage) => {
+ const appended = truth && truth.length > start && truth.subarray(0, start).equals(Buffer.from(before, 'utf8')) ? truth.subarray(start) : null;
+ const result = { ...prepared, apply: async (tx, preimage) => {
const outcome = await apply(tx, preimage);
- const [row2] = await tx.executeRaw<{ bytes: string | null }>(`SELECT COALESCE(body_bytes, octet_length(COALESCE(compiled_truth,'')) + octet_length(COALESCE(timeline,'')))::text AS bytes
- FROM pages WHERE id=$1`, [stored.page.id]);
+ const [row2] = await tx.executeRaw<{ bytes: string | null; truth: string | null }>(`SELECT COALESCE(body_bytes, octet_length(COALESCE(compiled_truth,'')) + octet_length(COALESCE(timeline,'')))::text AS bytes,
+ (CASE WHEN body_storage='segmented' THEN truth_bytes ELSE octet_length(COALESCE(compiled_truth,'')) END)::text AS truth FROM pages WHERE id=$1`, [stored.page.id]);
const bodyBytes = Number(row2?.bytes ?? 0);
+ const truthEnd = Number(row2?.truth ?? 0);
+ if (appended && truthEnd >= appended.length) result.mentionRange = { start: truthEnd - appended.length, end: truthEnd, sha256: sha256Hex(appended) };
return { ...outcome, body_bytes: bodyBytes, appended_bytes: Math.max(0, bodyBytes - beforeBytes), chunks_new: Number(outcome.chunks ?? 0), region };
} } as PreparedMutation;
+ return result;
}
diff --git a/test/large-pages/append-mention-links.test.ts b/test/large-pages/append-mention-links.test.ts
index cc2eb48ea0..79e8d32e3e 100644
--- a/test/large-pages/append-mention-links.test.ts
+++ b/test/large-pages/append-mention-links.test.ts
@@ -20,6 +20,9 @@ import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
import { testBackends } from '../helpers/test-backends.ts';
import { waitFor } from '../helpers/wait-for.ts';
import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { runLinksEffect } from '../../src/core/persistence/effect-links.ts';
+import type { PersistenceEffect } from '../../src/core/persistence/effect-model.ts';
+import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from '../../src/core/persistence/protocol.ts';
const SMALL = 'notes/mention-log-small';
const BIG = 'notes/mention-log-big';
@@ -27,6 +30,11 @@ const INLINE = 'notes/mention-log-inline';
const TAKES_SEGMENTED = 'notes/mention-log-takes';
const TAKES_INLINE = 'notes/mention-log-takes-inline';
const FENCED_LATER = 'notes/mention-log-fenced-later';
+const BUSY = 'notes/mention-log-busy';
+const BUSY_INLINE = 'notes/mention-log-busy-inline';
+const NORMALIZED = 'notes/mention-log-normalized';
+/** A takes fence in the two-dash marker form Tier 1 rewrites to the canonical one (one byte more per marker). */
+const TWO_DASH_TAKES = '\n\n## Takes\n\n<!-- gbrain:takes:begin -->\n\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | Widgets will sell | take | brain | 0.5 | 2026-07 | notes |\n<!-- gbrain:takes:end -->\n\nTail paragraph.';
/** About 10 KB of conversation turns, then the mentions. */
const filler = conversationBody(10_000, { seed: 7 });
const mentions = (...slugs: string[]) => `${filler}\n\nFollow-up with ${slugs.map(slug => `[[${slug}]]`).join(', ')}.`;
@@ -35,6 +43,8 @@ const TAKES_BEGIN = '<!--- gbrain:takes:begin -->';
const OPEN_TAKES = `\n\n${TAKES_BEGIN}\nPrivate musing.\n\n${TAKES_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | Widgets will sell | take | brain | 0.5 | 2026-07 | notes |\n<!--- gbrain:takes:end -->\n\nMore private musing.\n`;
/** A line as long as the takes begin marker, which a later trusted edit turns into one without moving any byte after it. */
const PLACEHOLDER = 'x'.repeat(TAKES_BEGIN.length);
+/** Appends the busy-page seam lands at most, across the effects it delays. */
+const BUSY_LANDINGS = 5;
for (const kind of testBackends()) {
describe(`remote append_page mention links (${kind})`, () => {
@@ -54,10 +64,11 @@ for (const kind of testBackends()) {
};
/** Release the page's links effects (and only those) and wait until each settles; returns the segment text loaded meanwhile. */
const runLinks = async (slug: string) => {
- const original = brain.engine.readSegmentTexts.bind(brain.engine);
+ const original = brain.engine.readSegmentTexts;
const loaded = { segments: 0, bytes: 0 };
- brain.engine.readSegmentTexts = (async (sourceId: string, hashes: Uint8Array[]) => {
- const texts = await original(sourceId, hashes);
+ // Unbound, so a transaction engine (which inherits this property) still reads through its own transaction.
+ brain.engine.readSegmentTexts = (async function (this: AppendBrain['engine'], sourceId: string, hashes: Uint8Array[]) {
+ const texts = await original.call(this, sourceId, hashes);
loaded.segments += texts.size;
for (const text of texts.values()) loaded.bytes += text.length;
return texts;
@@ -85,8 +96,13 @@ for (const kind of testBackends()) {
await brain.seed(TAKES_SEGMENTED, `${conversationPage(1_500_000, { seed: 4 }).trimEnd()}${OPEN_TAKES}`);
await brain.seed(TAKES_INLINE, `${conversationPage(20_000, { seed: 5 }).trimEnd()}${OPEN_TAKES}`);
await brain.seed(FENCED_LATER, `${conversationPage(20_000, { seed: 6 }).trimEnd()}\n\n${PLACEHOLDER}\n`);
- for (const slug of [SMALL, BIG, TAKES_SEGMENTED]) expect((await brain.body(slug)).storage).toBe('segmented');
- for (const slug of [INLINE, TAKES_INLINE, FENCED_LATER]) expect((await brain.body(slug)).storage).toBe('inline');
+ await brain.seed(BUSY, conversationPage(1_500_000, { seed: 9 }));
+ await brain.seed(BUSY_INLINE, conversationPage(20_000, { seed: 10 }));
+ // Stored as written (no import screen), so the append's publication is the write that normalizes the fence.
+ await brain.engine.putPage(NORMALIZED, { type: 'note', title: 'Normalized', compiled_truth: `${conversationBody(20_000, { seed: 11 })}${TWO_DASH_TAKES}`, timeline: '', frontmatter: {} } as never,
+ { sourceId: 'default' });
+ for (const slug of [SMALL, BIG, TAKES_SEGMENTED, BUSY]) expect((await brain.body(slug)).storage).toBe('segmented');
+ for (const slug of [INLINE, TAKES_INLINE, FENCED_LATER, BUSY_INLINE, NORMALIZED]) expect((await brain.body(slug)).storage).toBe('inline');
}, 600_000);
afterAll(() => brain.close(), 120_000);
@@ -164,5 +180,58 @@ for (const kind of testBackends()) {
expect(await remoteEdges(FENCED_LATER)).toEqual([]);
expect((await linksEffects(FENCED_LATER)).at(-1)!.outcome).toEqual({ links: 'committed', added: 0, removed: 0, skipped_targets: [] });
}, 300_000);
+
+ test('appends landing between the effect\'s read and its page lock do not make it retry, and its edge lands', async () => {
+ for (const slug of [BUSY_INLINE, BUSY]) {
+ await deferred(() => append(slug, mentions('notes/alice-example')));
+ const [{ id }] = await brain.engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM persistence_effects WHERE kind='links' AND data->>'slug'=$1 ORDER BY id DESC LIMIT 1", [slug]);
+ // Seam: just before the effect takes its page lock (its transaction), another remote append to the page lands. The
+ // effect runs here, outside the consumer, so the consumer publishes that append; its own links effect waits (deferred),
+ // since the effect worker would otherwise queue it behind the running one this append's caller is waiting on.
+ const original = brain.engine.transaction;
+ const claim = original.bind(brain.engine) as typeof original;
+ let landed = 0;
+ let running = false;
+ // A transaction engine inherits this property, so its nested transactions (savepoints) come through here too.
+ brain.engine.transaction = (async function (this: AppendBrain['engine'], fn: (tx: never) => Promise<unknown>, ...rest: unknown[]) {
+ if (running && landed < BUSY_LANDINGS && String(fn).includes('lockedPage(')) {
+ landed++;
+ await deferred(() => append(slug, `${filler}\n\nAnother agent's turn ${landed}.`));
+ }
+ return (original as (...args: unknown[]) => Promise<unknown>).call(this, fn, ...rest);
+ }) as typeof brain.engine.transaction;
+ // Counted seam: each pass claims the effect and runs it once, as the effect worker does; a revision_conflict is the
+ // contention the worker would retry 250 ms later.
+ let attempts = 0;
+ try {
+ for (;;) {
+ attempts++;
+ const effect = await claim(async tx => {
+ await declarePersistenceProtocol(tx);
+ return (await tx.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '10 minutes',
+ attempts=attempts+1 WHERE id=$1 AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, randomUUID()]))[0]!;
+ });
+ running = true;
+ try { await runLinksEffect(brain.engine, effect, randomUUID()); break; }
+ catch (error) { if ((error as { code?: string }).code !== 'revision_conflict' || attempts >= BUSY_LANDINGS) throw error; }
+ finally { running = false; }
+ }
+ } finally { brain.engine.transaction = original; }
+ expect({ attempts, landed }).toEqual({ attempts: 1, landed: 1 });
+ expect((await linksEffects(slug)).find(e => e.request_id && e.state === 'committed' && e.outcome?.added === 1)).toBeDefined();
+ expect(await remoteEdges(slug)).toEqual([mention('notes/alice-example')]);
+ }
+ }, 300_000);
+
+ test('an inline append whose publication normalizes a fence before it mines its own text', async () => {
+ await deferred(() => append(NORMALIZED, mentions('notes/alice-example')));
+ const stored = (await brain.body(NORMALIZED)).truth;
+ expect(stored).toContain('<!--- gbrain:takes:begin -->');
+ const [effect] = (await linksEffects(NORMALIZED)).slice(-1);
+ expect(Buffer.byteLength(stored)).toBe(effect!.data.range.end);
+ await runLinks(NORMALIZED);
+ expect(await remoteEdges(NORMALIZED)).toEqual([mention('notes/alice-example')]);
+ expect((await linksEffects(NORMALIZED)).at(-1)!.outcome).toEqual({ links: 'committed', added: 1, removed: 0, skipped_targets: [] });
+ }, 300_000);
});
}