Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): publish a page in set-based statements and stamp its claim before the transaction (#6574)

garrytanbffd74ad95b7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f154da17c2..e9e158240f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.208.0] - 2026-10-13
+
+**A large page publishes in a few dozen statements instead of thousands, so a slow database link no longer blocks its source forever (#6574).** Publishing a page re-sent every canonical timeline bullet, fact row and take as its own statement on every write, even a one-word edit. Behind Supabase's transaction pooler with pipelining off (the #6543 setting), each one waited a full round trip. A reported 1.1 MB company page with about 4,100 timeline rows and 1,012 facts needed about 6,000 statements at 56 ms each, ran past the 300 s publication ceiling on every attempt, restarted from zero, and held 99 writes behind it for 16 hours. The same projection on a 2,000-row test page went from 6,036 statements to 21.
+
+### Itemized changes
+
+- **Set-based canonical projection** (`src/core/persistence/canonical-projections.ts`). Timeline rows go in one `INSERT … SELECT FROM jsonb_to_recordset` per 500 rows, straight to the page id the publication already holds locked, with the same `ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING` dedupe and the same free-text sanitizing as `addTimelineEntry`. Fact field refreshes and take resolutions are each one `UPDATE … FROM jsonb_to_recordset` instead of one per row. Each statement stays well inside the publication's 5 s `statement_timeout`.
+- **`insertFacts` inserts in multi-row chunks** (`src/core/engine-sql/facts.ts`), 500 rows per statement, for every caller. Each input's id is mapped back by `(source_markdown_slug, row_num)`: a row the unique index skips stays null, and the first input wins a duplicate row number, as before. The `superseded by #N` pass now reads every target in one statement and writes every link in one more, with the same chain, cycle, int4-overflow and warning rules. Embedded rows keep their `::vector`/`::halfvec` cast, model and text hash. A lone surrogate in free text still lands as U+FFFD.
+- **Guarded fact renumbers** (`src/core/trust/fence-guard.ts`) move in one statement instead of one per row.
+- **No false "owner missing" during a long publish** (`src/core/persistence/consumer.ts`, `group-publish.ts`, `claim-lease.ts`). The publish transaction locks its request rows, so a lease renewal from another connection waited on that lock, overran its deadline, and the claim read lapsed. `gbrain sync` then stopped `drain_stalled` with `owner_missing`. Now the consumer commits one renewal before the transaction opens, stamping the claim `publishing` with a lease of the ceiling plus grace, settle and 30 s, and stops renewing until the publish ends. `sync-drain` already waits on a live `publishing` claim and reports `publication_overdue` past the ceiling. Tradeoff: an owner that crashes mid-publish holds its head until that lease ends, not 30 s.
+- **Slow projection log.** A projection that takes 30 s or more prints `[persistence] phase=publication reason=slow_projection source=… slug=… elapsed_ms=… timeline_rows=… fact_rows=… take_rows=… steps=timeline:…,facts:…,…`, so the slow step is named in one line.
+- **`unexpected_file_bytes` explains itself.** The registry summary said "A canonical skill file mode changed outside publication" and the docs said to run doctor. It now says the file matches neither the recorded prior nor the published bytes, and that the user picks which version to keep. A command that resolves it is a follow-up.
+- **Tests.** `test/canonical-projection-statements.test.ts` projects a 100-row and a 2,000-row page and allows only one extra statement per extra 500-row chunk (on master: 336 and 6,036; now 15 and 21), on PGLite, and checks every row lands once on PGLite and Postgres. New `insertFacts` cases cover a duplicate row number inside a batch, a 1,203-row batch with duplicates and supersession across chunks, embeddings, and hostile text. `test/e2e/publication-claim-lease-6574-postgres.test.ts` holds a put_pages group inside its open transaction and reads each member from another connection: `running`, `publishing`, leased past the ceiling. It fails on master. The SQL-text goldens for `facts` and `_driver` changed because `insertFacts` now sends one multi-row INSERT per chunk.
+
## [0.60.207.0] - 2026-10-13
**The claim root probe's buffer test no longer depends on how random worktree ids happen to sort.** `test/e2e/claim-earlier-equivalence.test.ts` checks that the indexed root probe reads fewer than 0.85× the buffers of the former COALESCE key. Its fixture queued each worktree's rows as one contiguous block. The former key's scan of the pending index `(worktree_id, sequence)` can only use `sequence` as an index condition, so it skipped every root whose rows all came after the candidate. When the random ids sorted in reverse insert order, the former key read 1388 buffers against the current probe's 1309 (ratio 0.943) and the test failed. It failed in #6613's CI at 1308 against `< 1205.3`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 2ee0b362e2..0c76ccb9df 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3115,7 +3115,7 @@ More: [docs/guides/write-refusals.md#unclosed_ambiguous_tail](../../docs/guides/
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A canonical skill file mode changed outside publication. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+| A canonical file a write was publishing (or its file mode) matches neither its recorded prior nor its published bytes, so recovery left it untouched and its worktree stays blocked. | Something outside gbrain edited, split or restored the file while its write was publishing or recovering; gbrain never overwrites bytes it cannot account for. | Do not delete the file to unblock it. Inspect the owner (gbrain sources writer status --json shows the request and its blocked reason) and ask the user which version to keep: the bytes on disk, or the request's recorded prior or published bytes. Run: gbrain sources writer status --json | user | `gbrain doctor --json` | 1 | no |
### unexpected_staging_bytes
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index b83346bca5..aa822c1ed9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -534,6 +534,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.204.0', text: '`recall` now accepts relative `since` phrases it used to refuse (`"6 weeks ago"`, `"a month ago"`, `"last month"`, `"the past 2 years"`; months and years step the calendar), and `question` with `include_expired: true` now ranks expired and superseded facts alongside active ones instead of refusing the call. Every `since` value that parsed before gives the same window, and calls without `include_expired` rank active facts only, as before.' },
// GBRA-81 item 5 (per-stage search timings). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.205.0', text: 'Every `search` and `query` response now carries `_meta.retrieval.timings` (integer milliseconds per stage, `other_ms` and the operation total), and the CLI explain view of `gbrain search` and `gbrain query` prints them as a `timings:` line; results are unchanged and the timings never appear in result text.' },
+ // #6574 (publication round trips). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.207.0', text: 'Publishing a page now writes its timeline rows, fact rows, fact field refreshes and take resolutions in a few set-based statements (one per 500 rows) instead of one statement per row, and `insertFacts` inserts in multi-row chunks for every caller. A large page no longer needs thousands of round trips, so it publishes inside `persistence.publication_ceiling_ms` behind a transaction-mode pooler with pipelining off. A projection that takes 30 s or more logs `[persistence] phase=publication reason=slow_projection` with its row counts and per-step milliseconds.' },
+ { since: '0.60.207.0', text: 'Before a publish opens its transaction, the consumer now commits one claim renewal that stamps the request `publishing` and leases it for the publication ceiling plus its grace, and stops renewing until the publish ends. A long publish no longer reads as a lapsed claim, so `gbrain sync` no longer stops `drain_stalled` with `owner_missing` while the publish is still working; a publish past the ceiling still reports `publication_overdue`. An owner that crashes mid-publish now holds its head until that lease runs out (the ceiling plus about 70 s) rather than 30 s.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index 12b7586580..0b92fcf833 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -30,6 +30,7 @@ import { compileRowNormalizer } from './normalize.ts';
import { projectionEligibleSql } from '../eligibility/sql.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
import { storedTrustTier } from '../trust/tier.ts';
+import { ensureWellFormed } from '../text-safe.ts';
export type EmbeddingCast = '::vector' | '::halfvec';
@@ -158,6 +159,77 @@ export async function expireFact(exec: SqlExecutor, id: number, opts?: { superse
return result.affectedRows > 0;
}
+/** Rows per multi-row fact INSERT: facts carries per-row triggers, and each statement runs under the publication's 5 s statement_timeout. */
+const FACT_INSERT_CHUNK = 500;
+
+const factRowKey = (slug: string, rowNum: number | null) => `${slug}\u0000${rowNum}`;
+
+/** A string bound inside a JSONB document: a lone surrogate becomes U+FFFD, as UTF-8 parameter encoding did for the per-row INSERT. */
+const wellFormed = <T extends string | null | undefined>(s: T): T => (typeof s === 'string' ? ensureWellFormed(s) as T : s);
+
+/**
+ * #6574: inserts fact rows in chunks of FACT_INSERT_CHUNK with one statement
+ * each. Returns each input's new id, aligned to `rows`, or null when the v51
+ * ON CONFLICT DO NOTHING skipped it; within a chunk the first input for a
+ * (slug, row_num) wins, as the per-row loop's order did.
+ */
+async function insertFactRows(tx: SqlExecutor, castSuffix: EmbeddingCast,
+ rows: ReadonlyArray<NewFact & { row_num: number; source_markdown_slug: string }>, sourceId: string): Promise<Array<number | null>> {
+ const rowIds: Array<number | null> = [];
+ for (let at = 0; at < rows.length; at += FACT_INSERT_CHUNK) {
+ const chunk = rows.slice(at, at + FACT_INSERT_CHUNK).map((input, ord) => {
+ const embedding = input.embedding ?? null;
+ return {
+ entity_slug: wellFormed(input.entity_slug ?? null), fact: wellFormed(input.fact), kind: input.kind ?? 'fact',
+ visibility: input.visibility ?? 'private', notability: input.notability ?? 'medium', context: wellFormed(input.context ?? null),
+ valid_from: (input.valid_from ?? new Date()).toISOString(), valid_until: input.valid_until?.toISOString() ?? null,
+ expired_at: input.expired_at?.toISOString() ?? null, source: wellFormed(input.source), source_session: wellFormed(input.source_session ?? null),
+ confidence: input.confidence ?? 1.0, embedding: embedding ? toPgVectorLiteral(embedding) : null,
+ embedded_at: embedding ? new Date().toISOString() : null, embedding_model: embedding ? wellFormed(input.embedding_model ?? null) : null,
+ hash_text: embedding && input.embedding_model ? wellFormed(input.fact) : null,
+ row_num: input.row_num, source_markdown_slug: wellFormed(input.source_markdown_slug),
+ claim_metric: wellFormed(input.claim_metric ?? null), claim_value: input.claim_value ?? null, claim_unit: wellFormed(input.claim_unit ?? null),
+ claim_period: wellFormed(input.claim_period ?? null), event_type: wellFormed(input.event_type ?? null), attributed_to: input.attributed_to ?? null, ord,
+ };
+ });
+ const inserted = (await tx.run<{ id: number; source_markdown_slug: string; row_num: number | null }>(sqlFragment`
+ INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, expired_at, source, source_session, confidence,
+ embedding, embedded_at, embedding_model, embedded_text_hash,
+ row_num, source_markdown_slug,
+ claim_metric, claim_value, claim_unit, claim_period,
+ event_type, attributed_to
+ )
+ SELECT ${sourceId}, r.entity_slug, r.fact, r.kind, r.visibility, r.notability, r.context,
+ r.valid_from::timestamptz, r.valid_until::timestamptz, r.expired_at::timestamptz, r.source, r.source_session, r.confidence,
+ ${castSuffix === '::halfvec' ? trustedSql('r.embedding::halfvec') : trustedSql('r.embedding::vector')}, r.embedded_at::timestamptz, r.embedding_model, md5(r.hash_text),
+ r.row_num, r.source_markdown_slug,
+ r.claim_metric, r.claim_value, r.claim_unit, r.claim_period,
+ r.event_type, r.attributed_to
+ FROM jsonb_to_recordset(${JSON.stringify(chunk)}::text::jsonb) AS r(
+ entity_slug text, fact text, kind text, visibility text, notability text, context text,
+ valid_from text, valid_until text, expired_at text, source text, source_session text, confidence real,
+ embedding text, embedded_at text, embedding_model text, hash_text text,
+ row_num integer, source_markdown_slug text,
+ claim_metric text, claim_value double precision, claim_unit text, claim_period text,
+ event_type text, attributed_to text, ord integer)
+ ORDER BY r.ord
+ ON CONFLICT (source_id, source_markdown_slug, row_num)
+ WHERE row_num IS NOT NULL
+ DO NOTHING
+ RETURNING id, source_markdown_slug, row_num
+ `)).rows;
+ const byKey = new Map<string, number[]>();
+ for (const row of inserted) {
+ const key = factRowKey(row.source_markdown_slug, row.row_num == null ? null : Number(row.row_num));
+ byKey.set(key, [...(byKey.get(key) ?? []), Number(row.id)]);
+ }
+ for (const input of chunk) rowIds.push(byKey.get(factRowKey(input.source_markdown_slug, input.row_num ?? null))?.shift() ?? null);
+ }
+ return rowIds;
+}
+
export async function insertFacts(
exec: SqlExecutor,
resolveCast: ResolveEmbeddingCast | undefined,
@@ -176,9 +248,7 @@ export async function insertFacts(
// deleteForPageFirst runs; stays 0 for the standalone insert path.
let deleted = 0;
// Single transaction so the v51 partial UNIQUE index can roll back
- // the whole batch on constraint violation. Per-row INSERTs (not
- // multi-row VALUES) keep the embedding-vs-no-embedding branching
- // readable; batch sizes are small (5-30 rows per page in practice).
+ // the whole batch on constraint violation.
// v0.46 (#3014): the fence path carries struck rows — `expired_at` is
// stamped inline here, and `superseded by #N` references are resolved
// to `facts.superseded_by` in a second pass below (same transaction).
@@ -214,58 +284,11 @@ export async function insertFacts(
deleted = r.affectedRows;
}
}
- const out: number[] = [];
- // Per-input inserted id, aligned to `rows` (null when the v51
- // ON CONFLICT DO NOTHING skipped the row) — the second pass below
- // must not index `out` positionally, or a skipped row would shift
- // every later UPDATE onto the wrong fact.
- const rowIds: Array<number | null> = [];
- for (const input of rows) {
- const validFrom = input.valid_from ?? new Date();
- const validUntil = input.valid_until ?? null;
- const expiredAt = input.expired_at ?? null;
- const kind = input.kind ?? 'fact';
- const visibility = input.visibility ?? 'private';
- const notability = input.notability ?? 'medium';
- const confidence = input.confidence ?? 1.0;
- const entitySlug = input.entity_slug ?? null;
- const context = input.context ?? null;
- const sourceSession = input.source_session ?? null;
- const embedding = input.embedding ?? null;
- const embeddedAt = embedding ? new Date() : null;
- const embedLit = embedding ? toPgVectorLiteral(embedding) : null;
- // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
- const claimMetric = input.claim_metric ?? null;
- const claimValue = input.claim_value ?? null;
- const claimUnit = input.claim_unit ?? null;
- const claimPeriod = input.claim_period ?? null;
- // v0.40.2.0 — event_type column (Commit 1 migration v89).
- const eventType = input.event_type ?? null;
-
- const ins = (await tx.run<{ id: number }>(sqlFragment`
- INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, expired_at, source, source_session, confidence,
- embedding, embedded_at, embedding_model, embedded_text_hash,
- row_num, source_markdown_slug,
- claim_metric, claim_value, claim_unit, claim_period,
- event_type, attributed_to
- ) VALUES (
- ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
- ${validFrom}, ${validUntil}, ${expiredAt}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : trustedSql(vectorLiteralSql(embedLit, castSuffix))}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? sqlFragment`md5(${input.fact})` : null},
- ${input.row_num}, ${input.source_markdown_slug},
- ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
- ${eventType}, ${input.attributed_to ?? null}
- )
- ON CONFLICT (source_id, source_markdown_slug, row_num)
- WHERE row_num IS NOT NULL
- DO NOTHING
- RETURNING id
- `)).rows;
- if (ins[0]) out.push(Number(ins[0].id));
- rowIds.push(ins[0] ? Number(ins[0].id) : null);
- }
+ // #6574: one INSERT per chunk of rows, not one per row. A publication
+ // over a high-latency link paid a round trip per fact row; a 1,000-row
+ // fence took a minute before anything else ran.
+ const rowIds = await insertFactRows(tx, castSuffix, rows, ctx.source_id);
+ const out = rowIds.filter((id): id is number => id !== null);
// v0.46 (#3014) — second pass: resolve `superseded by #N` page-local
// references to fact ids. Same transaction so a target row inserted
@@ -274,37 +297,45 @@ export async function insertFacts(
// against a target that already existed before this batch. A target
// whose `expired_at` is set resolves only when it is itself superseded
// (an A -> B -> C chain), declared in this batch or already linked in
- // the DB.
+ // the DB. Every target is read in one statement and every link written
+ // in one more (#6574).
+ const refs = rows.flatMap((row, i) => row.superseded_by_row !== undefined && rowIds[i] !== null && isInt4RowRef(row.superseded_by_row)
+ ? [{ slug: row.source_markdown_slug, row_num: row.superseded_by_row }] : []);
+ const targets = new Map<string, { id: number; struck: boolean; next_row: number | null }>();
+ if (refs.length) {
+ const found = (await tx.run<{ slug: string; row_num: number; id: number; expired_at: Date | null; next_row: number | null }>(sqlFragment`
+ SELECT f.source_markdown_slug AS slug, f.row_num, f.id, f.expired_at, n.row_num AS next_row FROM facts f
+ JOIN (SELECT DISTINCT slug, row_num FROM jsonb_to_recordset(${JSON.stringify(refs)}::text::jsonb) AS r(slug text, row_num integer)) t
+ ON f.source_markdown_slug = t.slug AND f.row_num = t.row_num
+ LEFT JOIN facts n ON n.id = f.superseded_by
+ WHERE f.source_id = ${ctx.source_id}
+ `)).rows;
+ for (const t of found) targets.set(factRowKey(t.slug, Number(t.row_num)),
+ { id: Number(t.id), struck: t.expired_at != null, next_row: t.next_row == null ? null : Number(t.next_row) });
+ }
+ const links: Array<{ id: number; superseded_by: number }> = [];
for (let i = 0; i < rows.length; i++) {
const targetRow = rows[i].superseded_by_row;
if (targetRow === undefined || rowIds[i] === null) continue;
const slug = rows[i].source_markdown_slug;
const chain = supersessionChainOf(rows, slug);
- // Only look up an int4-safe target. An absurd `#N` (11+ digits)
- // would overflow the `row_num` comparison and abort the cycle;
- // skipping the lookup leaves `target` undefined, so
- // resolveSupersededByRow treats it as a dangling reference (NULL +
- // warning) instead of throwing.
- let target: SupersedeTarget | undefined;
- if (isInt4RowRef(targetRow)) {
- const found = (await tx.run<{ id: number; expired_at: Date | null; next_row: number | null }>(sqlFragment`
- SELECT f.id, f.expired_at, n.row_num AS next_row FROM facts f
- LEFT JOIN facts n ON n.id = f.superseded_by
- WHERE f.source_id = ${ctx.source_id}
- AND f.source_markdown_slug = ${slug}
- AND f.row_num = ${targetRow}
- LIMIT 1
- `)).rows;
- target = found[0]
- ? { id: Number(found[0].id), struck: found[0].expired_at != null }
- : undefined;
- if (found[0]?.next_row != null && !chain.has(targetRow)) chain.set(targetRow, Number(found[0].next_row));
- }
+ // Only an int4-safe target was looked up. An absurd `#N` (11+ digits)
+ // leaves `target` undefined, so resolveSupersededByRow treats it as a
+ // dangling reference (NULL + warning) instead of throwing.
+ const found = isInt4RowRef(targetRow) ? targets.get(factRowKey(slug, targetRow)) : undefined;
+ const target: SupersedeTarget | undefined = found ? { id: found.id, struck: found.struck } : undefined;
+ if (found?.next_row != null && !chain.has(targetRow)) chain.set(targetRow, found.next_row);
const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug, chain);
if (warning) warnings.push(warning);
- if (superseded_by !== null) {
- (await tx.run(sqlFragment`UPDATE facts SET superseded_by = ${superseded_by} WHERE id = ${rowIds[i]}`)).rows;
- }
+ if (superseded_by === null) continue;
+ links.push({ id: rowIds[i]!, superseded_by });
+ // A later reference to this row sees the link, as the per-row reads did.
+ const own = targets.get(factRowKey(slug, rows[i].row_num));
+ if (own) own.next_row = targetRow;
+ }
+ if (links.length) {
+ await tx.run(sqlFragment`UPDATE facts f SET superseded_by = l.superseded_by
+ FROM jsonb_to_recordset(${JSON.stringify(links)}::text::jsonb) AS l(id bigint, superseded_by bigint) WHERE f.id = l.id`);
}
return out;
});
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9207e93530..db40b353bd 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -463,7 +463,7 @@ export const CODES = {
trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },
unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },
unclosed_ambiguous_tail: { class: 'caller', summary: "A fence has no end marker and text follows its table, and the repair model read that tail as table rows written without pipes or could not tell, so gbrain will not choose where the fence ends; nothing was written.", why: "Closing after the wrong row would hide rows behind the privacy boundary or expose text; a deterministic rule cannot place the end marker and the model declined to, so a person decides. The attempt memo keeps the same bytes from costing a second model call.", actor: 'user', docs: 'docs/guides/write-refusals.md#unclosed_ambiguous_tail', suggestion: 'Read the page (gbrain get --source <id> -- <slug>), add the end marker after the last real row of the named fence (moving any rows the tail holds into the table), commit, then gbrain sync --source <id> --no-pull. The preview (gbrain repair fences --source <id> --only <path>, read-only) names the fence, section and last row.', fix: { argv: ['gbrain', 'repair', 'fences', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Read-only: names each held fence with its section and last parsed row so the person knows where the end marker belongs; writes nothing and calls no model.', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
- unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },
+ unexpected_file_bytes: { class: 'server', actor: 'user', summary: "A canonical file a write was publishing (or its file mode) matches neither its recorded prior nor its published bytes, so recovery left it untouched and its worktree stays blocked.", why: 'Something outside gbrain edited, split or restored the file while its write was publishing or recovering; gbrain never overwrites bytes it cannot account for.', suggestion: "Do not delete the file to unblock it. Inspect the owner (gbrain sources writer status --json shows the request and its blocked reason) and ask the user which version to keep: the bytes on disk, or the request's recorded prior or published bytes.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the blocked request, its source and its blocked reason.', requires_exclusive: false } },
unexpected_staging_bytes: { class: 'server', summary: "Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved." },
unknown: { class: 'server', summary: "An unclassified failure (legacy StructuredError fallback code)." },
unknown_command: { class: 'caller', summary: "The CLI has no command by that name.", suggestion: 'Run `gbrain --help` for the command list.', exit: 2 },
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index b65d17d8c0..94b4a597c9 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -297,6 +297,32 @@ function canonicalTakeRows(body: CanonicalBody): Set<number> {
* the shared scan refuses throws typed `invalid_fence` (wire `invalid_params`)
* naming the first defect's fence, section and reason.
*/
+/** #6574: a canonical projection at least this slow logs its steps. */
+const SLOW_PROJECTION_MS = 30_000;
+
+/** Rows per timeline INSERT (#6574): each statement stays well inside the publication's 5 s statement_timeout. */
+const TIMELINE_INSERT_CHUNK = 500;
+
+function timelineChunks(timeline: ReadonlyMap<string, ExtractedTimelineEntry>): ExtractedTimelineEntry[][] {
+ const entries = [...timeline.values()];
+ const chunks: ExtractedTimelineEntry[][] = [];
+ for (let at = 0; at < entries.length; at += TIMELINE_INSERT_CHUNK) chunks.push(entries.slice(at, at + TIMELINE_INSERT_CHUNK));
+ return chunks;
+}
+
+/**
+ * #6574: a page's canonical timeline rows in one statement per chunk, in body order. The publication already holds the page's
+ * row lock (lockPageKeys), so the rows go straight to its id; free text is sanitized as addTimelineEntry does (#2011).
+ */
+function insertCanonicalTimeline(tx: BrainEngine, pageId: number, entries: ExtractedTimelineEntry[]) {
+ const rows = JSON.stringify(entries.map((entry, ord) => ({ ord, date: entry.date, source: sanitizeForJsonb(entry.source || ''),
+ summary: sanitizeForJsonb(entry.summary), detail: sanitizeForJsonb(entry.detail || '') })));
+ return tx.executeRaw(`INSERT INTO timeline_entries (page_id,date,source,summary,detail)
+ SELECT $1,r.date::date,r.source,r.summary,r.detail FROM jsonb_to_recordset($2::text::jsonb) AS r(ord integer,date text,source text,summary text,detail text)
+ ORDER BY r.ord
+ ON CONFLICT (page_id,date,md5(summary),source) DO NOTHING`, [pageId, rows]);
+}
+
export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {
const scan=scanCanonicalFences(page);
if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);
@@ -390,22 +416,33 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`, [sourceId, slug, incoming]);
- const factFields = factRows.map(fact => () => tx.executeRaw(`UPDATE facts SET kind=$4,notability=$5,context=$6,
- valid_from=COALESCE($7::timestamptz,valid_from),valid_until=$8::timestamptz,expired_at=$9::timestamptz,
- source=$10,confidence=$11,claim_metric=$12,claim_value=$13,claim_unit=$14,claim_period=$15,attributed_to=$16
- WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num=$3`,
- [sourceId, slug, fact.row_num, fact.kind, fact.notability, fact.context, fact.valid_from?.toISOString() ?? null,
- fact.valid_until?.toISOString() ?? null, fact.expired_at?.toISOString() ?? null, fact.source, fact.confidence,
- fact.claim_metric ?? null, fact.claim_value ?? null, fact.claim_unit ?? null, fact.claim_period ?? null, fact.attributed_to ?? null]));
+ // #6574: every fence row's fields refresh in one statement, not one round trip per row.
+ const fieldRows = JSON.stringify([...new Map(factRows.map(fact => [fact.row_num, fact])).values()].map(fact => ({ row_num: fact.row_num, kind: fact.kind, notability: fact.notability,
+ context: fact.context, valid_from: fact.valid_from?.toISOString() ?? null, valid_until: fact.valid_until?.toISOString() ?? null,
+ expired_at: fact.expired_at?.toISOString() ?? null, source: fact.source, confidence: fact.confidence, claim_metric: fact.claim_metric ?? null,
+ claim_value: fact.claim_value ?? null, claim_unit: fact.claim_unit ?? null, claim_period: fact.claim_period ?? null, attributed_to: fact.attributed_to ?? null })));
+ const factFields = () => factRows.length ? tx.executeRaw(`UPDATE facts f SET kind=r.kind,notability=r.notability,context=r.context,
+ valid_from=COALESCE(r.valid_from::timestamptz,f.valid_from),valid_until=r.valid_until::timestamptz,expired_at=r.expired_at::timestamptz,
+ source=r.source,confidence=r.confidence,claim_metric=r.claim_metric,claim_value=r.claim_value,claim_unit=r.claim_unit,
+ claim_period=r.claim_period,attributed_to=r.attributed_to
+ FROM jsonb_to_recordset($3::text::jsonb) AS r(row_num integer,kind text,notability text,context text,valid_from text,valid_until text,
+ expired_at text,source text,confidence real,claim_metric text,claim_value double precision,claim_unit text,claim_period text,attributed_to text)
+ WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num=r.row_num`, [sourceId, slug, fieldRows]) : Promise.resolve([]);
const checkTakes = () => refuseCollisions(tx, id);
const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone]);
// Full canonical versions include resolution fields; a revert restores those
// fields from Markdown too, without the ordinary immutable-resolution API.
- const resolveTakes = takes.map(take => () => tx.executeRaw(`UPDATE takes SET resolved_at=$3::timestamptz,
- resolved_quality=$4,resolved_outcome=$5,resolved_source=$6,resolved_value=$7,resolved_unit=$8,resolved_by=$9
- WHERE page_id=$1 AND row_num=$2`, [id, take.rowNum, take.resolvedAt ?? null, take.resolvedQuality ?? null,
- take.resolvedQuality === 'correct' ? true : take.resolvedQuality === 'incorrect' ? false : null,
- take.resolvedEvidence ?? null, take.resolvedValue ?? null, take.resolvedUnit ?? null, take.resolvedBy ?? null]));
+ const resolutions = JSON.stringify(takes.map(take => ({ row_num: take.rowNum, resolved_at: take.resolvedAt ?? null,
+ resolved_quality: take.resolvedQuality ?? null,
+ resolved_outcome: take.resolvedQuality === 'correct' ? true : take.resolvedQuality === 'incorrect' ? false : null,
+ resolved_source: take.resolvedEvidence ?? null, resolved_value: take.resolvedValue ?? null, resolved_unit: take.resolvedUnit ?? null,
+ resolved_by: take.resolvedBy ?? null })));
+ const resolveTakes = () => tx.executeRaw(`UPDATE takes k SET resolved_at=r.resolved_at::timestamptz,resolved_quality=r.resolved_quality,
+ resolved_outcome=r.resolved_outcome,resolved_source=r.resolved_source,resolved_value=r.resolved_value,resolved_unit=r.resolved_unit,
+ resolved_by=r.resolved_by
+ FROM jsonb_to_recordset($2::text::jsonb) AS r(row_num integer,resolved_at text,resolved_quality text,resolved_outcome boolean,
+ resolved_source text,resolved_value real,resolved_unit text,resolved_by text)
+ WHERE k.page_id=$1 AND k.row_num=r.row_num`, [id, resolutions]);
// Event-page references have a different canonical origin and remain intact;
// new rows carry their Markdown detail on insert, pinned rows refresh only from their preimage.
const timelineRows = [
@@ -413,25 +450,44 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source
AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed`, [id, deletions])
.then(rows => { for (const row of rows) if (row.removed) removedDates.push(row.date); return rows; }),
- ...[...timeline.values()].map(entry => () => tx.addTimelineEntry(slug, entry, { sourceId })),
+ ...timelineChunks(timeline).map(rows => () => insertCanonicalTimeline(tx, id, rows)),
() => tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)
WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`, [id, refreshes]),
];
- if (!projectFences) {
- await pipelined(tx, timelineRows);
- return { timelineRowsRemoved: removedSummary(removedDates) };
- }
- // #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).
- // The timeline rows are independent of the fact and take rows, so they ride in the first pipeline.
- const guard = await guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig }, () => pipelined(tx, [expireFacts, ...timelineRows]));
- if (guard.rows.length) await tx.insertFacts(guard.rows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
- const contested = await guard.finish(tx);
- await pipelined(tx, [...factFields, checkTakes, dropTakes]);
- if (takes.length) {
- await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
- await pipelined(tx, resolveTakes);
+ const started = Date.now();
+ const steps: Array<[string, number]> = [];
+ const step = async <T>(name: string, run: () => Promise<T>): Promise<T> => {
+ const at = Date.now();
+ try { return await run(); } finally { steps.push([name, Date.now() - at]); }
+ };
+ try {
+ if (!projectFences) {
+ await step('timeline', () => pipelined(tx, timelineRows));
+ return { timelineRowsRemoved: removedSummary(removedDates) };
+ }
+ // #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).
+ // The timeline rows are independent of the fact and take rows, so they ride in the first pipeline.
+ const guard = await step('timeline', () => guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig },
+ () => pipelined(tx, [expireFacts, ...timelineRows])));
+ if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
+ const contested = await step('fact_trust', () => guard.finish(tx));
+ await step('fact_fields', () => pipelined(tx, [factFields, checkTakes, dropTakes]));
+ if (takes.length) {
+ await step('takes', async () => {
+ await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
+ await resolveTakes();
+ });
+ }
+ return { timelineRowsRemoved: removedSummary(removedDates), ...(contested.length ? { contested } : {}) };
+ } finally {
+ // #6574: a slow projection names its slow step and its row counts, so a round-trip-bound publish is visible in one line.
+ const elapsed = Date.now() - started;
+ if (elapsed >= SLOW_PROJECTION_MS) {
+ process.stderr.write(`[persistence] phase=publication reason=slow_projection source=${sourceId} slug=${slug} elapsed_ms=${elapsed}`
+ + ` timeline_rows=${timeline.size} fact_rows=${factRows.length} take_rows=${takes.length}`
+ + ` steps=${steps.map(([name, ms]) => `${name}:${ms}`).join(',')}\n`);
+ }
}
- return { timelineRowsRemoved: removedSummary(removedDates), ...(contested.length ? { contested } : {}) };
};
}
diff --git a/src/core/persistence/claim-lease.ts b/src/core/persistence/claim-lease.ts
index 011179fe8d..6ddb24f359 100644
--- a/src/core/persistence/claim-lease.ts
+++ b/src/core/persistence/claim-lease.ts
@@ -96,3 +96,14 @@ export async function endLostLease(lease: ClaimLease, boundMs = 1_000): Promise<
if (timer) clearTimeout(timer);
}
+/**
+ * #6574: before a publication. Its transaction locks the request rows it publishes, so a renewal from another connection
+ * waits on that lock until the publish ends, overruns its deadline, and the claim reads lapsed ("owner missing") for a
+ * publish that is still working. So the cadence stops here, an in-flight renewal settles, and `stamp` commits one renewal
+ * that covers the publication's whole bound. A stamp that fails leaves the claim as it was; the publication still checks
+ * its own token.
+ */
+export async function holdClaimForPublication(lease: ClaimLease, stamp: () => Promise<unknown>): Promise<void> {
+ await lease.end();
+ await stamp().catch(() => undefined);
+}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 23b6106a05..f191ae3e03 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -5,7 +5,7 @@ import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortRea
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
import { preparationConfigView } from './config-snapshot.ts';
-import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
+import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, holdClaimForPublication, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { claimPhaseStamp, claimStateOf, claimTripleText, EXPIRED_PREPARING_CHARGE_SQL, enterClaimPhase, startClaimPhase, type ClaimPhaseClock, type WaitingOn } from './claim-phase.ts';
import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, preparationKind, startPreparation, type PreparationPolicy } from './preparation-budget.ts';
import { isTerminal, type WriteRequest } from './model.ts';
@@ -34,7 +34,7 @@ import { consumerConnectionRoute, consumerStatementEngine, poolerExposureLine }
import { isConnectionLoss } from '../retry-matcher.ts';
import { INSPECT_OWNER_RETRY_MS } from './health.ts';
import { lockOpenOsError } from './native-lock.ts';
-import { boundPublication, readPublicationCeilingMs, type PublicationBound } from './publication-deadline.ts';
+import { boundPublication, publicationLeaseMs, readPublicationCeilingMs, type PublicationBound } from './publication-deadline.ts';
type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };
/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */
@@ -940,7 +940,10 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
preparationActive = false;
enterClaimPhase(clock, 'publishing');
await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
- const { done, settled } = await boundPublication(() => this.publishSingle(row, prepared), this.publicationBound(row, await readPublicationCeilingMs(this.engine), clock));
+ const ceilingMs = await readPublicationCeilingMs(this.engine);
+ await holdClaimForPublication(lease, () => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!,
+ publicationLeaseMs(ceilingMs), undefined, claimPhaseStamp(clock, row.execution_token)));
+ const { done, settled } = await boundPublication(() => this.publishSingle(row, prepared), this.publicationBound(row, ceilingMs, clock));
if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', failureLogText(done), '', row);
if (done.state === 'queued' && done.blocked_reason === 'writer_lock_unavailable') {
root.retryAfterMs = INSPECT_OWNER_RETRY_MS;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 8e12b9c250..c59e258992 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -42,7 +42,7 @@ import { cancelRows, laneFaultBlockedReason, laneFaultCancelMessage, windowPrede
import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,
foregroundPriority, independentGroup, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
-import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
+import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, holdClaimForPublication, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { claimPhaseStamp, enterClaimPhase, startClaimPhase, type ClaimPhaseClock } from './claim-phase.ts';
import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, startPreparation, type PreparationPolicy, type PreparationRun } from './preparation-budget.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
@@ -51,7 +51,7 @@ import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects, queuesMentionLinks, reconcileFinishedBatch } from './effect-journal.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
import { declareDurablePersistence } from './protocol.ts';
-import { bindPublicationTimeouts, boundPublication, publicationTransaction, type PublicationBound } from './publication-deadline.ts';
+import { bindPublicationTimeouts, boundPublication, publicationLeaseMs, publicationTransaction, type PublicationBound } from './publication-deadline.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
@@ -659,6 +659,8 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
const live = rows.map((row, i) => ({ row, i })).filter(({ row }) => !released.has(row.id));
if (!live.length) return progressed;
const liveRows = live.map(({ row }) => row);
+ if (run.publication) await holdClaimForPublication(lease, () => renewGroupClaims(engine, liveRows, publicationLeaseMs(run.publication!.ceilingMs), undefined,
+ live.map(({ i }) => stampOf(i))));
let requeued = new Set<string>();
if (live.every(({ i }) => 'ok' in prepared[i]!)) {
// #6278 lanes: a prefix publishes under the original group's order key, then drops its own begun mark.
diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.ts
index 67698d15a0..6c80f71ce6 100644
--- a/src/core/persistence/publication-deadline.ts
+++ b/src/core/persistence/publication-deadline.ts
@@ -28,6 +28,11 @@ export const PUBLICATION_CEILING_DEFAULT_MS = 5 * 60_000;
/** After the ceiling: how long before the publication's signal is aborted, and how long after that before `restart_required`. */
export const PUBLICATION_GRACE_MS = 30_000;
export const PUBLICATION_SETTLE_MS = 5_000;
+
+/** #6574: the claim lease a publication takes before it opens its transaction: past it, the owner has already reported restart_required. */
+export function publicationLeaseMs(ceilingMs: number, marginMs = 30_000): number {
+ return ceilingMs + PUBLICATION_GRACE_MS + PUBLICATION_SETTLE_MS + marginMs;
+}
const CEILING_TTL_MS = 5_000;
let ceiling = { value: PUBLICATION_CEILING_DEFAULT_MS, at: 0 };
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index 0a5949d041..ae85bd9873 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -60,13 +60,17 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
.map(r => Number(r.row_num)));
let rows = input.rows;
const contested: typeof guarded = [];
+ const moves: Array<{ id: number; row_num: number }> = [];
for (const g of guarded) {
const target = rows.find(r => r.fact === g.fact && r.visibility === g.visibility && !occupied.has(r.row_num));
if (!target) { contested.push(g); continue; }
- await tx.executeRaw('UPDATE facts SET row_num = $2 WHERE id = $1', [Number(g.id), target.row_num]);
+ moves.push({ id: Number(g.id), row_num: target.row_num });
occupied.add(target.row_num);
rows = rows.filter(r => r !== target);
}
+ // #6574: every guarded row moves in one statement; each starts detached (row_num NULL), so no move collides with another.
+ if (moves.length) await tx.executeRaw(`UPDATE facts f SET row_num = m.row_num FROM jsonb_to_recordset($1::text::jsonb) AS m(id bigint, row_num integer)
+ WHERE f.id = m.id`, [JSON.stringify(moves)]);
const gated: Array<{ row: T; decision: GatedRowDecision }> = [];
const inserted: T[] = [];
// Only new rows are gated; owner-tier writers (tool_observed and above) never are, so they read no gate config.
diff --git a/test/canonical-projection-statements.test.ts b/test/canonical-projection-statements.test.ts
new file mode 100644
index 0000000000..c38f43b660
--- /dev/null
+++ b/test/canonical-projection-statements.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #6574: a canonical projection's statement count does not grow with the page.
+ *
+ * Publication ran one statement per timeline row, fact row and take; behind a
+ * transaction-mode pooler with pipelining off, a 7,000-row page paid one round
+ * trip each and never finished inside the publication ceiling. These cases
+ * project a small and a large page and allow the large one only one more
+ * statement per extra 500-row chunk, and check the projected rows are the
+ * page's rows, once each.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } 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 { parseMarkdown } from '../src/core/markdown.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { prepareCanonicalProjections } from '../src/core/persistence/canonical-projections.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-projection-statements-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(dataDir, { recursive: true, force: true });
+});
+
+function pageOf(size: number, prose: string): string {
+ const day = (i: number) => new Date(Date.UTC(2020, 0, 1) + i * 86_400_000).toISOString().slice(0, 10);
+ const facts = ['<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ ...Array.from({ length: size }, (_, i) => `| ${i + 1} | Example claim ${i + 1} | fact | 1.0 | world | medium | 2026-01-01 | | remember | |`),
+ '<!--- gbrain:facts:end -->'].join('\n');
+ const takes = ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',
+ '|---|-------|------|-----|--------|-------|--------|',
+ ...Array.from({ length: 25 }, (_, i) => `| ${i + 1} | Example take ${i + 1} | take | brain | 0.5 | 2026-07 | notes |`),
+ '<!--- gbrain:takes:end -->'].join('\n');
+ const timeline = Array.from({ length: size }, (_, i) => `- **${day(i)}** | markdown — Example event ${i + 1}`).join('\n');
+ return `---\ntype: company\ntitle: Example company\n---\n${prose}\n\n${facts}\n\n${takes}\n\n## Timeline\n\n${timeline}\n`;
+}
+
+/** Counts every statement the transaction handle runs: queries, execs, and a nested transaction's savepoint and release. */
+function countingEngine(tx: BrainEngine): { engine: BrainEngine; count: () => number } {
+ let statements = 0;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const wrap = (handle: any): any => new Proxy(handle, {
+ get(target, key) {
+ const value = Reflect.get(target, key, target);
+ if (key === 'query' || key === 'exec') return (...args: unknown[]) => { statements++; return value.apply(target, args); };
+ if (key === 'transaction') return (fn: (inner: unknown) => unknown) => { statements += 2; return value.call(target, (inner: unknown) => fn(wrap(inner))); };
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const db = wrap((tx as any).db);
+ return { engine: Object.create(tx, { db: { get: () => db } }) as BrainEngine, count: () => statements };
+}
+
+async function withSource(engine: BrainEngine, run: (sourceId: string, put: (slug: string, content: string) => Promise<unknown>) => Promise<void>) {
+ const dir = mkdtempSync(join(dataDir, 'case-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `stmts-${randomUUID().slice(0, 8)}`;
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await run(sourceId, (slug, content) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } }));
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ }
+}
+
+async function projectEdit(engine: BrainEngine, sourceId: string, slug: string, content: string): Promise<number> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ const project = await prepareCanonicalProjections(engine, parseMarkdown(content, slug), slug, sourceId, snapshot, 'editing');
+ let statements = -1;
+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
+ // The statement count reads PGLite's transaction handle; on Postgres the projection runs uncounted and only its rows are checked.
+ if (tx.kind !== 'pglite') { await project(tx); return; }
+ const counted = countingEngine(tx);
+ await project(counted.engine);
+ statements = counted.count();
+ }, TEST_WRITE_ATTRIBUTION));
+ return statements;
+}
+
+async function projectedRows(engine: BrainEngine, sourceId: string, slug: string) {
+ const [row] = await engine.executeRaw<{ timeline: number; distinct_timeline: number; facts: number; takes: number }>(`SELECT
+ (SELECT count(*)::int FROM timeline_entries t WHERE t.page_id=p.id) AS timeline,
+ (SELECT count(DISTINCT (t.date, t.summary))::int FROM timeline_entries t WHERE t.page_id=p.id) AS distinct_timeline,
+ (SELECT count(*)::int FROM facts f WHERE f.source_id=p.source_id AND f.source_markdown_slug=p.slug AND f.expired_at IS NULL) AS facts,
+ (SELECT count(*)::int FROM takes k WHERE k.page_id=p.id) AS takes
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, slug]);
+ return row;
+}
+
+describe('#6574 canonical projection statements', () => {
+ test('a large page projects with a statement count that grows only by chunk, and its rows land once each', async () => {
+ for (const engine of engines) {
+ await withSource(engine, async (sourceId, put) => {
+ const counts: number[] = [];
+ for (const size of [100, 2_000]) {
+ const slug = `companies/example-${size}`;
+ await put(slug, pageOf(size, 'First draft.'));
+ expect(await projectedRows(engine, sourceId, slug)).toEqual({ timeline: size, distinct_timeline: size, facts: size, takes: 25 });
+ const statements = await projectEdit(engine, sourceId, slug, pageOf(size, 'Second draft with one more sentence.'));
+ expect(await projectedRows(engine, sourceId, slug)).toEqual({ timeline: size, distinct_timeline: size, facts: size, takes: 25 });
+ counts.push(statements);
+ }
+ if (engine.kind !== 'pglite') return;
+ // The only growth is one statement per extra 500-row chunk of timeline rows and of fact rows.
+ expect(counts[0]).toBeGreaterThan(0);
+ expect(counts[0]).toBeLessThan(40);
+ expect(counts[1] - counts[0]).toBeLessThanOrEqual(2 * (Math.ceil(2_000 / 500) - 1));
+ });
+ }
+ }, 300_000);
+});
diff --git a/test/e2e/canonical-projection-statements.test.ts b/test/e2e/canonical-projection-statements.test.ts
new file mode 100644
index 0000000000..454598fb77
--- /dev/null
+++ b/test/e2e/canonical-projection-statements.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../canonical-projection-statements.test.ts'));
diff --git a/test/e2e/publication-claim-lease-6574-postgres.test.ts b/test/e2e/publication-claim-lease-6574-postgres.test.ts
new file mode 100644
index 0000000000..956e87a42d
--- /dev/null
+++ b/test/e2e/publication-claim-lease-6574-postgres.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #6574: a publish transaction locks the request rows it publishes, so a lease renewal from another connection waited on
+ * that lock and the claim read lapsed ("owner missing") for a publish that was still working; `gbrain sync` then stopped
+ * `drain_stalled`. The claim is now stamped once, committed, before the transaction opens, for the publication's whole
+ * bound. This holds a put_pages group inside its open transaction and reads each member's claim from another connection:
+ * still running, stamped `publishing`, and leased past the ceiling, not the 30 s renewal lease. Synthetic content only.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer, preparePersistedMutation } from '../../src/core/persistence/service.ts';
+import { claimGroupFollowers, claimNextWrite, publicationGroupKey } from '../../src/core/persistence/journal.ts';
+import { executeClaimedGroup } from '../../src/core/persistence/group-publish.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+const config = { engine: 'postgres' as const, embedding_disabled: true };
+const page = (slug: string, body: string) => ({ slug, content: `---\ntitle: ${slug}\ntype: note\n---\n\n${body}\n` });
+const tick = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+
+d('#6574 publication claim lease (Postgres)', () => {
+ test('a group held inside its publish transaction keeps every member claimed, stamped publishing, past the renewal lease', async () => {
+ const fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-publication-lease-pg-'));
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine: PostgresEngine = pg.engine;
+ const root = join(fixtureDir, 'brain'); mkdirSync(join(root, 'notes'), { recursive: true });
+ _resetWriteThroughCacheForTest();
+ let registration: LocalRegistration;
+ const dispatch = async (name: string, params: Record<string, unknown>) => {
+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params, {
+ remote: true, config, sourceId: 'default',
+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] },
+ logger: { info() {}, warn() {}, error() {} },
+ }));
+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, any>;
+ };
+ try {
+ await withEnv({ GBRAIN_HOME: join(fixtureDir, 'home') }, async () => {
+ await engine.setConfig('sync.repo_path', root);
+ await claimWorktree(engine, 'default', root);
+ registration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['default'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'] });
+ try {
+ const holder = await acquireWorktree((await getWorktreeBinding(engine, 'default'))!, 5000);
+ try {
+ const batch = await dispatch('put_pages', { request_id: randomUUID(), wait_ms: 0, pages: [
+ page('notes/l-1', 'First body.'), page('notes/l-2', 'Second body.'), page('notes/l-3', 'Third body.')] });
+ expect(batch.state).toBe('pending');
+ await disposePersistenceConsumer(engine);
+ } finally { await holder!.release(); }
+ await engine.executeRaw("UPDATE persistence_requests SET state='queued',execution_token=NULL,claim_expires_at=NULL,blocked_reason=NULL WHERE state='running' AND recovery IS NULL");
+ const head = (await claimNextWrite(engine, localHostId()))!;
+ const followers = await claimGroupFollowers(engine, head, publicationGroupKey(head)!, 7);
+ const members = [head, ...followers];
+ expect(members.map(row => row.slug)).toEqual(['notes/l-1', 'notes/l-2', 'notes/l-3']);
+
+ let release!: () => void;
+ const released = new Promise<void>(resolve => { release = resolve; });
+ let held = false;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'publication:after_publication' || held) return;
+ const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE request_id=$1::uuid', [detail.requestId]);
+ if (row?.slug !== 'notes/l-3') return;
+ held = true;
+ await released;
+ });
+ const settled: WriteRequest[] = [];
+ const ceilingMs = 120_000;
+ const run = executeClaimedGroup(engine, members, {
+ hostId: localHostId(), prepare: async row => preparePersistedMutation(engine, row, config as never),
+ settled: row => settled.push(row), publication: { ceilingMs },
+ });
+ for (let i = 0; i < 100 && !held; i++) await tick(50);
+ expect(held).toBe(true);
+ // Read from another connection while the transaction holds the rows: what sync-drain and writer status see.
+ const claims = await engine.executeRaw<{ slug: string; state: string; phase: string | null; lease_s: number }>(`SELECT slug, state,
+ claim_phase->>'phase' AS phase, extract(epoch FROM claim_expires_at - now())::float8 AS lease_s
+ FROM persistence_requests WHERE id = ANY($1::uuid[]) ORDER BY slug`, [members.map(row => row.id)]);
+ release();
+ await run;
+ installFaultHook(undefined);
+ expect(claims.map(c => [c.slug, c.state, c.phase])).toEqual([
+ ['notes/l-1', 'running', 'publishing'], ['notes/l-2', 'running', 'publishing'], ['notes/l-3', 'running', 'publishing']]);
+ for (const claim of claims) expect(Number(claim.lease_s)).toBeGreaterThan(ceilingMs / 1000);
+ expect(settled.map(row => [row.slug, row.state])).toEqual([['notes/l-1', 'committed'], ['notes/l-2', 'committed'], ['notes/l-3', 'committed']]);
+ const [after] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests
+ WHERE id = ANY($1::uuid[]) AND (state <> 'committed' OR claim_expires_at IS NOT NULL)`, [members.map(row => row.id)]);
+ expect(Number(after!.n)).toBe(0);
+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }
+ });
+ } finally {
+ _resetWriteThroughCacheForTest();
+ await pg.close();
+ rmSync(fixtureDir, { recursive: true, force: true });
+ }
+ }, 120_000);
+});
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index ad915fe024..57aaea1c12 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -1614,7 +1614,7 @@
"via": "tagged"
},
{
- "paramCount": 25,
+ "paramCount": 2,
"unsafeOptions": {
"cancelFence": false,
"prepare": true,
@@ -1638,25 +1638,7 @@
"via": "unsafe"
},
{
- "paramCount": 25,
- "unsafeOptions": {
- "cancelFence": false,
- "prepare": true,
- "simple": false
- },
- "via": "unsafe"
- },
- {
- "paramCount": 24,
- "unsafeOptions": {
- "cancelFence": false,
- "prepare": true,
- "simple": false
- },
- "via": "unsafe"
- },
- {
- "paramCount": 3,
+ "paramCount": 2,
"unsafeOptions": {
"cancelFence": false,
"prepare": true,
diff --git a/test/fixtures/goldens/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.json
index 9931a91149..b7ac15dab3 100644
--- a/test/fixtures/goldens/sql-text/facts.json
+++ b/test/fixtures/goldens/sql-text/facts.json
@@ -426,33 +426,10 @@
"lane": "tx",
"params": [
"string",
- "string",
- "string",
- "string",
- "string",
- "string",
- "null",
- "Date",
- "null",
- "null",
- "string",
- "null",
- "number",
- "null",
- "null",
- "null",
- "null",
- "number",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null"
+ "string"
],
- "sql": "INSERT INTO facts ( source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, expired_at, source, source_session, confidence, embedding, embedded_at, embedding_model, embedded_text_hash, row_num, source_markdown_slug, claim_metric, claim_value, claim_unit, claim_period, event_type, attributed_to ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25 ) ON CONFLICT (source_id, source_markdown_slug, row_num) WHERE row_num IS NOT NULL DO NOTHING RETURNING id",
- "textSha256": "ea2d66315f5edb9eaa1132fc036a326e5ba4973f89d477ff29c53dd22a980690"
+ "sql": "INSERT INTO facts ( source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, expired_at, source, source_session, confidence, embedding, embedded_at, embedding_model, embedded_text_hash, row_num, source_markdown_slug, claim_metric, claim_value, claim_unit, claim_period, event_type, attributed_to ) SELECT $1, r.entity_slug, r.fact, r.kind, r.visibility, r.notability, r.context, r.valid_from::timestamptz, r.valid_until::timestamptz, r.expired_at::timestamptz, r.source, r.source_session, r.confidence, r.embedding::vector, r.embedded_at::timestamptz, r.embedding_model, md5(r.hash_text), r.row_num, r.source_markdown_slug, r.claim_metric, r.claim_value, r.claim_unit, r.claim_period, r.event_type, r.attributed_to FROM jsonb_to_recordset($2::text::jsonb) AS r( entity_slug text, fact text, kind text, visibility text, notability text, context text, valid_from text, valid_until text, expired_at text, source text, source_session text, confidence real, embedding text, embedded_at text, embedding_model text, hash_text text, row_num integer, source_markdown_slug text, claim_metric text, claim_value double precision, claim_unit text, claim_period text, event_type text, attributed_to text, ord integer) ORDER BY r.ord ON CONFLICT (source_id, source_markdown_slug, row_num) WHERE row_num IS NOT NULL DO NOTHING RETURNING id, source_markdown_slug, row_num",
+ "textSha256": "2601865e0cfed0d3ffb1da93396ad860ffe7981e0808c4f22ef99a11bcf88442"
},
{
"event": "commit",
@@ -484,74 +461,10 @@
"lane": "tx",
"params": [
"string",
- "string",
- "string",
- "string",
- "string",
- "string",
- "null",
- "Date",
- "null",
- "null",
- "string",
- "null",
- "number",
- "null",
- "null",
- "null",
- "null",
- "number",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null"
- ],
- "sql": "INSERT INTO facts ( source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, expired_at, source, source_session, confidence, embedding, embedded_at, embedding_model, embedded_text_hash, row_num, source_markdown_slug, claim_metric, claim_value, claim_unit, claim_period, event_type, attributed_to ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25 ) ON CONFLICT (source_id, source_markdown_slug, row_num) WHERE row_num IS NOT NULL DO NOTHING RETURNING id",
- "textSha256": "ea2d66315f5edb9eaa1132fc036a326e5ba4973f89d477ff29c53dd22a980690"
- },
- {
- "lane": "tx",
- "params": [
- "string",
- "string",
- "string",
- "string",
- "string",
- "string",
- "null",
- "Date",
- "null",
- "null",
- "string",
- "null",
- "number",
- "Date",
- "string",
- "string",
- "number",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null"
- ],
- "sql": "INSERT INTO facts ( source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, expired_at, source, source_session, confidence, embedding, embedded_at, embedding_model, embedded_text_hash, row_num, source_markdown_slug, claim_metric, claim_value, claim_unit, claim_period, event_type, attributed_to ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, '[0.10000000149011612,0.20000000298023224,0.30000001192092896]'::vector, $14, $15, md5($16), $17, $18, $19, $20, $21, $22, $23, $24 ) ON CONFLICT (source_id, source_markdown_slug, row_num) WHERE row_num IS NOT NULL DO NOTHING RETURNING id",
- "textSha256": "55ec99676fc259d94b5e8723d9629d422832e92b2ef019444e55a2de7989556d"
- },
- {
- "lane": "tx",
- "params": [
- "string",
- "string",
- "number"
+ "string"
],
- "sql": "SELECT f.id, f.expired_at, n.row_num AS next_row FROM facts f LEFT JOIN facts n ON n.id = f.superseded_by WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num = $3 LIMIT 1",
- "textSha256": "0d0262b3ffb96f1eee1b39fe4146f4bebddcd648d82fc082fe593ca9bd950d94"
+ "sql": "INSERT INTO facts ( source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, expired_at, source, source_session, confidence, embedding, embedded_at, embedding_model, embedded_text_hash, row_num, source_markdown_slug, claim_metric, claim_value, claim_unit, claim_period, event_type, attributed_to ) SELECT $1, r.entity_slug, r.fact, r.kind, r.visibility, r.notability, r.context, r.valid_from::timestamptz, r.valid_until::timestamptz, r.expired_at::timestamptz, r.source, r.source_session, r.confidence, r.embedding::vector, r.embedded_at::timestamptz, r.embedding_model, md5(r.hash_text), r.row_num, r.source_markdown_slug, r.claim_metric, r.claim_value, r.claim_unit, r.claim_period, r.event_type, r.attributed_to FROM jsonb_to_recordset($2::text::jsonb) AS r( entity_slug text, fact text, kind text, visibility text, notability text, context text, valid_from text, valid_until text, expired_at text, source text, source_session text, confidence real, embedding text, embedded_at text, embedding_model text, hash_text text, row_num integer, source_markdown_slug text, claim_metric text, claim_value double precision, claim_unit text, claim_period text, event_type text, attributed_to text, ord integer) ORDER BY r.ord ON CONFLICT (source_id, source_markdown_slug, row_num) WHERE row_num IS NOT NULL DO NOTHING RETURNING id, source_markdown_slug, row_num",
+ "textSha256": "2601865e0cfed0d3ffb1da93396ad860ffe7981e0808c4f22ef99a11bcf88442"
},
{
"event": "commit",
diff --git a/test/insert-facts-batch.test.ts b/test/insert-facts-batch.test.ts
index 57e5fd5090..aa7b18949a 100644
--- a/test/insert-facts-batch.test.ts
+++ b/test/insert-facts-batch.test.ts
@@ -550,3 +550,56 @@ describe('engine.insertFacts — v0.46 (#3014) atomic deleteForPageFirst reconci
expect(rows.rows.map((x: { fact: string }) => x.fact)).toEqual(['fresh fence row', 'legacy forget record']);
});
});
+
+describe('engine.insertFacts — #6574 chunked multi-row insert', () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const q = async (sql: string, params: unknown[] = []) => (await (engine as any).db.query(sql, params)).rows;
+
+ test('a duplicate row_num inside one batch keeps the first input and nulls the rest, as the per-row loop did', async () => {
+ const r = await engine.insertFacts(
+ [fixtureFact(1, { fact: 'first wins' }), fixtureFact(1, { fact: 'second loses' }), fixtureFact(2, { fact: 'other' })],
+ { source_id: 'default' },
+ );
+ expect(r.inserted).toBe(2);
+ const rows = await q(`SELECT id, row_num, fact FROM facts ORDER BY row_num`);
+ expect(rows.map((x: { fact: string }) => x.fact)).toEqual(['first wins', 'other']);
+ expect(rows.map((x: { id: number }) => Number(x.id))).toEqual(r.ids.map(Number));
+ });
+
+ test('a batch past one chunk keeps order, skips cross-chunk duplicates and resolves supersession across chunks', async () => {
+ const n = 1_203;
+ const rows: BatchFact[] = Array.from({ length: n }, (_, i) => fixtureFact(i + 1, { fact: `claim ${i + 1}` }));
+ rows.push(fixtureFact(7, { fact: 'late duplicate of row 7' }));
+ rows[0] = fixtureFact(1, { fact: 'retired', expired_at: new Date('2026-06-01T00:00:00Z'), superseded_by_row: n });
+ const r = await engine.insertFacts(rows, { source_id: 'default' });
+ expect(r.inserted).toBe(n);
+ expect(r.warnings).toEqual([]);
+ const stored = await q(`SELECT id, row_num, fact, superseded_by FROM facts ORDER BY id`);
+ expect(stored.map((x: { row_num: number }) => Number(x.row_num))).toEqual(Array.from({ length: n }, (_, i) => i + 1));
+ expect(stored.map((x: { id: number }) => Number(x.id))).toEqual(r.ids.map(Number));
+ expect(stored.find((x: { row_num: number }) => Number(x.row_num) === 7).fact).toBe('claim 7');
+ const last = stored.find((x: { row_num: number }) => Number(x.row_num) === n);
+ expect(Number(stored[0].superseded_by)).toBe(Number(last.id));
+ });
+
+ test('an embedded row keeps its vector, model and text hash; a row without one stays unembedded', async () => {
+ const [{ dims }] = await q(`SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'facts'::regclass AND attname = 'embedding'`);
+ const vector = new Float32Array(Number(dims)).fill(0.25);
+ await engine.insertFacts(
+ [fixtureFact(1, { fact: 'embedded', embedding: vector, embedding_model: 'test-model' }), fixtureFact(2, { fact: 'plain', embedding_model: 'ignored' })],
+ { source_id: 'default' },
+ );
+ const rows = await q(`SELECT row_num, embedding IS NOT NULL AS has_vector, embedded_at IS NOT NULL AS has_at, embedding_model,
+ embedded_text_hash = md5(fact) AS hash_ok, embedded_text_hash FROM facts ORDER BY row_num`);
+ expect(rows[0]).toMatchObject({ has_vector: true, has_at: true, embedding_model: 'test-model', hash_ok: true });
+ expect(rows[1]).toMatchObject({ has_vector: false, has_at: false, embedding_model: null, embedded_text_hash: null });
+ });
+
+ test('free text with JSON-hostile characters and a lone surrogate lands intact (the surrogate as U+FFFD)', async () => {
+ const hostile = 'quotes " \\ backslash, {braces}, [brackets], comma, em — dash, emoji 🚀, lone \uD83D end';
+ await engine.insertFacts([fixtureFact(1, { fact: hostile, context: 'ctx "q"' })], { source_id: 'default' });
+ const [row] = await q(`SELECT fact, context FROM facts`);
+ expect(row.fact).toBe(hostile.replace('\uD83D end', '\uFFFD end'));
+ expect(row.context).toBe('ctx "q"');
+ });
+});
diff --git a/test/persistence-claim-lease.test.ts b/test/persistence-claim-lease.test.ts
index 3f691c4a97..e8216fc4b1 100644
--- a/test/persistence-claim-lease.test.ts
+++ b/test/persistence-claim-lease.test.ts
@@ -13,7 +13,7 @@
* in milliseconds, with no datastore.
*/
import { describe, expect, test } from 'bun:test';
-import { CLAIM_LOST, endLostLease, startClaimLease } from '../src/core/persistence/claim-lease.ts';
+import { CLAIM_LOST, endLostLease, holdClaimForPublication, startClaimLease } from '../src/core/persistence/claim-lease.ts';
const FAST = { everyMs: 5, deadlineMs: 40 };
const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
@@ -147,3 +147,34 @@ describe('startClaimLease', () => {
expect(performance.now() - started).toBeLessThan(1_000);
});
});
+
+describe('holdClaimForPublication (#6574)', () => {
+ test('stops the cadence, lets the in-flight renewal settle first, then stamps once', async () => {
+ const order: string[] = [];
+ let renewals = 0;
+ let finishRenewal!: () => void;
+ const lease = startClaimLease(async () => {
+ renewals++;
+ order.push('renewal started');
+ await new Promise<void>(resolve => { finishRenewal = resolve; });
+ order.push('renewal settled');
+ return true;
+ }, { everyMs: 5, deadlineMs: 5_000 });
+ for (let i = 0; i < 200 && renewals === 0; i++) await sleep(5);
+ expect(renewals).toBe(1);
+ const held = holdClaimForPublication(lease, async () => { order.push('stamped'); });
+ await sleep(20);
+ expect(order).toEqual(['renewal started']);
+ finishRenewal();
+ await held;
+ expect(order).toEqual(['renewal started', 'renewal settled', 'stamped']);
+ await sleep(30);
+ expect(renewals).toBe(1);
+ expect(lease.held).toBe(true);
+ });
+
+ test('a stamp that fails leaves the publication to its own token check instead of throwing', async () => {
+ const lease = startClaimLease(async () => true, FAST);
+ await expect(holdClaimForPublication(lease, async () => { throw new Error('connection reset'); })).resolves.toBeUndefined();
+ });
+});