Skip to content

fix: stop overestimating update space for large agent databases - #186980

Merged
fuller-stack-dev merged 2 commits into
openclaw:mainfrom
fuller-stack-dev:fix/update-activation-space-history-owner-20261028
Oct 28, 2026
Merged

fuller-stack-dev merged 2 commits into
openclaw:mainfrom
fuller-stack-dev:fix/update-activation-space-history-owner-20261028

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Related: #183091, #183177, #173284

What Problem This Solves

Fixes updates refusing enough free disk space when a large agent database is charged for shared update-history preparation.

User Impact

SQLite installations with agent databases larger than shared state can update with a smaller activation allowance. The reduction is the difference between the largest database family and shared state: about 20 GiB for the reported installation. Both initial preflight and activation use the corrected calculation.

PostgreSQL configurations, missing shared-state identity, separate source-volume checks, the 64 MiB reserve, and rollback's checks of actual output sizes retain their existing behavior. No configuration change or migration is required. This repair must be present in the runtime performing admission; an older installed updater's own preflight is unchanged.

Why This Change Was Made

Candidate snapshot admission was already reduced by #173284. Activation still charged the largest family for three overlapping shared-history images; #183177 correctly moved that same calculation into early preflight without reducing it.

The shared admission owner now identifies the canonical shared family and uses 2S + 2L + H instead of 2S + 3L, where S is total family bytes, L the largest family and H shared state. It keeps the previous growth envelope: a prepared shared image can include baseline H plus current history up to L; retaining that image alongside backups and all writable rollback outputs needs 2S - H + 2(H + L). The budget stays unchanged when shared state is largest. Capture and restore lifetimes are unchanged. #186510 separately owns redundant generation-image I/O.

Initial admission cannot guarantee arbitrary later migration/history growth. Actual rollback allocation still refuses before moving current databases if the resulting images cannot fit. PostgreSQL export sizing and implicit generation staging on another temporary volume remain separate accounting limitations.

Evidence

  • Red on 76fc97e3765d: native admission refused 83,959,808 available bytes, requiring 88,158,208, although real SQLite capture preserved source bytes and passed integrity. The fixed source admits that capacity. Independent source-blind checks also admitted a varied 6 MiB fixture and refused a one-byte shortage.
  • pnpm test src/infra/update-database-backup-space.test.ts src/infra/update-database-backup.test.ts src/infra/update-database-backup-engine.test.ts src/infra/update-database-restore.test.ts src/infra/update-candidate-rehearsal.resources.test.ts --maxWorkers=1: 94 passed, 309s including worker preparation. Covers both admission callers, WAL capture, source preservation, shortages, conservative fallback, external-volume checks, rollback output allocation failure and retained history.
  • pnpm build: passed, 237s. pnpm tsgo:core, changed test graph (services), scoped Oxlint, formatting and git diff --check: passed.
  • Local AutoReview: complete source snapshot against 76fc97e3765d, P0–P2, scoped-clean, no actionable findings. Local ClawSweeper was unavailable; the hosted review request follows the repository maintainer workflow. Rebased onto 60b52d9d21d1 after inspecting disjoint native-schema, gateway placement/ancestor, Android release and Codex catalog changes; capacity source and tests are byte-identical to the reviewed/tested snapshot.
  • Entire new test file audited: five distinct cases with real SQLite files; only OS capacity is mocked. Fixtures own their paths and close handles, remove temporary data and restore mocks. No existing tests removed. Smallest fix stays in the existing shared admission owner; production +27/-3 lines, tests +133.

A full published-driver × candidate upgrade and live Gateway/model round trip were not run. Proof exercises admission/capture owners and the existing restore suite, not an end-to-end fleet deployment.

Baseline recording (real terminal capture of the synthetic fixture):

update-activation-space-base.mp4

Fixed revision recording (53ba64cbcdf688951d0358efa9631c825ef7bbe8, same fixture and observation point):

update-activation-space-head.mp4

Proof manifest and raw sanitized terminal records.

Test budget correction

CI 40750132163 passed the applicable product and security checks but refused the total test-line budget. Keep the 133-line real SQLite regression file: it proves initial admission and capture, WAL sizing, exact boundary refusal, shared-database identity, and conservative PostgreSQL behavior. The entire file was audited; no tests were removed.

