Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): forecast capacity from the 7-day aggregate; size defaults from a growth model (#6696 A3, A2)

garrytan099fdc5c0714
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 6522ec57ae..68501aee0b 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -839,8 +839,8 @@ Default admission limits are enforced atomically:
| --- | ---: | ---: |
| Outstanding requests | 100 | 1,000 |
| Queued intent bytes | 32 MiB | 256 MiB |
-| Lifetime request IDs | 250,000 | 1,000,000 |
-| Terminal receipt reservation | 1.5 GiB | 8 GiB |
+| Lifetime request IDs | 2,000,000 | 8,000,000 |
+| Terminal receipt reservation | 16 GiB | 64 GiB |
| Recovery bytes | — | 1 GiB, also 256 MiB per worktree |
Completion space is reserved at admission. Beforeimage/recovery bytes are
@@ -852,10 +852,15 @@ not evicted, and receipts with unfinished effects stay retained without
blocking compaction of later receipts. Lifetime IDs and replay protection are
not silently reset.
-Each admission reserves at least 16 KiB of receipt bytes until compaction; a
-compacted receipt keeps about 4 KiB. The cumulative defaults cover one
-principal admitting about 600 writes a day for at least a year. Every limit and
-the retention window are brain-wide database settings:
+Each admission reserves at least 16 KiB of receipt bytes. When the request
+finishes and none of its effects is still pending, the reservation shrinks in
+the same statement to what the receipt keeps (its intent, authority, outcome,
+error, effects and 4 KiB of slack), so a `remember`, a maintenance write or a
+conflict gives most of its 16 KiB back at once; a page write whose embedding or
+Git effect is still queued keeps its reservation until compaction. A compacted
+receipt keeps about 4 KiB. The cumulative defaults cover one principal
+admitting 5,000 writes a day for at least a year ([growth model](#growth-model)).
+Every limit and the retention window are brain-wide database settings:
```bash
gbrain config set persistence.limits.principal_lifetime_ids 500000
@@ -869,9 +874,72 @@ Keys are `persistence.limits.<limit>` for `principal_outstanding`,
`brain_outstanding`, `principal_intent_bytes`, `brain_intent_bytes`,
`principal_lifetime_ids`, `brain_lifetime_ids`, `principal_terminal_bytes`,
`brain_terminal_bytes`, `brain_recovery_bytes` and `worktree_recovery_bytes`,
-each a nonnegative integer. `gbrain doctor` warns (`persistence_capacity`) once
-a principal or the brain uses 80% of its lifetime IDs or receipt bytes and
-prints the `gbrain config set` command with a value that covers about one more
-year at the current admission rate; a `queue_capacity` refusal carries the same
-command. Raising a cap is a mitigation: lifetime IDs remain permanent replay
-protection.
+each a nonnegative integer. `gbrain doctor` (`persistence_capacity`) forecasts
+each cumulative cap from the full last-7-day admission aggregate: it warns when
+a principal or the brain uses 80% of its lifetime IDs or receipt bytes or would
+run out within `persistence.capacity.warn_days` (30) days, and fails at 95% or
+within `persistence.capacity.fail_days` (7) days. Receipt bytes are forecast at
+their compacted (net) size once compaction can start; the finding's `basis`
+says which rate it used. It prints the `gbrain config set` command with a value
+that covers about one more year at that rate; `persistence_request_growth`
+uses the same threshold and value, and a `write_quota_exhausted` refusal
+carries the same command. Raising a cap is a mitigation: lifetime IDs remain
+permanent replay protection.
+
+<a id="growth-model"></a>
+### Growth model
+
+The defaults come from this model, sized for an autopilot brain that admits
+5,000 requests a day for 365 days. Configured values are never changed.
+
+- **Request IDs** are permanent, so they grow by the admission rate:
+ 5,000 × 365 = 1,825,000. The principal default is 2,000,000; the brain
+ default, 8,000,000, keeps the brain at four principals' worth.
+- **Receipt bytes** grow by two parts. Through the 30-day retention window a
+ receipt holds its reservation (up to 16,384 bytes; true-up returns most of
+ it when no effect is pending), and after compaction it keeps about 4,096
+ bytes (a compacted `put_page` measures about 3.9 KB). After a year at
+ 5,000 a day: 5,000 × 4,096 × 335 + 5,000 × 16,384 × 30 = 6,860,800,000 +
+ 2,457,600,000 = 9,318,400,000 bytes (8.7 GiB).
+- **Bulk days** (a reclone or a full sync) hold their reservations for the
+ window too. A 22,074-admission day reserves 22,074 × 16,384 =
+ 361,660,416 bytes; three in one window is about 1.0 GiB.
+- **Carried-in use**: a brain that already holds 74,982 receipts at
+ 1,228,424,148 bytes (16,383 bytes each, nothing compacted yet) adds 1.1 GiB.
+
+8.7 + 1.0 + 1.1 = 10.8 GiB, so the principal default is 16 GiB, which still
+covers the year if compacted receipts average 7 KB instead of 4 KB
+(5,000 × 7,168 × 335 + 2,457,600,000 = 14.5 GB, plus the same 2.1 GiB). The
+brain default is 64 GiB.
+
+For scale: the previous principal default of 1.5 GiB (1,610,612,736 bytes)
+left that brain 382,188,588 bytes, or 23,327 more admissions at 16,384 bytes:
+about 7 days at 3,308 a day and one day at 22,074. On the new defaults the
+same brain has (2,000,000 − 74,982) / 3,308 = 581 days of request IDs at its
+current rate, 385 at 5,000 a day.
+
+**Autopilot brains: check capacity on day one.** An autopilot brain admits
+far more requests than an interactive one. After its first day of runs:
+
+```bash
+gbrain doctor --only persistence_capacity,persistence_request_growth --json
+```
+
+**Say to your agent:** *"How many days of write capacity does my brain have left?"*
+
+<a id="quota-near-exhaustion"></a>
+### Quota near exhaustion
+
+When `persistence_capacity` warns or fails, or a write is refused with
+`write_quota_exhausted`:
+
+1. Read the finding: `gbrain doctor --only persistence_capacity --json`.
+ `details.resources[]` names the scope, resource, days left and `basis`;
+ `fix` is the reversible unblock.
+2. Run the `gbrain config set <key> <value>` it prints on the brain host
+ (undo with `gbrain config unset <key>`). Writes resume at once; retry the
+ refused write with the same `request_id`.
+3. Verify: `gbrain doctor --only persistence_capacity --json` reads `ok`.
+
+Raising a receipt-bytes cap is safe: the counter tracks bytes that are really
+stored, and compaction frees the window's reservations as receipts age out.
diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.ts
index 01358d1d4b..141f489e79 100644
--- a/src/commands/doctor/checks/persistence-capacity.ts
+++ b/src/commands/doctor/checks/persistence-capacity.ts
@@ -2,11 +2,19 @@ import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { capacityDiagnostics } from '../../../core/persistence/diagnostics.ts';
import { oneYearCapacity, readJournalLimits } from '../../../core/persistence/limits.ts';
+import { readCapacityForecast, type CapacityForecast } from '../../../core/persistence/capacity-forecast.ts';
+import { doctorVerify } from '../check-fix.ts';
+
+const VERIFY = 'gbrain doctor --only persistence_capacity --json';
+const DOCS = 'docs/guides/concurrent-writes.md#quota-near-exhaustion';
/**
- * #5470: warn at 80% of a cumulative managed-write cap (permanent request IDs,
- * receipt bytes) before admission refuses. Transient caps drain on their own.
- * Bounded: one indexed read per counter row (brain plus each principal).
+ * #5470/#6696 (A3): a cumulative managed-write cap (permanent request IDs,
+ * receipt bytes) is a warning when it is at 80% or would refuse admission
+ * within `persistence.capacity.warn_days` (30) at its 7-day rate, and a
+ * failure at 95% or within `persistence.capacity.fail_days` (7). The rate is
+ * the full 7-day aggregate (capacity-forecast.ts); receipt bytes forecast at
+ * their compacted (net) size. Each key gets the one value that covers a year.
*/
export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Check> {
try {
@@ -14,23 +22,43 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Che
terminal_bytes: string; recovery_bytes: string }>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,
terminal_bytes::text,recovery_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key`);
const limits = await readJournalLimits(engine);
- const near = capacityDiagnostics(counters, limits)
- .filter(row => row.approaching_capacity && (row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes'));
+ const forecast: CapacityForecast | null = await readCapacityForecast(engine, { limits }).catch(() => null);
+ const cumulative = capacityDiagnostics(counters, limits).filter(row => row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes');
const resources = [];
const needed = new Map<string, number>();
- for (const row of near) {
- const value = await oneYearCapacity(engine, row.scope, row.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', row.used, row.limit);
- resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key });
+ let worst: 'ok' | 'warn' | 'fail' = 'ok';
+ for (const row of cumulative) {
+ const predicted = forecast?.rows.find(f => f.scope === row.scope && f.resource === row.resource);
+ const status = predicted?.status ?? (row.approaching_capacity ? 'warn' : 'ok');
+ if (status === 'ok') continue;
+ if (status === 'fail' || worst === 'ok') worst = status;
+ // No admission inside the window: the latest admissions, however old, size the year instead.
+ const value = predicted && predicted.per_day_7d > 0 ? predicted.recommended_limit
+ : await oneYearCapacity(engine, row.scope, row.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', row.used, row.limit);
+ resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key, status,
+ ...(predicted ? { pct: predicted.pct, days_to_exhaustion: predicted.days_to_exhaustion, exhaustion_date: predicted.exhaustion_date, basis: predicted.basis,
+ per_day_7d: predicted.per_day_7d, ...(predicted.net_per_day_7d !== undefined ? { net_per_day_7d: predicted.net_per_day_7d } : {}),
+ ...(predicted.reclaimable_bytes !== undefined ? { reclaimable_bytes: predicted.reclaimable_bytes } : {}) } : {}) });
+ // Every principal shares one brain-wide key, so each key gets the largest value any scope needs.
needed.set(row.config_key, Math.max(needed.get(row.config_key) ?? 0, value));
}
- // Every principal shares one brain-wide key, so each key gets the largest value any scope needs.
const commands = [...needed].map(([key, value]) => `gbrain config set ${key} ${value}`);
- const details = { exact: true, inspected: counters.length, truncated: false, resources, commands };
- if (!resources.length) return { name: 'persistence_capacity', status: 'ok', message: 'Managed write capacity is below 80% of every cumulative limit.', details };
- return { name: 'persistence_capacity', status: 'warn', details,
- message: `${resources.length} managed write limit(s) at or above 80%: ${resources.map(r =>
- `${r.scope} ${r.resource} ${r.used}/${r.limit}`).join('; ')}. Admission refuses at the limit. Run on the brain host: ${commands.join('; ')} ` +
- '(each covers about one more year at the current admission rate). This is a mitigation: permanent request IDs are never evicted.' };
+ const details = { exact: true, inspected: counters.length, truncated: false, resources, commands, verify: VERIFY, docs: DOCS,
+ forecast: forecast ? { thresholds: forecast.thresholds, window_days: forecast.window_days, retention_days: forecast.retention_days,
+ table_bytes: forecast.table_bytes, rows: forecast.rows } : { health: 'unknown' } };
+ const thresholds = forecast?.thresholds;
+ if (!resources.length) return { name: 'persistence_capacity', status: 'ok', details,
+ message: thresholds ? `Managed write capacity is below ${thresholds.warn_pct}% of every cumulative limit and none runs out within ${thresholds.warn_days} days at its 7-day rate.`
+ : 'Managed write capacity is below 80% of every cumulative limit.' };
+ const [first] = [...needed];
+ return { name: 'persistence_capacity', status: worst, details,
+ fix: { argv: ['gbrain', 'config', 'set', first![0], String(first![1])], consent: [], actor: 'host_admin', requires_exclusive: false,
+ verify: doctorVerify('persistence_capacity'), docs: DOCS,
+ why: `Raises ${first![0]} to a value that covers about one more year at the 7-day rate; reversible with gbrain config unset.${commands.length > 1 ? ` Also run: ${commands.slice(1).join('; ')}.` : ''}` },
+ message: `${resources.length} managed write limit(s) near exhaustion: ${resources.map(r => `${r.scope} ${r.resource} ${r.used}/${r.limit}`
+ + ('days_to_exhaustion' in r && r.days_to_exhaustion !== null ? ` (about ${r.days_to_exhaustion} day(s) left at the 7-day rate, ${r.basis})` : '')).join('; ')}. `
+ + `Admission refuses at the limit. Run on the brain host: ${commands.join('; ')} (each covers about one more year at the current admission rate), `
+ + `then verify with ${VERIFY}. Permanent request IDs are never evicted.` };
} catch (error) {
return { name: 'persistence_capacity', status: 'warn',
message: `Managed write capacity could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 8c6fc73aa5..15d89dbed5 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -8,10 +8,10 @@ import { readPreparationPolicy } from '../../../core/persistence/switches.ts';
import { resolvePrepare, resolveSessionTimeouts } from '../../../core/db.ts';
import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
import { lostCallerWrites } from '../../../core/repair/failed-writes.ts';
+import { readCapacityForecast, readCapacityThresholds } from '../../../core/persistence/capacity-forecast.ts';
const WINDOW_DAYS = 7;
const SAMPLE = 10_000;
-const WARN_DAYS = 90;
const HORIZON_DAYS = 3650;
/**
@@ -46,8 +46,9 @@ export async function requestIndexesCheck(engine: BrainEngine): Promise<Check> {
* over the last 7 days (sampled from the newest 10,000 admissions per scope,
* one bounded index read each), lifetime request IDs against
* `persistence.limits.*`, and the projected days until admission refuses.
- * Warns when a scope would exhaust its lifetime IDs within 90 days, with the
- * same `gbrain config set` value `persistence_capacity` prints.
+ * Warns when a scope would exhaust its lifetime IDs within
+ * `persistence.capacity.warn_days` (30), the threshold `persistence_capacity`
+ * uses, with the same `gbrain config set` value it prints.
*/
export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
const docs = 'docs/guides/repair.md#request-growth';
@@ -58,6 +59,7 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
const counters = await engine.executeRaw<{ key: string; lifetime_ids: string }>(
"SELECT key,lifetime_ids::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key");
const limits = await readJournalLimits(engine);
+ const { warnDays } = await readCapacityThresholds(engine);
const now = Date.now();
const scopes = [];
for (const counter of counters) {
@@ -78,11 +80,14 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
days_to_exhaustion: daysLeft === null ? null : Math.floor(daysLeft),
exhaustion_date: daysLeft === null ? null : new Date(now + daysLeft * 86_400_000).toISOString().slice(0, 10) });
}
- const soon = scopes.filter(scope => scope.days_to_exhaustion !== null && scope.days_to_exhaustion < WARN_DAYS);
+ const soon = scopes.filter(scope => scope.days_to_exhaustion !== null && scope.days_to_exhaustion < warnDays);
// Every principal shares one brain-wide key, so each key gets the largest value any scope needs.
const needed = new Map<string, number>();
+ const forecast = soon.length ? await readCapacityForecast(engine, { limits }).catch(() => null) : null;
for (const scope of soon) {
- const value = await oneYearCapacity(engine, scope.scope, 'LifetimeIds', scope.lifetime_ids, scope.limit);
+ const predicted = forecast?.rows.find(row => row.scope === scope.scope && row.resource === 'lifetime_ids');
+ const value = predicted && predicted.per_day_7d > 0 ? predicted.recommended_limit
+ : await oneYearCapacity(engine, scope.scope, 'LifetimeIds', scope.lifetime_ids, scope.limit);
needed.set(scope.config_key, Math.max(needed.get(scope.config_key) ?? 0, value));
}
const commands = [...needed].map(([key, value]) => `gbrain config set ${key} ${value}`);
@@ -90,7 +95,7 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
commands, verify: 'gbrain doctor --json (check persistence_request_growth)', docs };
const rows = `${details.rows_exact ? '' : '~'}${details.rows} request row(s)`;
if (!soon.length) return { name: 'persistence_request_growth', status: 'ok', details,
- message: `${rows}; no scope exhausts its lifetime request IDs within ${WARN_DAYS} days at its last-${WINDOW_DAYS}-day rate.` };
+ message: `${rows}; no scope exhausts its lifetime request IDs within ${warnDays} days at its last-${WINDOW_DAYS}-day rate.` };
return { name: 'persistence_request_growth', status: 'warn', details,
message: `${rows}. ${soon.map(scope => `${scope.scope} admits ${scope.per_day}/day over the last ${scope.window_days} day(s) and reaches `
+ `${scope.config_key}=${scope.limit} (${scope.lifetime_ids} used) around ${scope.exhaustion_date}`).join('; ')}; admission refuses then. `
diff --git a/src/core/config.ts b/src/core/config.ts
index 003bc06ac9..0cffff542a 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1772,6 +1772,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts
'persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts', 'persistence.preparation_deadlines', // #6278: persistence/preparation-budget.ts, switches.ts
'persistence.publication_ceiling_ms', 'persistence.terminal_failures.window_days', 'persistence.terminal_failures.spike_factor', 'persistence.terminal_failures.spike_min', // #6405: persistence/sync-drain.ts (in-pass publication ceiling); #6650: persistence/terminal-failures.ts
+ 'persistence.capacity.warn_days', 'persistence.capacity.fail_days', 'persistence.capacity.background_pause_pct', // #6696: persistence/capacity-forecast.ts, admission-origin.ts
'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)
// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)
diff --git a/src/core/persistence/capacity-forecast.ts b/src/core/persistence/capacity-forecast.ts
new file mode 100644
index 0000000000..73a26b5a76
--- /dev/null
+++ b/src/core/persistence/capacity-forecast.ts
@@ -0,0 +1,177 @@
+/**
+ * #6696 (A3): days until a cumulative managed-write cap refuses admission,
+ * from a full 7-day aggregate of `persistence_requests` (and lifecycle
+ * receipts) on the `sequence` index, per scope (`brain`, each principal) and
+ * resource (`lifetime_ids`, `terminal_bytes`).
+ *
+ * Receipt bytes are reported gross (what the window's receipts reserve now)
+ * and net (what they keep once compacted). The counter grows by the gross
+ * rate until the oldest uncompacted receipt passes the retention window, and
+ * by the net rate after that, so `days_to_exhaustion` for terminal bytes uses
+ * net and `basis` says so. Rates are the larger of the window mean and the
+ * last 24 hours.
+ */
+import type { SqlEngine } from './model.ts';
+import { DEFAULT_JOURNAL_LIMITS, type JournalLimits } from './model.ts';
+import { DEFAULT_RECEIPT_RETENTION_DAYS, journalLimitKey, readJournalLimits, readReceiptRetentionDays, recommendedLimit } from './limits.ts';
+import { COMPACTED_HEADROOM_BYTES } from './receipt-bytes.ts';
+
+export const CAPACITY_WARN_DAYS_KEY = 'persistence.capacity.warn_days';
+export const CAPACITY_FAIL_DAYS_KEY = 'persistence.capacity.fail_days';
+export const DEFAULT_CAPACITY_WARN_DAYS = 30;
+export const DEFAULT_CAPACITY_FAIL_DAYS = 7;
+export const CAPACITY_WARN_PCT = 80;
+export const CAPACITY_FAIL_PCT = 95;
+const WINDOW_DAYS = 7;
+const HORIZON_DAYS = 3650;
+const SPIKE_FACTOR = 3;
+
+export type { CapacityResource } from './limits.ts';
+import type { CapacityResource } from './limits.ts';
+export interface CapacityForecastRow {
+ scope: string; resource: CapacityResource; used: number; limit: number; pct: number; config_key: string;
+ /** Window days actually observed (under 7 when the history is younger). */
+ window_days: number;
+ /** Ids admitted, or gross receipt bytes reserved, per day over the window. */
+ per_day_7d: number;
+ /** Terminal bytes only: the same receipts at their compacted size. */
+ net_per_day_7d?: number;
+ max_day_7d: number;
+ /** A single day over 3x the window mean (bulk sync, reclone). */
+ spike_day: string | null;
+ days_to_exhaustion: number | null;
+ exhaustion_date: string | null;
+ /** Terminal bytes only: slack a true-up or compaction would free now. */
+ reclaimable_bytes?: number;
+ basis: string;
+ /** A cap that covers one more year at this rate (never below double the current cap). */
+ recommended_limit: number;
+ status: 'ok' | 'warn' | 'fail';
+}
+export interface CapacityForecast {
+ rows: CapacityForecastRow[];
+ thresholds: { warn_days: number; fail_days: number; warn_pct: number; fail_pct: number };
+ retention_days: number;
+ table_bytes: number | null;
+ window_days: number;
+}
+
+interface Day { scope: string; day: string; ids: number; gross: number; net: number; recent_ids: number; recent_gross: number; recent_net: number }
+
+async function readDays(engine: SqlEngine, key: string, fallback: number): Promise<number> {
+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [key]);
+ const value = row ? Number(row.value) : fallback;
+ return Number.isFinite(value) && value >= 0 ? value : fallback;
+}
+
+/** First `sequence` inside the window: a binary search over the unique `sequence` index, never a scan of `created_at`. */
+async function windowStart(engine: SqlEngine, days: number): Promise<string | null> {
+ const [bounds] = await engine.executeRaw<{ lo: string | null; hi: string | null }>('SELECT min(sequence)::text AS lo,max(sequence)::text AS hi FROM persistence_requests');
+ if (!bounds?.lo || !bounds.hi) return null;
+ let lo = BigInt(bounds.lo), hi = BigInt(bounds.hi) + 1n;
+ while (lo < hi) {
+ const mid = (lo + hi) / 2n;
+ const [next] = await engine.executeRaw<{ sequence: string; inside: boolean }>(`SELECT sequence::text,created_at>now()-($2::double precision*interval '1 day') AS inside
+ FROM persistence_requests WHERE sequence>=$1::bigint ORDER BY sequence LIMIT 1`, [mid.toString(), days]);
+ if (!next || next.inside) hi = mid; else lo = BigInt(next.sequence) + 1n;
+ }
+ return lo.toString();
+}
+
+const NET_SQL = (r: string, e: string) => `LEAST(${r}.terminal_reservation,octet_length(${r}.authority::text)+COALESCE(octet_length(${r}.outcome::text),0)
+ +COALESCE(octet_length(${r}.error_detail::text),0)+COALESCE(octet_length(${r}.client_request_id),0)+COALESCE(${e}.bytes,0)+${COMPACTED_HEADROOM_BYTES})`;
+
+/** The configured days-to-exhaustion thresholds every capacity finding uses. */
+export async function readCapacityThresholds(engine: SqlEngine): Promise<{ warnDays: number; failDays: number }> {
+ const [warnDays, failDays] = await Promise.all([readDays(engine, CAPACITY_WARN_DAYS_KEY, DEFAULT_CAPACITY_WARN_DAYS), readDays(engine, CAPACITY_FAIL_DAYS_KEY, DEFAULT_CAPACITY_FAIL_DAYS)]);
+ return { warnDays, failDays };
+}
+
+export async function readCapacityForecast(engine: SqlEngine & { kind?: string }, opts: { limits?: JournalLimits } = {}): Promise<CapacityForecast> {
+ const limits = opts.limits ?? await readJournalLimits(engine);
+ const [{ warnDays, failDays }, retention] = await Promise.all([readCapacityThresholds(engine),
+ readReceiptRetentionDays(engine).catch(() => DEFAULT_RECEIPT_RETENTION_DAYS)]);
+ const counters = await engine.executeRaw<{ key: string; lifetime_ids: string; terminal_bytes: string }>(
+ "SELECT key,lifetime_ids::text,terminal_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key");
+ const start = await windowStart(engine, WINDOW_DAYS);
+ const days: Day[] = [];
+ if (start !== null) {
+ days.push(...(await engine.executeRaw<Record<string, string>>(`WITH w AS (SELECT * FROM persistence_requests
+ WHERE sequence>=$1::bigint AND created_at>now()-($2::double precision*interval '1 day')),
+ e AS (SELECT request_id,SUM(octet_length(data::text)+octet_length(kind)+1024) AS bytes FROM persistence_effects WHERE request_id IN (SELECT id FROM w) GROUP BY request_id)
+ SELECT 'principal:'||w.principal_kind||':'||w.principal_id AS scope,to_char(w.created_at AT TIME ZONE 'UTC','YYYY-MM-DD') AS day,
+ count(*)::text AS ids,COALESCE(SUM(w.terminal_reservation),0)::text AS gross,COALESCE(SUM(${NET_SQL('w', 'e')}),0)::text AS net,
+ count(*) FILTER (WHERE w.created_at>now()-interval '1 day')::text AS recent_ids,
+ COALESCE(SUM(w.terminal_reservation) FILTER (WHERE w.created_at>now()-interval '1 day'),0)::text AS recent_gross,
+ COALESCE(SUM(${NET_SQL('w', 'e')}) FILTER (WHERE w.created_at>now()-interval '1 day'),0)::text AS recent_net
+ FROM w LEFT JOIN e ON e.request_id=w.id GROUP BY 1,2`, [start, WINDOW_DAYS])).map(toDay));
+ }
+ days.push(...(await engine.executeRaw<Record<string, string>>(`SELECT 'principal:local_cli:'||principal_id::text AS scope,to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD') AS day,
+ count(*)::text AS ids,COALESCE(SUM(terminal_bytes),0)::text AS gross,COALESCE(SUM(terminal_bytes),0)::text AS net,
+ count(*) FILTER (WHERE created_at>now()-interval '1 day')::text AS recent_ids,
+ COALESCE(SUM(terminal_bytes) FILTER (WHERE created_at>now()-interval '1 day'),0)::text AS recent_gross,
+ COALESCE(SUM(terminal_bytes) FILTER (WHERE created_at>now()-interval '1 day'),0)::text AS recent_net
+ FROM persistence_topology_changes WHERE created_at>now()-($1::double precision*interval '1 day') GROUP BY 1,2`, [WINDOW_DAYS])).map(toDay));
+ const [history] = await engine.executeRaw<{ age_days: number | null; compaction_age_days: number | null }>(`SELECT
+ (SELECT EXTRACT(EPOCH FROM now()-created_at)/86400 FROM persistence_requests ORDER BY sequence LIMIT 1)::float8 AS age_days,
+ (SELECT EXTRACT(EPOCH FROM now()-min(completed_at))/86400 FROM persistence_requests
+ WHERE recovery IS NULL AND NOT compacted AND state IN ('committed','conflict','failed','cancelled'))::float8 AS compaction_age_days`);
+ const windowDays = Math.min(WINDOW_DAYS, Math.max(1, Number(history?.age_days ?? WINDOW_DAYS)));
+ // Days until the oldest uncompacted receipt is compactable: until then every receipt keeps its gross reservation.
+ const untilCompaction = Math.max(0, retention - Number(history?.compaction_age_days ?? 0));
+ const reclaim = await engine.executeRaw<{ scope: string; bytes: string }>(`WITH e AS (SELECT request_id,SUM(octet_length(data::text)+octet_length(kind)+1024) AS bytes,
+ bool_or(state<>'committed') AS unfinished FROM persistence_effects GROUP BY request_id)
+ SELECT 'principal:'||r.principal_kind||':'||r.principal_id AS scope,COALESCE(SUM(r.terminal_reservation-${NET_SQL('r', 'e')}),0)::text AS bytes
+ FROM persistence_requests r LEFT JOIN e ON e.request_id=r.id
+ WHERE r.state IN ('committed','conflict','failed','cancelled') AND r.recovery IS NULL AND NOT COALESCE(e.unfinished,false) GROUP BY 1`);
+ const tableBytes = await engine.executeRaw<{ bytes: string }>("SELECT pg_total_relation_size('persistence_requests')::text AS bytes").then(r => Number(r[0]?.bytes), () => null);
+ const now = Date.now();
+ const rows: CapacityForecastRow[] = [];
+ for (const counter of counters) {
+ const scopeDays = counter.key === 'brain' ? days : days.filter(day => day.scope === counter.key);
+ const byDay = new Map<string, Day>();
+ for (const day of scopeDays) {
+ const sum = byDay.get(day.day) ?? { ...day, ids: 0, gross: 0, net: 0, recent_ids: 0, recent_gross: 0, recent_net: 0 };
+ for (const field of ['ids', 'gross', 'net', 'recent_ids', 'recent_gross', 'recent_net'] as const) sum[field] += day[field];
+ byDay.set(day.day, sum);
+ }
+ const total = (field: keyof Omit<Day, 'scope' | 'day'>) => [...byDay.values()].reduce((n, day) => n + day[field], 0);
+ const prefix = counter.key === 'brain' ? 'brain' : 'principal';
+ const reclaimable = counter.key === 'brain' ? reclaim.reduce((n, row) => n + Number(row.bytes), 0) : Number(reclaim.find(row => row.scope === counter.key)?.bytes ?? 0);
+ for (const resource of ['lifetime_ids', 'terminal_bytes'] as const) {
+ const setting = `${prefix}${resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes'}` as keyof JournalLimits;
+ const limit = limits[setting] ?? DEFAULT_JOURNAL_LIMITS[setting];
+ const used = Number(counter[resource]);
+ const ids = resource === 'lifetime_ids';
+ const perDay = Math.max(total(ids ? 'ids' : 'gross') / windowDays, total(ids ? 'recent_ids' : 'recent_gross'));
+ const netPerDay = ids ? perDay : Math.max(total('net') / windowDays, total('recent_net'));
+ const maxDay = Math.max(0, ...[...byDay.values()].map(day => ids ? day.ids : day.gross));
+ const mean = total(ids ? 'ids' : 'gross') / windowDays;
+ const spike = [...byDay.values()].find(day => mean > 0 && (ids ? day.ids : day.gross) > SPIKE_FACTOR * mean)?.day ?? null;
+ const remaining = Math.max(0, limit - used);
+ let daysLeft: number | null;
+ let basis = `aggregate_${Number(windowDays.toFixed(2))}d${windowDays < WINDOW_DAYS ? '_short_history' : ''}`;
+ if (ids) daysLeft = perDay > 0 ? remaining / perDay : null;
+ else if (perDay <= 0) daysLeft = null;
+ else if (remaining <= perDay * untilCompaction) { daysLeft = remaining / perDay; basis += ':gross_before_compaction'; }
+ else { daysLeft = netPerDay > 0 ? untilCompaction + (remaining - perDay * untilCompaction) / netPerDay : null; basis += untilCompaction > 0 ? ':gross_then_net' : ':net_after_compaction'; }
+ if (daysLeft !== null && daysLeft > HORIZON_DAYS) daysLeft = null;
+ const pct = limit > 0 ? Math.round(used / limit * 1000) / 10 : used > 0 ? 100 : 0;
+ const status = pct >= CAPACITY_FAIL_PCT || daysLeft !== null && daysLeft < failDays ? 'fail'
+ : pct >= CAPACITY_WARN_PCT || daysLeft !== null && daysLeft < warnDays ? 'warn' : 'ok';
+ rows.push({ scope: counter.key, resource, used, limit, pct, config_key: journalLimitKey(setting), window_days: Number(windowDays.toFixed(2)),
+ per_day_7d: Math.round(perDay), ...(ids ? {} : { net_per_day_7d: Math.round(netPerDay), reclaimable_bytes: reclaimable }),
+ max_day_7d: maxDay, spike_day: spike,
+ days_to_exhaustion: daysLeft === null ? null : Math.floor(daysLeft),
+ exhaustion_date: daysLeft === null ? null : new Date(now + daysLeft * 86_400_000).toISOString().slice(0, 10),
+ basis, recommended_limit: recommendedLimit(resource, used, limit, { perDay, netPerDay }, retention), status });
+ }
+ }
+ return { rows, thresholds: { warn_days: warnDays, fail_days: failDays, warn_pct: CAPACITY_WARN_PCT, fail_pct: CAPACITY_FAIL_PCT },
+ retention_days: retention, table_bytes: Number.isFinite(tableBytes) ? tableBytes : null, window_days: Number(windowDays.toFixed(2)) };
+}
+
+function toDay(row: Record<string, string>): Day {
+ return { scope: row.scope!, day: row.day!, ids: Number(row.ids), gross: Number(row.gross), net: Number(row.net),
+ recent_ids: Number(row.recent_ids), recent_gross: Number(row.recent_gross), recent_net: Number(row.recent_net) };
+}
diff --git a/src/core/persistence/limits.ts b/src/core/persistence/limits.ts
index d3bc03910e..1ee31cc4a2 100644
--- a/src/core/persistence/limits.ts
+++ b/src/core/persistence/limits.ts
@@ -1,5 +1,9 @@
import { opError } from '../ops/contract.ts';
import { DEFAULT_JOURNAL_LIMITS, type JournalLimits, type SqlEngine } from './model.ts';
+import { COMPACTED_HEADROOM_BYTES, RECEIPT_RESERVATION_FLOOR } from './receipt-bytes.ts';
+
+/** Fallback compacted receipt size when no receipt is sampled; a compacted put_page measures about 3.9 KB. */
+const RETAINED_RECEIPT_BYTES = 4096;
export const RECEIPT_RETENTION_KEY = 'persistence.receipt_retention_days';
export const DEFAULT_RECEIPT_RETENTION_DAYS = 30;
@@ -35,23 +39,34 @@ export async function readReceiptRetentionDays(engine:SqlEngine):Promise<number>
const [row]=await engine.executeRaw<{value:string}>('SELECT value FROM config WHERE key=$1',[RECEIPT_RETENTION_KEY]);
return row ? parseJournalConfigValue(RECEIPT_RETENTION_KEY,row.value) : DEFAULT_RECEIPT_RETENTION_DAYS;
}
-/** Permanent accounting a compacted receipt keeps (authority, outcome, effects); measured ~3.9 KB for put_page. */
-const RETAINED_RECEIPT_BYTES = 4096;
-const RESERVED_RECEIPT_BYTES = 16_384;
+export type CapacityResource = 'lifetime_ids' | 'terminal_bytes';
+/** The cap that covers one more year: ids at the id rate; bytes at the net rate plus the retention window held at the gross rate. */
+export function recommendedLimit(resource: CapacityResource, used: number, limit: number, rate: { perDay: number; netPerDay?: number }, retentionDays: number): number {
+ const needed = resource === 'lifetime_ids' ? used + rate.perDay * 365
+ : used + (rate.netPerDay ?? rate.perDay) * 365 + Math.max(0, rate.perDay - (rate.netPerDay ?? rate.perDay)) * retentionDays;
+ const value = Math.max(Math.ceil(needed), 2 * limit, 1);
+ return resource === 'terminal_bytes' ? Math.ceil(value / 1024 ** 2) * 1024 ** 2 : value;
+}
+
/**
* A cumulative cap value that covers one more year at the scope's recent
* admission rate (sampled from its latest 1,000 admissions), never less than
- * double the current cap.
+ * double the current cap. Receipt bytes use the sample's measured
+ * reservations: what its receipts reserve now while the retention window
+ * holds them, and their compacted size after (capacity-forecast.ts
+ * `recommendedLimit`, the formula doctor uses too).
*/
export async function oneYearCapacity(engine:SqlEngine,scope:string,setting:'LifetimeIds'|'TerminalBytes',used:number,limit:number):Promise<number> {
const principal=/^principal:([^:]+):(.+)$/.exec(scope);
- const [sample]=await engine.executeRaw<{admissions:number;age_seconds:number|null}>(`SELECT count(*)::int AS admissions,
- EXTRACT(EPOCH FROM (now()-min(created_at)))::float8 AS age_seconds FROM (SELECT created_at FROM persistence_requests
+ const [sample]=await engine.executeRaw<{admissions:number;age_seconds:number|null;gross:number|null;net:number|null}>(`SELECT count(*)::int AS admissions,
+ EXTRACT(EPOCH FROM (now()-min(created_at)))::float8 AS age_seconds,avg(terminal_reservation)::float8 AS gross,
+ avg(LEAST(terminal_reservation,octet_length(authority::text)+COALESCE(octet_length(outcome::text),0)+COALESCE(octet_length(error_detail::text),0)+${COMPACTED_HEADROOM_BYTES}))::float8 AS net
+ FROM (SELECT created_at,terminal_reservation,authority,outcome,error_detail FROM persistence_requests
${principal ? 'WHERE principal_kind=$1 AND principal_id=$2' : ''} ORDER BY sequence DESC LIMIT 1000) recent`,
principal ? [principal[1],principal[2]] : []);
const perDay=sample.admissions/Math.max(1/24,(sample.age_seconds ?? 0)/86_400);
const retention=await readReceiptRetentionDays(engine).catch(()=>DEFAULT_RECEIPT_RETENTION_DAYS);
- const needed=setting==='LifetimeIds' ? used+perDay*365 : used+perDay*(365*RETAINED_RECEIPT_BYTES+retention*RESERVED_RECEIPT_BYTES);
- const value=Math.max(Math.ceil(needed),2*limit,1);
- return setting==='TerminalBytes' ? Math.ceil(value/1024**2)*1024**2 : value;
+ const measured=(value:number|null|undefined,fallback:number)=>Number.isFinite(Number(value)) && Number(value)>0 ? Number(value) : fallback;
+ return setting==='LifetimeIds' ? recommendedLimit('lifetime_ids',used,limit,{perDay},retention)
+ : recommendedLimit('terminal_bytes',used,limit,{perDay:perDay*measured(sample.gross,RECEIPT_RESERVATION_FLOOR),netPerDay:perDay*measured(sample.net,RETAINED_RECEIPT_BYTES)},retention);
}
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index 2b50f73877..ef8ec6080e 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -118,8 +118,9 @@ export interface JournalLimits {
export const DEFAULT_JOURNAL_LIMITS: Readonly<JournalLimits> = Object.freeze({
principalOutstanding: 100, brainOutstanding: 1000,
principalIntentBytes: 32 * 1024 ** 2, brainIntentBytes: 256 * 1024 ** 2,
- principalLifetimeIds: 250_000, brainLifetimeIds: 1_000_000,
- principalTerminalBytes: 1536 * 1024 ** 2, brainTerminalBytes: 8 * 1024 ** 3,
+ // #6696 (A2): sized for 5,000 admissions a day for a year (docs/guides/concurrent-writes.md#growth-model).
+ principalLifetimeIds: 2_000_000, brainLifetimeIds: 8_000_000,
+ principalTerminalBytes: 16 * 1024 ** 3, brainTerminalBytes: 64 * 1024 ** 3,
brainRecoveryBytes: 1024 ** 3, worktreeRecoveryBytes: 256 * 1024 ** 2,
});
export type SqlEngine = Pick<BrainEngine, 'executeRaw'>;
diff --git a/src/core/persistence/receipt-bytes.ts b/src/core/persistence/receipt-bytes.ts
index 374ed04866..266ede6625 100644
--- a/src/core/persistence/receipt-bytes.ts
+++ b/src/core/persistence/receipt-bytes.ts
@@ -2,8 +2,10 @@ import { jsonBytes } from './digest.ts';
/** The smallest terminal reservation an admission takes; the receipt is sized down at commit (true-up). */
export const RECEIPT_RESERVATION_FLOOR = 16_384;
-/** Slack every trued-up receipt keeps for later bookkeeping on the row (effect re-arms, redaction markers). */
+/** Slack a trued-up receipt keeps while it can still change (effect re-arms, redaction markers). */
export const RECEIPT_HEADROOM_BYTES = 4096;
+/** Slack a compacted receipt keeps: the 1 KiB compaction always kept (a compacted put_page measures about 3.9 KB). */
+export const COMPACTED_HEADROOM_BYTES = 1024;
/** Bumped when the retained-bytes formula changes; `receipt-true-up` previews bind it. */
export const RECEIPT_FORMULA_VERSION = 1;
/** Bytes one effect row holds on its receipt; the SQL twin of `effectBytes`. */
@@ -29,13 +31,13 @@ export interface ReceiptBytesFields {
* `terminal` it counts the intent, authority, outcome, error message, error
* detail, client request id and `effects` (already summed with
* `EFFECT_BYTES_SQL`), plus `RECEIPT_HEADROOM_BYTES`; at `compacted` the
- * intent and error message are gone.
+ * intent and error message are gone and the slack is `COMPACTED_HEADROOM_BYTES`.
*/
export function retainedReceiptBytes(row: ReceiptBytesFields, opts: { stage: 'terminal' | 'compacted'; effects?: number }): number {
const json = (value: unknown) => value === null || value === undefined ? 0 : jsonBytes(value);
const kept = json(row.authority) + json(row.outcome) + json(row.error_detail) + Buffer.byteLength(row.client_request_id ?? '');
const dropped = opts.stage === 'terminal' ? json(row.intent) + Buffer.byteLength(row.error_message ?? '') : 0;
- return kept + dropped + (opts.effects ?? 0) + RECEIPT_HEADROOM_BYTES;
+ return kept + dropped + (opts.effects ?? 0) + (opts.stage === 'terminal' ? RECEIPT_HEADROOM_BYTES : COMPACTED_HEADROOM_BYTES);
}
/** Config row counting true-up decrements clamped at a counter below the delta (counter drift); doctor reports it. */
diff --git a/test/helpers/w5-scenarios.ts b/test/helpers/w5-scenarios.ts
index e54bef57ef..b1f82604fe 100644
--- a/test/helpers/w5-scenarios.ts
+++ b/test/helpers/w5-scenarios.ts
@@ -173,6 +173,8 @@ export async function compactionSkipsUnfinishedReceipts(databaseUrl?: string) {
export async function capacityWarnsAndRefusalNamesTheKey(databaseUrl?: string) {
await managedBrain(async ({ engine, ctx }) => {
expect(await checkPersistenceCapacity(engine)).toMatchObject({ status: 'ok', details: { exact: true, truncated: false } });
+ // The percentage line alone: the days-to-exhaustion thresholds (#6696) are off for this scenario.
+ await engine.setConfig('persistence.capacity.warn_days', '0'); await engine.setConfig('persistence.capacity.fail_days', '0');
for (let i = 0; i < 8; i++) await put(ctx, `notes/cap-${i}`, `Cap ${i}.`);
await engine.setConfig('persistence.limits.principal_outstanding', '10');
expect((await checkPersistenceCapacity(engine)).status).toBe('ok');
diff --git a/test/persistence-capacity-forecast.test.ts b/test/persistence-capacity-forecast.test.ts
new file mode 100644
index 0000000000..af8f040d43
--- /dev/null
+++ b/test/persistence-capacity-forecast.test.ts
@@ -0,0 +1,93 @@
+/**
+ * #6696 (A3): the capacity check reads days-to-exhaustion from a full 7-day
+ * aggregate, so a cap at 76% that the current rate fills within 30 days
+ * warns (it read ok at the old 80% line); a burst followed by idle days still
+ * counts and is flagged; a history younger than 7 days divides by its age.
+ * Both backends.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { checkPersistenceCapacity } from '../src/commands/doctor/checks/persistence-capacity.ts';
+import { readCapacityForecast } from '../src/core/persistence/capacity-forecast.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+/** 70 admissions (plus one 8 days old unless `history` is false), in time order, the i-th newest created `ageDays(i)` days ago, against a principal id cap of 1,000 with 760 already used. */
+async function seed(engine: BrainEngine, ageDays: (i: number) => number, history = true) {
+ const requests = await requestFixture(engine);
+ const ids: string[] = [];
+ const ages: number[] = [];
+ // An admission older than the window, so the history spans the full seven days.
+ if (history) { ids.push((await requests.admit('old')).id); ages.push(8); }
+ for (let i = 0; i < 70; i++) { ids.push((await requests.admit(`p${i}`)).id); ages.push(ageDays(69 - i)); }
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw(`UPDATE persistence_requests r SET created_at=now()-(t.age*interval '1 day') FROM unnest($1::uuid[],$2::float8[]) AS t(id,age) WHERE r.id=t.id`,
+ [ids, ages]);
+ await tx.executeRaw("UPDATE persistence_counters SET lifetime_ids=760 WHERE key LIKE 'principal:%'");
+ });
+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');
+}
+const principalIds = async (engine: BrainEngine) => (await readCapacityForecast(engine)).rows.find(r => r.scope.startsWith('principal:') && r.resource === 'lifetime_ids')!;
+
+for (const kind of testBackends()) {
+ describe(`capacity forecast ${kind}`, () => {
+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;
+ let scratch: string;
+ beforeAll(async () => {
+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-forecast-'));
+ factory = await freshBrainFactory(kind, databaseUrl);
+ }, 120_000);
+ afterAll(async () => {
+ await factory?.dispose();
+ if (scratch) rmSync(scratch, { recursive: true, force: true });
+ });
+ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {
+ const engine = await factory.fresh();
+ await withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => fn(engine));
+ }, 120_000);
+
+ check('76% used at a 10/day burn warns with days to exhaustion and the one-year command', async engine => {
+ await seed(engine, i => i * 0.1 + 0.05);
+ const row = await principalIds(engine);
+ expect(row).toMatchObject({ used: 760, limit: 1000, pct: 76, status: 'warn', spike_day: null });
+ expect(row.per_day_7d).toBe(10);
+ expect(row.days_to_exhaustion).toBe(24);
+ expect(row.basis).toBe('aggregate_7d');
+ const doctor = await checkPersistenceCapacity(engine);
+ expect(doctor.status).toBe('warn');
+ expect(doctor.message).toContain('about 24 day(s) left at the 7-day rate');
+ expect((doctor.details as { commands: string[] }).commands).toEqual([`gbrain config set persistence.limits.principal_lifetime_ids ${760 + 10 * 365}`]);
+ expect(doctor.fix).toMatchObject({ argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', String(760 + 10 * 365)], actor: 'host_admin' });
+ });
+
+ check('a burst followed by idle days still counts toward the rate and is flagged as a spike', async engine => {
+ await seed(engine, i => i === 0 ? 6.9 : 3 + i * 0.0001);
+ const row = await principalIds(engine);
+ expect(row.spike_day).not.toBeNull();
+ expect(row.per_day_7d).toBe(10);
+ expect(row.status).toBe('warn');
+ });
+
+ check('a history younger than seven days divides by its age, not by seven', async engine => {
+ await seed(engine, i => i * 0.0285, false);
+ const row = await principalIds(engine);
+ expect(row.window_days).toBeCloseTo(1.97, 1);
+ expect(row.basis).toStartWith('aggregate_1.9');
+ expect(row.basis).toEndWith('d_short_history');
+ expect(row.status).toBe('fail');
+ expect((await checkPersistenceCapacity(engine)).status).toBe('fail');
+ });
+
+ check('a quiet brain far from its caps is ok', async engine => {
+ await requestFixture(engine).then(r => r.admit('one'));
+ expect((await checkPersistenceCapacity(engine)).status).toBe('ok');
+ });
+ });
+}
diff --git a/test/persistence-capacity.test.ts b/test/persistence-capacity.test.ts
index 68db0d11a5..13329f632b 100644
--- a/test/persistence-capacity.test.ts
+++ b/test/persistence-capacity.test.ts
@@ -24,6 +24,17 @@ test('cumulative principal and brain defaults carry 600 admissions a day for at
expect(bytesDays(DEFAULT_JOURNAL_LIMITS.brainTerminalBytes)).toBeGreaterThanOrEqual(365);
});
+test('#6696 defaults carry an autopilot brain at 5,000 admissions a day for a year on ids and receipt bytes', () => {
+ // The growth model in docs/guides/concurrent-writes.md#growth-model: every receipt reserves 16 KiB through the
+ // 30-day window and keeps 4 KiB once compacted (measured 3.9 KB per compacted put_page).
+ const perDay = 5000, windowDays = 30, reserved = 16_384, retained = 4096;
+ const bytesDays = (limit: number) => windowDays + (limit - perDay * windowDays * reserved) / (perDay * retained);
+ expect(DEFAULT_JOURNAL_LIMITS.principalLifetimeIds).toBeGreaterThanOrEqual(2_000_000);
+ expect(DEFAULT_JOURNAL_LIMITS.brainLifetimeIds).toBeGreaterThanOrEqual(DEFAULT_JOURNAL_LIMITS.principalLifetimeIds);
+ expect(DEFAULT_JOURNAL_LIMITS.principalLifetimeIds / perDay).toBeGreaterThanOrEqual(365);
+ expect(bytesDays(DEFAULT_JOURNAL_LIMITS.principalTerminalBytes)).toBeGreaterThanOrEqual(365);
+ expect(DEFAULT_JOURNAL_LIMITS.brainTerminalBytes).toBeGreaterThanOrEqual(DEFAULT_JOURNAL_LIMITS.principalTerminalBytes);
+});
test('configured retention compacts receipts past a backlog of unfinished effects', () => compactionSkipsUnfinishedReceipts(), 180_000);
test('doctor warns at 80% of a cumulative cap and the refusal names the key and a value', () => capacityWarnsAndRefusalNamesTheKey(), 120_000);