Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

A write carrying write_capacity_low says it was saved; one-year value uses the 7-day mean (GST-2107)

garrytan1cc350aebc89
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cadb056cf..6f0576dc1a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A write that saved now says so when it carries a low-capacity warning, and the warning no longer asks the user to raise a write cap by tens of gigabytes.** When a cumulative write cap (receipt bytes or request ids) was at 80% or forecast to run out within 30 days, every write receipt's `write_capacity_low` notice ended with `actor: host_admin` and `next: tell_user_to_run: gbrain config set persistence.limits.principal_terminal_bytes <value>`. An agent that read only the end of a successful `remember` took that for a refusal and told its user the memory was not saved. The value was also oversized: it projected the last 24 hours for a whole year, so one bulk sync day could recommend several times the current cap. The notice now opens with "This write was saved and writes still work", its fix is the read-only `gbrain doctor --only persistence_capacity --json`, and the one-more-year value uses the 7-day mean rate. Days-to-exhaustion warnings still react to a bulk day. Doctor's finding keeps the `gbrain config set` command for the brain host's operator.
+
+### Itemized changes
+
+- `src/core/persistence/capacity-snapshot.ts`: `write_capacity_low` says the write was saved and names doctor's read-only check (actor `agent`) as its fix, with no cap raise in the notice.
+- `src/core/persistence/capacity-forecast.ts`: `recommended_limit` (doctor `persistence_capacity`, the notice snapshot, `gbrain sync status` and `/metrics`) covers one more year at the 7-day mean gross and net rates instead of the larger of the mean and the last 24 hours.
+- Docs: `docs/guides/write-refusals.md` (`write_capacity_low` row), `docs/guides/concurrent-writes.md` (the notice, the mean-rate value, and returning a raised `persistence.receipt_retention_days` to the default before raising a cap), `docs/guides/repair.md` (unset the 90-day retention once a failed-writes recovery is done), `docs/architecture/key-files/core-persistence-capacity.md`.
+- Tests: `test/persistence-capacity-notices.test.ts` (the notice's fix and wording; a burst of 28 admissions in the last day over a 10-a-day week recommends the mean-rate value, ids exactly and receipt bytes under the mean-rate ceiling).
+
## [0.60.620.0] - 2026-11-09
**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.
diff --git a/docs/architecture/key-files/core-persistence-capacity.md b/docs/architecture/key-files/core-persistence-capacity.md
index abafb6ce9e..b1e7effefe 100644
--- a/docs/architecture/key-files/core-persistence-capacity.md
+++ b/docs/architecture/key-files/core-persistence-capacity.md
@@ -6,9 +6,9 @@ Cumulative write caps (permanent request ids, receipt bytes) and the paths that
- `src/core/persistence/receipt-true-up.ts` — `trueUpRequests(engine, ids)`: after the settling transaction commits, in its own short transaction, locks the brain and principal counters in key order, then a compare-and-set on each request row (still `terminal_reservation` as read, no queued or running effect, same effect bytes) shrinks it to `retainedReceiptBytes` and releases the difference. Idempotent; never touches `updated_at`. Called from the effect runner (`effects.ts`, every claimed request), `embedding-settlement.ts`, `embedding-noop-settle.ts` (the `embed --stale` bulk settle), `effect-retry.ts` (reconciled) and `backup/snapshot.ts` (restore). `test/persistence-true-up-sites.test.ts` fails on an effect state-change site that is not wired. `sweepCompactedReservations` is the bounded one-shot pass over receipts compacted with their full reservation (cursor `persistence.true_up.compacted_through`, `done` at the end).
- `src/core/persistence/admission-origin.ts` — `withAdmissionOrigin('interactive' | 'background')` (an outer background scope wins), `resolveAdmissionOrigin` (unset reads background, never derived from `ctx.remote`), `persistence.capacity.background_pause_pct` (default 80) and `backgroundPaused`, the `write_capacity_backpressure` refusal background producers get past the line. A background scope also carries the per-run owner cache (`backgroundOwnerCheck`); `backgroundWorktreeInactive` (a `recovering` worktree, read under the admission's lock in `journal.ts`) and `backgroundOwnerUnverified` refuse `owner_unavailable` pre-receipt with the owner-status fix; a draining worktree still admits.
- `src/core/persistence/owner-verification.ts` — #6741 C: the claim's owner verification (`verifyOwnerRoot`: paths recorded, physical root, marker and reservation intact; a device-only change is `restampable`), shared by writer onboarding and background admissions; `assertBackgroundOwner` refuses a background admission `owner_unavailable` once per source per run (cache: admission-origin.ts `backgroundOwnerCheck`). Tests: `test/background-owner-verification.test.ts`.
-- `src/core/persistence/capacity-forecast.ts` — `readCapacityForecast`: per principal, one statement walks `persistence_requests_principal` newest first until `created_at` leaves the 7-day window and buckets by day; gross and net (compacted) receipt rates, `days_to_exhaustion`, `basis` (`:legacy_under_reserved` while receipts admitted before the intent-sized reservation remain), `recommended_limit`. `light` skips the reclaim read and table size. Thresholds `persistence.capacity.warn_days` (30) and `fail_days` (7).
+- `src/core/persistence/capacity-forecast.ts` — `readCapacityForecast`: per principal, one statement walks `persistence_requests_principal` newest first until `created_at` leaves the 7-day window and buckets by day; gross and net (compacted) receipt rates, `days_to_exhaustion` (at the larger of the 7-day mean and the last 24 hours), `basis` (`:legacy_under_reserved` while receipts admitted before the intent-sized reservation remain), `recommended_limit` (one more year at the 7-day mean, GST-2107, so one bulk day is not projected for a year). `light` skips the reclaim read and table size. Thresholds `persistence.capacity.warn_days` (30) and `fail_days` (7).
- `src/core/engine-key.ts` + `src/core/engine-root.ts` — the key every per-engine cache uses. `engineKey(engine)` returns the engine itself through the `ENGINE_ROOT` symbol (each engine stores itself there; a page-transaction clone inherits it, forwarding proxies and a recovered degraded engine return it), and otherwise walks a page-transaction clone, a read-through view or a statement-deadline wrapper (`engineCacheKey`) to the engine behind it. A process with mounted brains keeps one entry per brain in the search telemetry writer (`getTelemetryWriter(engine)`), `search.track_retrieval`, minion admission policy, `mcp.strict_params` last-known-good, publication ceiling, `write_capacity_low` throttle, `search.hnsw_iterative_scan` and `search.vector_legacy_guard`, and a transaction or view shares its engine's entry. A one-brain process behaves as before. Test: `test/engine-keyed-caches.test.ts`.
-- `src/core/persistence/capacity-snapshot.ts` — `cachedCapacitySnapshot`: one light forecast per engine per 60 s, shared by every caller; `capacityNotices` builds `write_capacity_low` (kind `info`, muteable; hourly per engine and scope on write and sync receipts, `scopes` limits a remote caller to the brain and its own principal) and `write_capacity_backpressure` (once per pause start). Read by `mcp/dispatch.ts`, `cli/main.ts`, `commands/sync/{run,operator}.ts`, `cycle.ts` and the admin `/metrics` gauges in `serve-http-metrics.ts`. #6803: the cache keys on the real engine (`engineCacheKey`), the shared fetch is bounded at `CAPACITY_FETCH_BOUND_MS` (10 s) and a timed-out fetch is never cached; `capacitySnapshotWithin` (sync status, write and sync receipts: `CAPACITY_READ_WAIT_MS`, 1.5 s) returns `unknown` for that call alone, and `capacityNotices` on an unknown snapshot returns no notice and leaves throttle and pause state as it was. Test: `test/capacity-bounded-read-6803.test.ts`.
+- `src/core/persistence/capacity-snapshot.ts` — `cachedCapacitySnapshot`: one light forecast per engine per 60 s, shared by every caller; `capacityNotices` builds `write_capacity_low` (kind `info`, muteable; it says the write was saved and its fix is the read-only doctor check, GST-2107; hourly per engine and scope on write and sync receipts, `scopes` limits a remote caller to the brain and its own principal) and `write_capacity_backpressure` (once per pause start). Read by `mcp/dispatch.ts`, `cli/main.ts`, `commands/sync/{run,operator}.ts`, `cycle.ts` and the admin `/metrics` gauges in `serve-http-metrics.ts`. #6803: the cache keys on the real engine (`engineCacheKey`), the shared fetch is bounded at `CAPACITY_FETCH_BOUND_MS` (10 s) and a timed-out fetch is never cached; `capacitySnapshotWithin` (sync status, write and sync receipts: `CAPACITY_READ_WAIT_MS`, 1.5 s) returns `unknown` for that call alone, and `capacityNotices` on an unknown snapshot returns no notice and leaves throttle and pause state as it was. Test: `test/capacity-bounded-read-6803.test.ts`.
- `src/core/persistence/compaction-pass.ts` — `runCompactionPass`, the consumer's idle and volume maintenance: `compactWriteReceiptsDetailed`, one sweep step, and the `persistence.maintenance.last_compaction` record (`at`, `host_id`, `compacted`, `freed_bytes`, `skipped_by_reason`). Each step resumes from the timer queue (`journal.ts` `yieldToEventLoop`), as do the consumer's maintenance chain, the per-table queue `VACUUM` and the effects drain passes (`NOOP_SETTLE_BATCH` 50), so on PGLite a request waits behind one step at most. `journal.ts` `compactReceipt` compacts one receipt in its own transaction (counters first, `lock_timeout` 2 s, `statement_timeout` 15 s) and skips open managed-sync runs (`OPEN_SYNC_CURSOR_EXCLUSION`) and the newest sync receipt per worktree (`newestSyncReceipt`).
- `src/core/repair/receipt-compaction.ts` — `gbrain repair receipt-compaction`: explicit-only, preview-bound, destructive consent, `publication: 'projection'`; `--older-than` (the `pages purge-deleted` grammar) floored at the configured retention unless `--force`, committed only unless `--include-failures`; the approved set binds an absolute cutoff and the newest sequence. Test: `test/repair-receipt-compaction.test.ts`.
- `src/core/persistence/refusal-breaker.ts` — `assertRefusalBreakerClosed`: `submitMaintenance` refuses before admission after `persistence.maintenance.refusal_breaker_threshold` (3; 0 off) same-code terminal refusals in 24 h for the same request `digest` (source, slug, intent with its revision and planner); `listSuppressedWrites` feeds doctor `maintenance_write_drift`. The ghost case (`canonical_file_missing`, tagged by `page-prepare.ts`, kept in `error_detail.origin`, returned by `liveFileDrift`) refuses before admission in `prepared-maintenance.ts`. Test: `test/maintenance-ghost-breaker-6696.test.ts`.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 3afe88c9e0..e370035b4a 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -914,7 +914,8 @@ 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`
+that covers about one more year at the window's mean rate (a bulk day in the
+last 24 hours shortens the days left, but is not projected for a year); `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.
@@ -1005,11 +1006,18 @@ When `persistence_capacity` warns or fails, or a write is refused with
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.
+Check `persistence.receipt_retention_days` first: a window raised for a
+recovery holds every receipt's reservation that much longer and multiplies the
+window part of the recommended value, so `gbrain config unset
+persistence.receipt_retention_days` (back to 30 days) is the smaller step once
+the recovery is done.
**Warnings before the wall.** A cap at or past 80%, or one that runs out
within `persistence.capacity.warn_days` (default 30), adds the
-`[gbrain notice write_capacity_low]` notice (kind `info`) with the same
-`gbrain config set` command. Write and sync receipts carry it at most once an
+`[gbrain notice write_capacity_low]` notice (kind `info`). It rides a write
+that succeeded, so it opens with "This write was saved" and its fix is the
+read-only `gbrain doctor --only persistence_capacity --json`; the
+`gbrain config set` command stays in doctor's finding for the brain host. Write and sync receipts carry it at most once an
hour per engine per scope (a remote client sees only the brain and its own
principal); `gbrain sync status`, doctor and autopilot cycle output carry it
every time. `gbrain notices mute write_capacity_low` mutes it on receipts;
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 5184f4732f..7d4e592f1f 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2668,6 +2668,7 @@ gbrain config set persistence.receipt_retention_days 90 # keep the receipts wh
gbrain repair failed-writes --source <id> # preview: every refused write with its class
gbrain repair failed-writes --source <id> --apply --expect <hash>
gbrain repair failed-writes --source <id> # replayed writes now read already_written
+gbrain config unset persistence.receipt_retention_days # recovered: back to 30 days, so receipts stop holding write capacity 3x longer
```
Candidates are failed receipts refused by the guard (`writer_coordinator_required`,
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index cc48ea8298..305c2fbf2f 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -125,7 +125,7 @@ of making a duplicate.
| <a id="upload_too_many_parts"></a>`upload_too_many_parts` | `upload_too_many_parts` | An `upload_page_part` call would be part number 64 plus one per 64 KiB of the declared `total_bytes` (one per eighth of `part_max_frame_bytes` when that is under 512 KiB) or later without completing the content. Each part is a stored row, so a session of tiny parts is bounded. The part was not stored. | Send all remaining bytes in that part if they fit within `part_max_frame_bytes`; otherwise abort and begin again, cutting parts near `part_max_frame_bytes` (`get_page_upload` returns it). |
| <a id="part_splits_code_point"></a>`part_splits_code_point` | `part_splits_code_point` | An `upload_page_part` text starts or ends with half of a surrogate pair, which has no UTF-8 encoding on its own. The part was not stored. | Move the cut before the high surrogate so the pair travels in one part, then send the part again. |
| <a id="write_quota_insufficient"></a>`write_quota_insufficient` (exit 12) | `write_quota_insufficient` | A bulk run (a managed sync catch-up, a reclone, a repair) estimated from its manifest more new receipts (ids and 16 KiB reservations) than the capacity left before its producer's pause line, so it did not start. Other writes still work. | Run the `gbrain config set <key> <value>` the message prints on the brain host, then rerun the same command. Verify with `gbrain doctor --only persistence_capacity --json`. |
-| <a id="write_capacity_low"></a>`write_capacity_low` (notice) | `write_capacity_low` | Not a refusal: a `[gbrain notice]` on write receipts, `sync` receipts, `gbrain sync status` and autopilot cycle output when a cumulative cap is at or past 80% or would run out within `persistence.capacity.warn_days` (30) days at its 7-day rate. Receipts carry it at most once an hour per engine and scope; `sync status` and doctor carry it every time. The structured `capacity` object names the scope, resource, days left and the config command. | Follow the [runbook](concurrent-writes.md#quota-near-exhaustion): raise the cap it names with the printed `gbrain config set`, then verify with `gbrain doctor --only persistence_capacity --json`. |
+| <a id="write_capacity_low"></a>`write_capacity_low` (notice) | `write_capacity_low` | Not a refusal: a `[gbrain notice]` on write receipts, `sync` receipts, `gbrain sync status` and autopilot cycle output when a cumulative cap is at or past 80% or would run out within `persistence.capacity.warn_days` (30) days at its 7-day rate. Receipts carry it at most once an hour per engine and scope; `sync status` and doctor carry it every time. The write that carries it was saved; the notice says so first and its fix is the read-only `gbrain doctor --only persistence_capacity --json`, never a cap raise. The structured `capacity` object in `gbrain sync status` names the scope, resource, days left and the config command. | Nothing to redo. Read the forecast with `gbrain doctor --only persistence_capacity --json` and follow the [runbook](concurrent-writes.md#quota-near-exhaustion) on the brain host; a raised `persistence.receipt_retention_days` comes back to the default before any cap raise. |
| <a id="write_capacity_backpressure"></a>`write_capacity_backpressure` (exit 12) | `write_capacity_backpressure` | A background producer (managed maintenance, conversation facts, an autopilot cycle phase, an autopilot catch-up sync) stopped admitting because a cumulative cap of its writer or the brain is past `persistence.capacity.background_pause_pct` (default 0.8). Interactive writes (`remember`, `put_page`, `edit_page`, an operator's `gbrain sync`, an approved `gbrain repair`) keep the remainder. No receipt was written. `reason` names the resource. Doctor `persistence_capacity` names the paused producers. | Depends on `reason`. `lifetime_ids`: ids are never freed, so only the brain host's `gbrain config set <key> <value>` from the `fix` resumes background work; waiting does not. `terminal_bytes`: the same reversible raise resumes it at once, or it resumes by itself as retained receipts compact. Verify with `gbrain doctor --only persistence_capacity --json`. |
### Other error codes
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2e82668a4c..141206108b 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },
{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },
{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },
+ { since: 'TBD', id: 'write_capacity_low_saved_gst2107', text: 'The `write_capacity_low` notice a write receipt carries now opens with "This write was saved" and its fix is the read-only `gbrain doctor --only persistence_capacity --json` (actor agent) instead of a `gbrain config set` cap raise for the user, so an agent reading the end of a successful write no longer reports it as refused. The one-more-year value doctor, the notice snapshot and `/metrics` recommend now uses the 7-day mean rate, so one bulk day is no longer projected for a year; days-to-exhaustion still uses the larger of the mean and the last 24 hours.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/capacity-forecast.ts b/src/core/persistence/capacity-forecast.ts
index b4a84d7a00..aa06d7b7a9 100644
--- a/src/core/persistence/capacity-forecast.ts
+++ b/src/core/persistence/capacity-forecast.ts
@@ -56,7 +56,7 @@ export interface CapacityForecastRow {
/** Terminal bytes only: uncompacted receipts holding more intent and authority than they reserved (admitted before #6696). */
under_reserved_receipts?: number;
basis: string;
- /** A cap that covers one more year at this rate (never below double the current cap). */
+ /** A cap that covers one more year at the window's mean rate, so one bulk day is not projected for a year (never below double the current cap). */
recommended_limit: number;
status: 'ok' | 'warn' | 'fail';
}
@@ -200,6 +200,7 @@ export async function readCapacityForecast(engine: SqlEngine & { kind?: string }
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 netMean = ids ? mean : total('net') / 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;
@@ -219,7 +220,7 @@ export async function readCapacityForecast(engine: SqlEngine & { kind?: string }
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 });
+ basis, recommended_limit: recommendedLimit(resource, used, limit, { perDay: mean, netPerDay: netMean }, retention), status });
}
}
return { rows, thresholds: { warn_days: warnDays, fail_days: failDays, warn_pct: CAPACITY_WARN_PCT, fail_pct: CAPACITY_FAIL_PCT },
diff --git a/src/core/persistence/capacity-snapshot.ts b/src/core/persistence/capacity-snapshot.ts
index 77dfdca6f7..6272bc83a3 100644
--- a/src/core/persistence/capacity-snapshot.ts
+++ b/src/core/persistence/capacity-snapshot.ts
@@ -103,13 +103,16 @@ const describe = (row: CapacityAttention) => `${row.scope} ${row.resource} ${row
+ `${row.days_to_exhaustion !== null ? `, about ${row.days_to_exhaustion} day(s) left` : ''})`;
const VERIFY = CAPACITY_VERIFY;
+/**
+ * GST-2107: this notice rides a write that succeeded, so it says so first and its fix is the read-only forecast; the cap raise
+ * stays in doctor's finding for the brain host's operator, never in the tail of a write an agent may read as a refusal.
+ */
function lowNotice(rows: CapacityAttention[]): Notice {
- const [first] = rows;
return { code: 'write_capacity_low', kind: 'info',
- why: `Write capacity is running low: ${rows.map(describe).join('; ')}. Writes still work; admission refuses at the cap. `
- + `The brain host raises it with ${rows.map(row => row.command).join('; ')} (each covers about one more year; reversible).`,
- fix: { argv: ['gbrain', 'config', 'set', first!.config_key, String(first!.recommended_limit)], consent: [], actor: 'host_admin', requires_exclusive: false,
- why: 'Raises the cap that runs out first to a value that covers about one more year; undo with gbrain config unset.', verify: VERIFY,
+ why: `This write was saved and writes still work. Write capacity is running low: ${rows.map(describe).join('; ')}; admission refuses only at the cap. `
+ + 'gbrain doctor --only persistence_capacity --json reads the forecast and the remedy for the brain host.',
+ fix: { argv: [...VERIFY.argv], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Reads which cap is running low, its forecast and the remedy, read-only; nothing needs to change for this write.', verify: VERIFY,
docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } };
}
diff --git a/test/persistence-capacity-notices.test.ts b/test/persistence-capacity-notices.test.ts
index 4b7a987411..946441f102 100644
--- a/test/persistence-capacity-notices.test.ts
+++ b/test/persistence-capacity-notices.test.ts
@@ -15,7 +15,9 @@ import { __resetCapacityNoticesForTests, cachedCapacitySnapshot, CAPACITY_NOTICE
import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
import { renderCapacityMetrics } from '../src/commands/serve-http-metrics.ts';
import { NOTICE_CODES } from '../src/core/error-registry.ts';
-import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';
+import { readCapacityForecast } from '../src/core/persistence/capacity-forecast.ts';
+import { recommendedLimit } from '../src/core/persistence/limits.ts';
+import { editRequest, freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -62,8 +64,11 @@ for (const kind of testBackends()) {
const t0 = Date.now() + 100 * CAPACITY_SNAPSHOT_TTL_MS; // past any snapshot an earlier case left on a reused engine
const first = await capacityNotices(engine, { throttle: true, now: t0 });
expect(codes(first)).toEqual(['write_capacity_low']);
- expect(first[0]).toMatchObject({ kind: 'info', fix: { actor: 'host_admin', argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', expect.stringMatching(/^\d+$/)] } });
+ // GST-2107: the notice rides a write that succeeded, so its last lines name a read-only check, never a cap raise for the user.
+ expect(first[0]).toMatchObject({ kind: 'info', fix: { actor: 'agent', argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] } });
expect(first[0]!.why).toContain('81%');
+ expect(first[0]!.why).toContain('This write was saved');
+ expect(first[0]!.why).not.toContain('config set');
expect(await capacityNotices(engine, { throttle: true, now: t0 + 1000 })).toEqual([]);
expect(codes(await capacityNotices(engine, { throttle: false, now: t0 + 1000 }))).toEqual(['write_capacity_low']);
expect(codes(await capacityNotices(engine, { throttle: true, now: t0 + CAPACITY_NOTICE_INTERVAL_MS }))).toEqual(['write_capacity_low']);
@@ -100,6 +105,26 @@ for (const kind of testBackends()) {
expect(own[0]!.why).toMatch(/principal:local_cli:/);
});
+ check('the one-year value follows the 7-day mean, not a burst in the last day (GST-2107)', async engine => {
+ const fixture = await requestFixture(engine);
+ const ids: string[] = [];
+ for (let i = 0; i < 71; i++) ids.push((await fixture.admit(`burst-${i}`)).id);
+ // One admission before the window (so it spans a full 7 days), 42 spread over the six days before the last one and 28 in
+ // the last hour: a mean of 10 a day, 28 in the last day.
+ const ageDays = (i: number) => i === 0 ? 10 : 6.5 - Math.floor((i - 1) / 7);
+ for (let i = 0; i < 43; i++) await editRequest(engine, ids[i]!, "created_at=now()-($2::double precision*interval '1 day')", [ageDays(i)]);
+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '100');
+ await engine.setConfig('persistence.limits.principal_terminal_bytes', '1');
+ const forecast = await readCapacityForecast(engine);
+ const row = (resource: string) => forecast.rows.find(r => r.scope.startsWith('principal:') && r.resource === resource)!;
+ expect(row('lifetime_ids').per_day_7d).toBe(28);
+ expect(row('lifetime_ids').recommended_limit).toBe(71 + 10 * 365);
+ const [{ gross }] = await engine.executeRaw<{ gross: string }>('SELECT SUM(terminal_reservation)::text AS gross FROM persistence_requests');
+ const used = row('terminal_bytes').used;
+ const ceiling = recommendedLimit('terminal_bytes', used, 1, { perDay: Number(gross) / 7, netPerDay: Number(gross) / 7 }, forecast.retention_days);
+ expect(row('terminal_bytes').recommended_limit).toBeLessThanOrEqual(ceiling);
+ });
+
check('writes within a minute share one snapshot; the next minute reads again', async engine => {
await requestFixture(engine).then(r => r.admit('one'));
await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');