After incorporating canonical main fefc2fb without rewriting published ancestry, the measured tree has 6,310,783 test lines. Set the ceiling to that exact total, 223 above the current main ceiling. This covers 90 pre-existing over-budget lines and 133 new regression lines, with no future allowance. The local budget check and independent P0–P2 AutoReview passed. Production and test changes are byte-identical to the previously validated 53ba64 patch.

@clawsweeper

clawsweeper Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@fuller-stack-dev

fuller-stack-dev commented Oct 28, 2026 •

Copy link
Copy Markdown
Member Author

Proof manifest

Actual local terminal recordings, with synthetic SQLite data and OS capacity fixture.

{
  "repository": "https://github.com/openclaw/openclaw",
  "pr": "https://github.com/openclaw/openclaw/pull/186980",
  "base": "76fc97e3765d8865a00e036e9868927ca6f1910e",
  "head": "53ba64cbcdf688951d0358efa9631c825ef7bbe8",
  "provider": "local macOS",
  "lease": null,
  "node": "26.12.1",
  "fixture": "real 4 MiB agent SQLite database plus small shared SQLite database; only OS available capacity is simulated",
  "baseResult": {
    "availableBytes": 83959808,
    "requiredBytes": 88158208,
    "preflightExit": 1,
    "captureIntegrity": "ok",
    "sourceUnchanged": true
  },
  "headResult": {
    "availableBytes": 83959808,
    "requiredBytes": 83959808,
    "preflightExit": 0,
    "captureIntegrity": "ok",
    "sourceUnchanged": true
  },
  "negativeControl": {
    "availableBytes": 83959807,
    "preflightExit": 1
  },
  "independentValidator": "pass: 4 MiB, varied 6 MiB, one-byte shortage; source blind",
  "review": "AutoReview P0-P2 scoped-clean on byte-identical authored source snapshot",
  "tests": "94 passed; full build, core/test types, lint, formatting passed before disjoint rebase",
  "limitations": [
    "No full published-driver upgrade or live Gateway/model round trip",
    "No new guarantee for arbitrary future migration growth or PostgreSQL export sizing",
    "Implicit generation staging on another temporary volume remains separate accounting limitation"
  ],
  "videos": {
    "base": "https://github.com/user-attachments/assets/ba90deec-c72e-49ab-8357-bbc0f2dec362",
    "head": "https://github.com/user-attachments/assets/2520eb6e-8af5-4fb2-8b61-37163264733e"
  },
  "redactions": [
    "Private fixture path replaced in terminal output before recording",
    "Local command paths removed from published cast metadata; recorded output/timing unchanged"
  ],
  "files": {
    "base.cast": {
      "sha256": "8d1722114e868f141dabf1489cb669c930595c317aba077ce7fc329632d79250",
      "bytes": 747
    },
    "head.cast": {
      "sha256": "bccf9a6b3def8a0280251b57154e341e3831e489b0b62393e64da71d9a7b14ed",
      "bytes": 569
    },
    "reproduce.mts": {
      "sha256": "160100f4b24bd9b6b7f1448df2f928c9d61e62ad07bbefc03cc7fb243eef07f5",
      "bytes": 3212
    },
    "base.mp4": {
      "sha256": "61f8e5dea39e79a81b83b5a83f4463bf7a7b0c264218894ad8de3db5764065e1",
      "bytes": 32281
    },
    "head-final.mp4": {
      "sha256": "86489dcd351de28a31dfdd41bcb669d702f16d354087a47aaeccae97cf8f5521",
      "bytes": 22896
    }
  },
  "artifactDelivery": "MP4 recordings are GitHub attachments; manifest and raw sanitized terminal records are inline in this PR comment. Text attachment upload returned HTTP422; no raw local paths or private data are included."
}
Raw sanitized terminal records

Base

[0.085842, "o", "REAL SQLITE UPDATE CAPACITY PROOF\r\nRevision: 76fc97e3765d8865a00e036e9868927ca6f1910e\r\nFixture: 4 MiB agent + small shared database; OS free-space fixture\r\n"]
[7.197331, "o", "Preflight: exit 1\r\nAvailable: 83959808 bytes\r\n"]
[7.197459, "o", "Update database backup needs 84 MiB (88158208 bytes) near <private fixture>, but only 80 MiB (83959808 bytes) is available. Free disk space before retrying; the databases have not been migrated.\r\nReal snapshot: integrity=ok; source unchanged=True\r\n"]
[7.197478, "o", "Elapsed: 7.112s; process exit=1\r\n"]
[7.199556, "x", "1"]

