Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

segmented gate: judge marked importer and resident rows by the floor

garrytan0be6171054c5
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index ecdb1611e9..fb1c8bf0aa 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -14,7 +14,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes. `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.
- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).
-- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR`: a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
+- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR`: a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v257). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 819a439884..683f07da53 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -886,6 +886,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.' },
{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text.' },
{ since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
+ { since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index 1a2ee474b1..84a921e7d9 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -137,7 +137,7 @@ export const segmentedWriterGateWork = { reads: 0 };
/**
* Writers seen in the last `SEGMENTED_WRITER_WINDOW_DAYS` days that do not read segmented pages
- * (`segmentedGateWriters`: evidence without the segment-reader mark, or a managed write stamped below
+ * (`segmentedGateWriters`: evidence without the segment-reader mark, or marked evidence of any role stamped below
* `SEGMENTED_WRITER_FLOOR`). Any one keeps segmented storage off. Cached per engine for
* `SEGMENTED_WRITER_GATE_TTL_MS`; `fresh` (doctor) reads through.
*/
diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.ts
index dfeed02dee..9abd781ab0 100644
--- a/src/core/persistence/writer-versions.ts
+++ b/src/core/persistence/writer-versions.ts
@@ -115,10 +115,12 @@ export interface SegmentedGateWriter {
/**
* Writers seen in the last `days` that keep segmented storage off: evidence without the segment-reader mark (an
- * older binary inserts NULL into a column it does not know; rows from before v254 count too), or a managed write
- * stamped below `floor` (an unparsable or missing stamp counts as below). Admitters count in any state, so a
- * failed or still-queued request of an older binary is seen as well; ingest-log and consumer rows are read only
- * when unmarked (ingest_log_unmarked_idx). Not seen: an older binary that writes neither a request nor an
+ * older binary inserts NULL into a column it does not know; rows from before v254 count too), or marked evidence
+ * stamped below `floor` (an unparsable or missing stamp counts as below) from any role: a release below the floor
+ * may write the mark (v0.60.290.0 does). Admitters count in any state, so a failed or still-queued request of an
+ * older binary is seen as well. The ingest log is read in two arms, unmarked and marked rows, each over its
+ * window on its partial index (ingest_log_unmarked_idx, v254; ingest_log_marked_idx, v257), so the read never
+ * scans the whole log. Not seen: an older binary that writes neither a request nor an
* ingest-log row (a single-page put on a brain without managed persistence, a run that dies before logging), and
* one-shot readers and exporters, which write nothing.
*/
@@ -137,8 +139,11 @@ export async function segmentedGateWriters(engine: SqlEngine, days: number, floo
SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,false,MAX(l.created_at),COUNT(*)::integer
FROM ingest_log l CROSS JOIN win WHERE l.writer_segment_reader IS NOT TRUE AND l.created_at>=win.since GROUP BY 2,3,4
UNION ALL
- SELECT 'resident',c.host_id::text,'process:'||c.kind,c.version,false,MAX(c.renewed_at),COUNT(*)::integer
- FROM persistence_consumers c CROSS JOIN win WHERE c.segment_reader IS NOT TRUE AND c.renewed_at>=win.since GROUP BY 2,3,4
+ SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,true,MAX(l.created_at),COUNT(*)::integer
+ FROM ingest_log l CROSS JOIN win WHERE l.writer_segment_reader IS TRUE AND l.created_at>=win.since GROUP BY 2,3,4
+ UNION ALL
+ SELECT 'resident',c.host_id::text,'process:'||c.kind,c.version,COALESCE(c.segment_reader,false),MAX(c.renewed_at),COUNT(*)::integer
+ FROM persistence_consumers c CROSS JOIN win WHERE c.renewed_at>=win.since GROUP BY 2,3,4,5
ORDER BY last_seen DESC`, [days]);
return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version, version_label: writerVersionLabel(row.version),
segment_reader: row.segment_reader === true, last_seen: iso(row.last_seen), requests: Number(row.requests) }))
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index f656de705e..d769ca9622 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 256;
+export const LATEST_SCHEMA_VERSION = 257;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index ebe402e5cf..84adda2632 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -257,6 +257,7 @@ import { v253 } from './v253-page-view-digests.ts';
import { v254 } from './v254-segment-reader-marks.ts';
import { v255 } from './v255-page-body-staging-texts.ts';
import { v256 } from './v256-chunk-retirement-index.ts';
+import { v257 } from './v257-ingest-log-marked-index.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -512,4 +513,5 @@ export const MIGRATIONS: Migration[] = [
v254,
v255,
v256,
+ v257,
];
diff --git a/src/core/schema-migrations/v257-ingest-log-marked-index.ts b/src/core/schema-migrations/v257-ingest-log-marked-index.ts
new file mode 100644
index 0000000000..2be706beaa
--- /dev/null
+++ b/src/core/schema-migrations/v257-ingest-log-marked-index.ts
@@ -0,0 +1,35 @@
+import type { Migration } from './types.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Large pages switch-on flip: the segmented-storage gate
+// (persistence/writer-versions.ts segmentedGateWriters) judges a marked
+// ingest_log row by its version against SEGMENTED_WRITER_FLOOR, because the
+// floor rises above releases that already write the segment-reader mark
+// (v0.60.290.0 marks its rows but must still hold the switch off). So the gate
+// reads the window's marked rows too, not only the unmarked ones v254 indexes.
+// ingest_log_marked_idx is the complement of ingest_log_unmarked_idx: each of
+// the gate's two importer arms reads its 7-day range from one partial index,
+// and together they cover every row once, so the read stays bounded by the
+// window instead of scanning the whole log (the only other ingest_log index
+// leads with source_id). Built online (CONCURRENTLY on Postgres); an
+// interrupted build leaves an INVALID index that the next initSchema drops and
+// rebuilds.
+export const INGEST_LOG_MARKED_INDEX = {
+ name: 'ingest_log_marked_idx',
+ table: 'ingest_log',
+ sql: 'CREATE INDEX IF NOT EXISTS ingest_log_marked_idx ON ingest_log (created_at) WHERE writer_segment_reader IS TRUE',
+};
+
+export const v257: Migration = {
+ version: 257,
+ name: 'ingest_log_marked_index',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 256, INGEST_LOG_MARKED_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 62888f7e46..042f4cfd3f 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1197,6 +1197,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 887cda07a0..bff844dbbd 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1197,6 +1197,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 6795e31c8f..f6b70b56d0 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1193,6 +1193,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 916d6c4c50..e8391545b0 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1200,6 +1200,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 19742ce77c..3a54feede2 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1200,6 +1200,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index f33f2ac2c8..867d8b12e2 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1196,6 +1196,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 32ac4d4e6c..333d2bbf20 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 251,
+ "count": 252,
"gaps": [
17,
18,
@@ -21,6 +21,7 @@
"FACT_UNLINKED_INDEX_SQL": "87dcf23c3fa570d93bfb214b6bbb024faa9ff9bff227aa78869a29580be03298",
"FTS_CJK_BOUNDARY_REGEX": "e8605bc0f2c6f3ecd2b451cbc8a4fe27ae0974d048f0bea655533cf37e0ff88d",
"FTS_INPUT_FUNCTION_SQL": "d2f44fc1ef338ff7563c07659d938b743fedb20230948792c71068c022ec54c3",
+ "INGEST_LOG_MARKED_INDEX": "1099f19af7873878974239a9a6f1a627827221eebd75aea01896246e0809e91c",
"INGEST_LOG_UNMARKED_INDEX": "c94e6b009f830527d2f1d6af1683bee94189474e8e67aa4c60165ab4abbd8726",
"ISSUANCE_CLOCK_SLACK_SECONDS": "8f36c80392df6f9b9c754826289b63969d9d41ca8955213291e4413d614dce35",
"OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX": "e9b472d9db37733e908ea40512ad3f9520d7a6729ce207b0d279d43d3beb5b2f",
@@ -65,7 +66,7 @@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 256,
+ "latest": 257,
"records": [
{
"handler": {
@@ -4004,6 +4005,32 @@
"transaction": false,
"verify": "absent",
"version": 256
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "INGEST_LOG_MARKED_INDEX",
+ "PLANNER_REPAIR_TABLES",
+ "analyzeAfterIndexBuild",
+ "buildIndexOnline",
+ "dropInvalidConcurrentIndex",
+ "migrationNotice",
+ "quietMigrationNotices",
+ "tableRows"
+ ],
+ "sha256": "538f0b1fd2adfa75e7d39fa07b2c11812c5e5bb1b71f8e21ffe934a8fb807b01"
+ },
+ "idempotent": true,
+ "name": "ingest_log_marked_index",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": false,
+ "verify": "absent",
+ "version": 257
}
],
"versions": [
@@ -4257,7 +4284,8 @@
253,
254,
255,
- 256
+ 256,
+ 257
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 7707b1bf2d..2fcf71b041 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -1197,6 +1197,7 @@
"idx_timeline_event_page": "CREATE INDEX idx_timeline_event_page ON public.timeline_entries USING btree (event_page_id) WHERE (event_page_id IS NOT NULL)",
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
+ "ingest_log_marked_idx": "CREATE INDEX ingest_log_marked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS TRUE)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
"ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.ts
index 5a5913a03a..4ad6f5a420 100644
--- a/test/large-pages/segmented-switch.test.ts
+++ b/test/large-pages/segmented-switch.test.ts
@@ -24,9 +24,9 @@ import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
-import { _resetSegmentedWriterGateForTests, readPageBodyPolicy, SEGMENTED_WRITER_GATE_TTL_MS, segmentedPageCeiling, segmentedWriterGateWork } from '../../src/core/page-body/limits.ts';
+import { _resetSegmentedWriterGateForTests, readPageBodyPolicy, SEGMENTED_WRITER_GATE_TTL_MS, SEGMENTED_WRITER_WINDOW_DAYS, segmentedPageCeiling, segmentedWriterGateWork } from '../../src/core/page-body/limits.ts';
import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';
-import { compareWriterVersions, SEGMENTED_WRITER_FLOOR, UNSTAMPED_WRITER } from '../../src/core/persistence/writer-versions.ts';
+import { compareWriterVersions, SEGMENTED_WRITER_FLOOR, segmentedGateWriters, UNSTAMPED_WRITER } from '../../src/core/persistence/writer-versions.ts';
import { BEHAVIOR_CHANGES } from '../../src/core/behavior-change-notice.ts';
import { VERSION } from '../../src/version.ts';
import { localHostId } from '../../src/core/persistence/identity.ts';
@@ -166,6 +166,40 @@ for (const kind of testBackends()) {
} finally { await heartbeat.stop(); }
}, 120_000);
+ test('B3: marked import runs and resident heartbeats are judged by the floor; unmarked ones block at any version', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const below = '0.60.200.0';
+ const importRun = (ref: string, version: string, marked: boolean | null) => engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader)
+ VALUES ('default', 'sync', $1, '[]'::jsonb, 'run', $2, $3::uuid, $4)`, [ref, version, randomUUID(), marked]);
+ const heartbeat = (nonce: string, version: string, marked: boolean | null) => engine.executeRaw(`INSERT INTO persistence_consumers (host_id, pid, nonce, kind, mode, host_json_path, persistence_home, version, segment_reader)
+ VALUES ($1::uuid, 4242, $2, 'serve', 'full', '/tmp/host.json', '/tmp', $3, $4)`, [randomUUID(), nonce, version, marked]);
+ const seen = async (floor?: string) => (await segmentedGateWriters(engine, SEGMENTED_WRITER_WINDOW_DAYS, floor)).map(b => [b.role, b.version, b.segment_reader]).sort();
+
+ await importRun('marked-run', SEGMENTED_WRITER_FLOOR, true);
+ await heartbeat('marked-nonce', SEGMENTED_WRITER_FLOOR, true);
+ expect(await seen()).toEqual([]);
+ expect(await segmentedNow()).toBe(true);
+ const raised = '0.60.291.0';
+ expect(compareWriterVersions(SEGMENTED_WRITER_FLOOR, raised)).toBeLessThan(0);
+ expect(await seen(raised)).toEqual([['importer', SEGMENTED_WRITER_FLOOR, true], ['resident', SEGMENTED_WRITER_FLOOR, true]]);
+
+ await engine.executeRaw(`UPDATE ingest_log SET writer_version=$1 WHERE source_ref='marked-run'`, [below]);
+ await engine.executeRaw(`UPDATE persistence_consumers SET version=$1 WHERE nonce='marked-nonce'`, [below]);
+ expect(await segmentedNow()).toBe(false);
+ expect((await blockersNow()).map(b => [b.role, b.principal, b.version, b.segment_reader]).sort())
+ .toEqual([['importer', 'ingest:sync', below, true], ['resident', 'process:serve', below, true]]);
+ expect((await segmentedStorageCheck(engine)).message).toContain(below);
+
+ await engine.executeRaw(`UPDATE ingest_log SET writer_version=$1 WHERE source_ref='marked-run'`, [VERSION]);
+ await engine.executeRaw(`UPDATE persistence_consumers SET version=$1 WHERE nonce='marked-nonce'`, [VERSION]);
+ expect(await segmentedNow()).toBe(true);
+ await importRun('unmarked-run', VERSION, null);
+ await heartbeat('unmarked-nonce', '99.0.0.0', null);
+ expect(await segmentedNow()).toBe(false);
+ expect((await blockersNow()).map(b => [b.role, b.version, b.segment_reader]).sort())
+ .toEqual([['importer', VERSION, false], ['resident', '99.0.0.0', false]]);
+ }, 120_000);
+
test('B3: a request an older binary admitted counts in any state, not only once committed', async () => inHome(async () => {
await engine.setConfig('pages.segmented_storage', 'on');
const requests = await requestFixture(engine);