Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1b: load probe, inventories and generations.md managed section

garrytanf26bd17e4e9a
diff --git a/docs/architecture/generations.md b/docs/architecture/generations.md
index 221b4f4f65..40ae6bb0f9 100644
--- a/docs/architecture/generations.md
+++ b/docs/architecture/generations.md
@@ -22,6 +22,11 @@ Migration v265 (a placeholder number, restamped when the change merges) adds fou
later run of the same result stops at that held row until `--mode release-held` publishes it. A fenced producer is
not counted. Only error codes are stored.
+Migration v266 (also a placeholder) adds the managed side (PR 1b): `derived_generations.locator` (a transcript key's
+current file) and `activation_id`, `derived_generation_items.pending` (an item a member request still overwrites or
+retires; a retirement marked pending is `retire_pending` and still live), and `derived_generation_activations`: one row
+per admitted managed activation with its members and whether it activated.
+
## Publishing
Under the item page locks (slug order) and then the key's advisory lock, `publishGeneration`:
@@ -45,15 +50,45 @@ Under the item page locks (slug order) and then the key's advisory lock, `publis
A partial result (an input cut at its cap, #6503) publishes additively: it writes its items, carries the rest of the
live generation forward, retires nothing and completes nothing.
-Adapters (`contract.ts`) own one kind each: `adapters/atoms.ts` (unmanaged atoms, one key per origin page or
-transcript) in this release. Managed brains keep the coordinator path until PR 1b.
+Adapters (`contract.ts`) own one kind each: `adapters/atoms.ts` (atoms, one key per origin page or transcript) in this
+release. An atom's identity leaves out the provenance a managed writer stamps (`source_kind`, `ingested_via`,
+`ingested_at`, `trust_tier` and the other content-hash ephemeral keys), so a managed write never reads as an edit.
+
+### Managed sources
+
+A managed source (`generations/managed.ts`) never composes a generation in one transaction: every page write is its own
+coordinated request with its own file. A publication is planned without locks and admitted as one batch, in order:
+
+1. `create` members: page writes of new identities only (a key no live row holds);
+2. one `managed_generation_activate` request (trusted local only; a remote one is refused): under the member page locks
+ and then the key lock it rechecks the expected generation, the input pin and each member at its planned identity,
+ flips the ledger and marks every item a member still overwrites or retires `pending`;
+3. `overwrite` and `retire` members: the existing per-page managed put and delete requests (version first, stamp), each
+ refusing unless its item is pending on the live generation its activation made, and clearing the mark on commit.
+
+The activation id is digest(operation id, run scope) and each member's digest(activation id, slug, action), so a rerun
+replays them. Between steps 1 and 3 old and new items are both live, never neither. The next extraction run of the
+source resumes pending members (`resumeManagedGenerationMembers`): a request still queued is waited on, one that ended
+without committing is submitted again, and a page edited since keeps its content. Pages a `create` member wrote for an
+activation that never happened are orphan candidates: doctor `generation_pending` and `--mode cleanup` list them with
+their activation id, and nothing retires them automatically.
+
+A transcript's key is its corpus root label and root-relative path (`transcript:corpus/team-a/2026-09-07-standup.txt`),
+never its basename or content hash. A file a live generation names as its `locator` keeps that key, and a file whose
+content equals the input of a live generation whose file is gone was moved: it keeps that key and the locator follows.
+
+`gbrain repair stale-atoms` retires each listed atom as an approved generation of its origin key (no floor or valve),
+bound to the atom's identity; `atoms-restore` keeps its command and JSON and still restores managed retirements, and
+doctor `atom_retirements_restorable` leaves out an atom whose retirement the ledger records, so it warns once.
## Repair
`gbrain repair generations --kind <kind>` is explicit-only and preview-bound (docs/guides/repair.md#generations):
`--mode restore` (the default) republishes the item set the selected live generation replaced, `--mode release-held`
-publishes a held result once. Doctor reports `generation_retirements` (ok, with the restorable count) and
-`generation_held` (warn).
+publishes a held result once (a managed source releases an atom page key through its writer), and `--mode cleanup` lists
+pending members and orphan candidates, read-only. A managed source restores retired atoms with `gbrain repair
+atoms-restore`; `--mode restore` refuses there. Doctor reports `generation_retirements` (ok, with the restorable
+count), `generation_held` (warn) and `generation_pending` (warn).
## Purge
@@ -95,3 +130,10 @@ proposal carrying the claim (`ledger-scrub.ts`). Restore then refuses that item
- Attempts have their own table instead of the held row's `attempts` column, because a held row means a result
waits for the operator (doctor warns, release-held lists it) and a key has at most one; counting failures there
would warn before any result is held and displace a real held result.
+- The shrink floor holds a result strictly below `shrink_floor` of the owned items (scaled by the input ratio), so a
+ result exactly at the floor publishes; this is the plan's "below it the result is held".
+- A managed activation's id includes the producer's run scope, because a connector run refused after an owner claimed the
+ source must not collide with the owner's run of the same result.
+- Managed `--mode restore` is refused and `atoms-restore` stays the managed restore path, because a generation restore
+ writes pages in one transaction, which a managed source cannot do; a managed restore through member requests is left
+ for a later PR.
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index a12d82e442..ff25f13544 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -63,10 +63,11 @@ const ROWS: readonly Row[] = [
['decide_sweep_deferred', 'out_of_scope', 'no_memory_text', 'source_id slot reason'],
['decision_receipts', 'out_of_scope', 'probed_reported', 'decision_id source_id slot mode provider model_alias model_resolved question_kind state_hash question_hash answer_choice outcome subject_ref call_site lane policy_fingerprint calibration_ref error_reason run_meta', 'run_meta'],
['derivation_inputs', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id input_table input_id source_id'],
+ ['derived_generation_activations', 'out_of_scope', 'no_memory_text', 'id source_id kind owner_key input_pin item_set_hash state members'],
['derived_generation_attempts', 'out_of_scope', 'no_memory_text', 'hold_id source_id kind owner_key codes'],
['derived_generation_items', 'swept', 'generation_ledger', 'item_key identity_hash action preimage', 'preimage'],
['derived_generation_valve', 'out_of_scope', 'no_memory_text', 'source_id kind window_key'],
- ['derived_generations', 'swept', 'generation_ledger', 'source_id kind owner_key state run_id operation_id hold_id input_pin completeness item_set_hash held_reason held_context proposal', 'held_context proposal'],
+ ['derived_generations', 'swept', 'generation_ledger', 'source_id kind owner_key state run_id operation_id hold_id input_pin completeness item_set_hash held_reason held_context proposal locator activation_id', 'held_context proposal'],
['dream_synthesis_completions', 'out_of_scope', 'no_memory_text', 'source_id idempotency_key'],
['dream_verdicts', 'out_of_scope', 'probed_reported', 'file_path content_hash reasons content_type segments entities model', 'segments entities reasons'],
['drift_decisions', 'out_of_scope', 'probed_reported', 'reasoning applied_by', 'reasoning'],
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 98229c2d05..ec1091454e 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -57,6 +57,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('decide_sweep_deferred', 'operational', 'Deferred System One sweep work with its schedule.'),
carry('decision_receipts', 'user_data', 'Durable System One decision receipts.'),
carry('derivation_inputs', 'user_data', 'Derivation dependency edges (#5575); purge needs them to find artifacts derived from purged content.'),
+ carry('derived_generation_activations', 'operational', 'Managed generation activations (GBRA-161 PR 1b): each admitted activation, its members and whether it activated; resume and the orphan listing read it.'),
carry('derived_generation_attempts', 'operational', 'Generation attempt counters per hold identity (GBRA-161): three terminal failures hold the result attempts_exhausted.'),
carry('derived_generation_items', 'user_data', 'Generation ledger items (GBRA-161): which derived items each generation owns, with the bounded preimages a restore republishes.'),
carry('derived_generation_valve', 'operational', 'Generation retirement valve counters per run window (GBRA-161).'),
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 3f07ec2f79..9a3a28f220 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 140, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 141, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/pathological/g1-generation-load.test.ts b/test/pathological/g1-generation-load.test.ts
new file mode 100644
index 0000000000..8cb9ade00f
--- /dev/null
+++ b/test/pathological/g1-generation-load.test.ts
@@ -0,0 +1,93 @@
+/**
+ * GBRA-161 PR 1b load probe (opt-in: GBRAIN_TEST_GENERATION_LOAD=1; GBRAIN_TEST_GENERATION_LOAD_ORIGINS, default 10000): publishes
+ * one atom generation per origin page through the primitive, then a second generation per origin that replaces its atom
+ * (one retirement each), and reports lock-wait percentiles (page locks and the generation key lock, measured per call)
+ * and ledger growth (rows and on-disk bytes of derived_generations and derived_generation_items). Postgres runs 8
+ * publishers at once; PGLite has one connection. It reports numbers and asserts only that every publication landed:
+ * the plan sets no threshold.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { atomGenerationAdapter, atomOwnerKey, readAtomInput } from '../../src/core/generations/adapters/atoms.ts';
+import { markdownItem } from '../../src/core/generations/adapters/page.ts';
+import { publishGeneration } from '../../src/core/generations/publish.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+const ENABLED = process.env.GBRAIN_TEST_GENERATION_LOAD === '1';
+const ORIGINS = Number(process.env.GBRAIN_TEST_GENERATION_LOAD_ORIGINS ?? 10000);
+
+const percentile = (values: number[], p: number) => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)]! : 0; };
+const atomMarkdown = (origin: string, title: string) => '---\ntype: atom\ntitle: ' + title + '\natom_type: insight\nsource_slug: ' + origin + '\nextracted_by: extract_atoms-load\n---\n' + title + '.\n';
+
+async function ledgerSize(engine: BrainEngine) {
+ const [row] = await engine.executeRaw<{ generations: number; items: number; generation_bytes: string; item_bytes: string }>(
+ "SELECT (SELECT count(*)::int FROM derived_generations) AS generations, (SELECT count(*)::int FROM derived_generation_items) AS items, pg_total_relation_size('derived_generations')::text AS generation_bytes, pg_total_relation_size('derived_generation_items')::text AS item_bytes");
+ return { generations: Number(row!.generations), items: Number(row!.items), generation_bytes: Number(row!.generation_bytes), item_bytes: Number(row!.item_bytes) };
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe('GBRA-161 PR 1b generation load probe (' + backend + ')', () => {
+ test.skipIf(!ENABLED)(ORIGINS + ' origins: two generations each; lock-wait percentiles and ledger growth', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g1-load-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ const proto = Object.getPrototypeOf(engine) as BrainEngine;
+ const pageLocks: number[] = []; const keyLocks: number[] = [];
+ const lockPageKeys = proto.lockPageKeys; const executeRaw = proto.executeRaw;
+ proto.lockPageKeys = async function (this: BrainEngine, ...args: Parameters<BrainEngine['lockPageKeys']>) {
+ const started = performance.now(); try { return await lockPageKeys.apply(this, args); } finally { pageLocks.push(performance.now() - started); }
+ };
+ proto.executeRaw = async function (this: BrainEngine, ...args: Parameters<BrainEngine['executeRaw']>) {
+ const keyed = typeof args[1]?.[0] === 'string' && String(args[1][0]).startsWith('gbrain:generation:');
+ const started = performance.now();
+ try { return await (executeRaw as (...a: unknown[]) => Promise<unknown>).apply(this, args); } finally { if (keyed) keyLocks.push(performance.now() - started); }
+ } as BrainEngine['executeRaw'];
+ try {
+ const origins = Array.from({ length: ORIGINS }, (_, index) => 'notes/load-' + String(index).padStart(6, '0'));
+ const seeded = performance.now();
+ for (const slug of origins) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Load origin ' + slug + '. The team ships small changes.', timeline: '' });
+ const seedMs = performance.now() - seeded;
+ const empty = await ledgerSize(engine);
+ const workers = backend === 'postgres' ? 8 : 1;
+ const pass = async (title: string) => {
+ pageLocks.length = 0; keyLocks.length = 0;
+ let next = 0; let published = 0;
+ const started = performance.now();
+ await Promise.all(Array.from({ length: workers }, async () => {
+ for (;;) {
+ const index = next++;
+ if (index >= origins.length) return;
+ const origin = origins[index]!;
+ const key = { kind: atomGenerationAdapter.kind, sourceId: 'default', ownerKey: atomOwnerKey({ kind: 'page', slug: origin }) };
+ const slug = 'atoms/load/' + title.toLowerCase().replaceAll(' ', '-') + '-' + String(index).padStart(6, '0');
+ const outcome = await publishGeneration(engine, atomGenerationAdapter, { key, items: [markdownItem(slug, atomMarkdown(origin, title))],
+ input: await readAtomInput(engine, key), runId: 'load:' + title + ':' + index });
+ if (outcome.state === 'published') published++;
+ }
+ }));
+ return { title, published, ms: Math.round(performance.now() - started),
+ page_lock_ms: { p50: +percentile(pageLocks, 0.5).toFixed(2), p99: +percentile(pageLocks, 0.99).toFixed(2), max: +Math.max(0, ...pageLocks).toFixed(2), samples: pageLocks.length },
+ key_lock_ms: { p50: +percentile(keyLocks, 0.5).toFixed(2), p99: +percentile(keyLocks, 0.99).toFixed(2), max: +Math.max(0, ...keyLocks).toFixed(2), samples: keyLocks.length },
+ ledger: await ledgerSize(engine) };
+ };
+ const first = await pass('First insight');
+ const second = await pass('Second insight');
+ const report = { backend, origins: ORIGINS, workers, seed_ms: Math.round(seedMs), ledger_before: empty, passes: [first, second],
+ ledger_bytes_per_origin: +(((second.ledger.generation_bytes + second.ledger.item_bytes) - (empty.generation_bytes + empty.item_bytes)) / ORIGINS).toFixed(1) };
+ console.log('[generation-load] ' + JSON.stringify(report));
+ if (process.env.GBRAIN_TEST_GENERATION_LOAD_OUT) writeFileSync(process.env.GBRAIN_TEST_GENERATION_LOAD_OUT + '.' + backend + '.json', JSON.stringify(report, null, 1));
+ expect([first.published, second.published]).toEqual([ORIGINS, ORIGINS]);
+ const [{ retired }] = await engine.executeRaw<{ retired: number }>("SELECT count(*)::int AS retired FROM pages WHERE type='atom' AND deleted_at IS NOT NULL");
+ expect(Number(retired)).toBe(ORIGINS);
+ } finally { proto.lockPageKeys = lockPageKeys; proto.executeRaw = executeRaw; await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 3_600_000);
+ });
+}