Head

[0.075073, "o", "REAL SQLITE UPDATE CAPACITY PROOF\r\nRevision: 53ba64cbcdf688951d0358efa9631c825ef7bbe8\r\nFixture: 4 MiB agent + small shared database; OS free-space fixture\r\n"]
[4.286179, "o", "Preflight: exit 0\r\nAvailable: 83959808 bytes\r\nActivation database budget admitted.\r\nReal snapshot: integrity=ok; source unchanged=True\r\n"]
[4.286186, "o", "Elapsed: 4.211s; process exit=0\r\n"]
[4.288842, "x", "0"]
Reproduction harness (Node 26.12.1; repository-pinned tsx)

Run: tsx --tsconfig <checkout>/tsconfig.json reproduce.mts <checkout> [blobBytes] [low]. Baseline exits 1; fixed head exits 0; low exits 1. Only OS available capacity is simulated. All SQLite files and capture/integrity operations are real.

import assert from 'node:assert/strict';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
const repo = process.argv[2];
const blobBytes=Number(process.argv[3] || 4194304);
const low=process.argv[4]==='low';
const { assessInitialUpdateSnapshotCapacity } = await import(`${repo}/src/infra/update-candidate-snapshot.ts`);
const { discoverUpdateStateSchemaInspectionInProcess } = await import(`${repo}/src/infra/update-candidate-state.ts`);
const { createUpdateDatabaseBackupInProcess } = await import(`${repo}/src/infra/update-database-backup.ts`);
const root = await fsp.realpath(await fsp.mkdtemp(path.join(os.tmpdir(), 'activation-space-proof-')));
const stateDir = path.join(root,'state');
const source = path.join(stateDir,'state/openclaw.sqlite');
const agent = path.join(stateDir,'agents/main/agent/openclaw-agent.sqlite');
const backupRoot = path.join(root,'backup');
const directory = `${backupRoot}.databases`;
const stagingRoot = path.join(root,'scratch');
const statfs = fs.statfsSync;
try {
  for (const dir of [path.dirname(source),path.dirname(agent),directory,stagingRoot]) await fsp.mkdir(dir,{recursive:true});
  { using db = new DatabaseSync(source); db.exec("PRAGMA user_version=17; CREATE TABLE witness(value BLOB); INSERT INTO witness(rowid,value) VALUES(42,zeroblob(1));"); }
  { using db = new DatabaseSync(agent); db.exec(`PRAGMA user_version=17; CREATE TABLE witness(value BLOB); INSERT INTO witness(rowid,value) VALUES(42,zeroblob(${blobBytes}));`); }
  const before = await fsp.readFile(source);
  const agentBefore = await fsp.readFile(agent);
  const sharedBytes = before.length;
  const agentBytes = (await fsp.stat(agent)).size;
  const bytes = sharedBytes + agentBytes;
  const admittedBytes = 2*bytes+2*agentBytes+sharedBytes+64*1024**2-(low?1:0);
  fs.statfsSync = ((...args:any[])=>({...statfs(...args), bsize:1, bavail:admittedBytes})) as typeof statfs;
  const result = await assessInitialUpdateSnapshotCapacity({config:{},stateDir,env:{},backupDirectory:directory});
  console.log(JSON.stringify({phase:'preflight',sourceBytes:bytes,availableBytes:admittedBytes,result},null,2));
  fs.statfsSync = statfs;
  const input = {backupRoot,stateDir,config:{},env:{},stagingRoot,stopped:true};
  const backup = await createUpdateDatabaseBackupInProcess({...input,inspectionPlan:await discoverUpdateStateSchemaInspectionInProcess(input)});
  assert.equal(backup.databases.length,2);
  { using db = new DatabaseSync(backup.databases.find((entry:any)=>entry.path===agent).snapshotPath,{readOnly:true}); assert.deepEqual({...db.prepare('SELECT rowid,length(value) AS bytes FROM witness').get()},{rowid:42,bytes:blobBytes}); assert.equal(db.prepare('PRAGMA integrity_check').get().integrity_check,'ok'); }
  assert.deepEqual(await fsp.readFile(source),before);
  assert.deepEqual(await fsp.readFile(agent),agentBefore);
  console.log(JSON.stringify({phase:'real-capture',snapshotBytes:backup.databases[0].sizeBytes,sourceUnchanged:true,integrity:'ok'}));
  process.exitCode=result.exitCode;
} finally { fs.statfsSync=statfs; await fsp.rm(root,{recursive:true,force:true}); }

@fuller-stack-dev
fuller-stack-dev marked this pull request as ready for review October 28, 2026 18:58
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 28, 2026
@clawsweeper

clawsweeper Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR sizes shared-history preparation from the shared database instead of the largest agent database in both update admission checks.

Example: A real 4 MiB agent SQLite fixture has 83,959,808 bytes available.

  • Before: Preflight refuses because it requires 88,158,208 bytes.
  • After: Preflight admits the fixture at 83,959,808 bytes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, source-supported repair with useful production-owner evidence and no identified defect, but the applicable upgrade validation remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Updates can refuse sufficient free space because a large agent database is charged for shared-history preparation.
Reason: The repair removes an evidenced overestimate, retains one admission owner and follows the maintainer author's approved direction.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a concrete admission overestimate still present on main, and no introduced correctness defect was found.

Priority: P2
Reviewed head: 53ba64cbcdf688951d0358efa9631c825ef7bbe8

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show a latest-stable published-driver upgrade through the shipped updater with settings and durable data preserved.
Agent review details

How this fits together

The updater measures database families and available disk space before staging and activation; the shared admission owner permits capture or returns a capacity refusal, while rollback separately checks actual writable-output sizes.

flowchart TD
  A[CLI update] --> B[Initial preflight]
  A --> C[Activation capture]
  B --> D[Shared space admission]
  C --> D
  D --> E[Database backups]
  E --> F[Rollback preparation]
  F --> G[Actual output space checks]
Loading

Technical review

Best possible solution:

Keep the correction in the existing shared admission owner while preserving conservative fallback and actual-size rollback checks.

Do we have a high-confidence way to reproduce the issue?

Current-main source establishes the excess L − H allowance, and the supplied baseline terminal records demonstrate refusal with real SQLite files; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch is the smallest complete repair: identify shared-family bytes in the existing admission owner and pass existing context from its two callers, without changing capture or restore mechanics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4757ac8eb6b8.

Provenance checked

  • Activation backup allowance changes intended behavior with a stated reason (d780fdc: Reserve space for verified snapshots, independent rollback copies and acquisition/publication scratch before database migrations.)
  • Shared preflight and activation admission keeps the original intent (8738c09: Refuse insufficient activation capacity before expensive validation by using the same calculation at both phases.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 8738c09 adds src/infra/update-database-backup-space.ts:20 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8738c093be6e; files: src/infra/update-database-backup-space.ts)
  • Jason (Json): Raw commit 712db88 adds src/infra/update-candidate-snapshot.ts:40 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 712db88927aa; files: src/infra/update-candidate-snapshot.ts)
  • Vincent Koc: Raw commit c73495d adds src/infra/update-database-backup.ts:286 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c73495de40bc; files: src/infra/update-database-backup.ts)

PR surface

Source +24, Tests +133. Total +157 across 4 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 27 3 +24
Tests 1 133 0 +133
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 160 3 +157

Labels

Label changes:

  • add P2: The overestimate unnecessarily refuses capacity-constrained SQLite updates with large agent databases; this is an operator update workflow with limited blast radius.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: The overestimate unnecessarily refuses capacity-constrained SQLite updates with large agent databases; this is an operator update workflow with limited blast radius.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Provide the published-driver × candidate upgrade result required by the update contract.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 28, 2026, 3:04 PM ET / 19:04 UTC.

@fuller-stack-dev
fuller-stack-dev enabled auto-merge (squash) October 28, 2026 19:39
@fuller-stack-dev
fuller-stack-dev merged commit db6efe4 into openclaw:main Oct 28, 2026
124 checks passed
@fuller-stack-dev
fuller-stack-dev deleted the fix/update-activation-space-history-owner-20261028 branch October 28, 2026 20:05
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via squash auto-merge.

amittell added a commit to amittell/openclaw that referenced this pull request Oct 28, 2026
Resolve the concrete baseline conflict with upstream openclaw#186980 while retaining
its SQLite regression coverage and all 977 telemetry regression lines.
Measure the pinned base at 6,310,907 lines and the combined tree at 6,311,884;
set that exact ceiling without extra allowance.

The ratchet passes, rejects one added line, and passes after restoration.
Touched-file format, source identities and 13 integration cases pass.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant