Skip to content

Commit 4c12c97

Browse files
masatohoshinosteipetefuller-stack-dev
authored
fix(sessions): highWaterBytes 0 no longer deletes all session history (#119909)
* fix(sessions): zero highWaterBytes no longer clears all session history resolveHighWaterBytes passed an explicit non-positive highWaterBytes through verbatim. The resolved value is the disk-budget cleanup loop's stop condition, so a zero target made enforce mode evict every unprotected session and prune its extracted archives instead of trimming to the documented 80% default. Route the non-positive case to the function's existing unusable-value branch (computeDefault). Not null: that disables the budget and permits unbounded growth, which is right for a cap but wrong for a target. Sibling of #119422, which fixed the same harm for maxDiskBytes and guarded only resolveMaxDiskBytes. * test(infra): isolate worktree migration discovery Keep worktree migration coverage focused on its real filesystem, Git, and SQLite owner while avoiding unrelated channel and plugin doctor cold starts on fork CI. Co-authored-by: masatohoshino <[email protected]> * test(ci): carry owner-approved SDK and doctor gate repairs Carry the already-approved plugin SDK contract manifest and focused doctor-flow test isolation from the maintainer-owned CI repair. Preserve real config migration, persistence, snapshot, and SQLite cleanup coverage; no production behavior changes. Co-authored-by: masatohoshino <[email protected]> * fix(sessions): use the renamed withTestDir helper in the new budget test * fix(sessions): align high-water zero contract * style(sessions): format high-water changes --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: FullerStackDev <[email protected]>
1 parent 1e19f22 commit 4c12c97

8 files changed

Lines changed: 90 additions & 22 deletions

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1253,7 +1253,7 @@ See [Multi-Agent Sandbox & Tools](/tools/multi-agent-sandbox-tools) for preceden
12531253
- Legacy `rotateBytes` is rejected by the current schema; `openclaw doctor --fix` removes it from older configs.
12541254
- `resetArchiveRetention`: age-based retention for reset/deleted transcript archives. By default, archives remain until disk-budget eviction; set a duration to opt into wall-clock deletion, or `false` to disable it explicitly.
12551255
- `maxDiskBytes`: optional sessions-directory disk budget. In `warn` mode it logs warnings; in `enforce` mode it removes oldest artifacts/sessions first. Set `false`, `0`, or `"0"` to disable the budget entirely.
1256-
- `highWaterBytes`: optional target after budget cleanup. Defaults to `80%` of `maxDiskBytes`.
1256+
- `highWaterBytes`: optional target after budget cleanup. Defaults to `80%` of `maxDiskBytes`. A value that resolves to zero falls back to the default; negative values are invalid. Disable the budget with `maxDiskBytes`, not with a zero high-water mark.
12571257
- **`threadBindings`**: global defaults for thread-bound session features.
12581258
- `enabled`: master switch for supported channel thread bindings
12591259
- `idleHours`: default inactivity auto-unfocus in hours (`0` disables; providers can override)

‎docs/reference/session-management-compaction.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ Per agent, on the Gateway host (resolved via `src/config/sessions.ts`):
5151
| `maxEntries` | `500` | cap on session entries |
5252
| `resetArchiveRetention` | keep (no age cutoff) | age cutoff for `*.reset.*`/`*.deleted.*` transcript archives; a duration opts into deletion |
5353
| `maxDiskBytes` | `10gb` | per-agent sessions disk budget; `false`, `0`, or `"0"` disables |
54-
| `highWaterBytes` | 80% of `maxDiskBytes` | target after budget cleanup |
54+
| `highWaterBytes` | 80% of `maxDiskBytes` | target after cleanup; zero-resolving values use the default, and negatives are invalid |
5555

5656
Reset advances the live `sessionKey -> sessionId` mapping but keeps the previous SQLite session, transcript, trajectory, and search rows. That history remains searchable under the same session key; ordinary entry and session lists show only the new live mapping. Retained reset history is bounded by the disk budget, not by `resetArchiveRetention`, which only ages archive artifacts. Explicit deletion is different: it writes and verifies a compressed transcript archive (`*.jsonl.deleted.<timestamp>.zst` when zstd is available) before removing the deleted session's rows.
5757

‎src/config/schema.help.automation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export const AUTOMATION_FIELD_HELP: Record<string, string> = {
8383
"session.maintenance.maxDiskBytes":
8484
'Per-agent sessions-directory disk budget (for example `500mb`). Defaults to `10gb`; when exceeded, warn mode reports pressure and enforce mode performs oldest-first cleanup (archived transcripts before live sessions). Set `false`, `0`, or `"0"` to disable.',
8585
"session.maintenance.highWaterBytes":
86-
"Target size after disk-budget cleanup (high-water mark). Defaults to 80% of maxDiskBytes; set explicitly for tighter reclaim behavior on constrained disks.",
86+
"Target size after disk-budget cleanup (high-water mark). Defaults to 80% of maxDiskBytes; set explicitly for tighter reclaim behavior on constrained disks. A value that resolves to zero falls back to the default; negative values are invalid. Disable the budget with maxDiskBytes instead.",
8787
cron: "Global scheduler settings for stored automations, run concurrency, delivery fallback, and run-session retention. Keep defaults unless you are scaling automation volume or integrating external webhook receivers.",
8888
"cron.enabled":
8989
"Enables automation execution for stored schedules managed by the gateway. Keep enabled for normal reminder/automation flows, and disable only to pause all automation execution without deleting jobs.",

‎src/config/sessions/disk-budget.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
pruneUnreferencedSessionArtifacts,
2323
} from "./disk-budget.js";
2424
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
25+
import { resolveMaintenanceConfigFromInput } from "./store-maintenance.js";
2526
import type { SessionEntry } from "./types.js";
2627

2728
async function expectPathExists(targetPath: string): Promise<void> {
@@ -831,6 +832,47 @@ describe("enforceSessionDiskBudget", () => {
831832
await expectPathExists(oldTranscript);
832833
});
833834
});
835+
836+
it("stops at the default target when highWaterBytes resolves to zero", async () => {
837+
await withTestDir({ prefix: "openclaw-zero-high-water-" }, async (dir) => {
838+
const storePath = path.join(dir, "sessions.json");
839+
const store: Record<string, SessionEntry> = {};
840+
for (let index = 1; index <= 4; index += 1) {
841+
await fs.writeFile(path.join(dir, `worker-${index}.jsonl`), "x".repeat(64 * 1024));
842+
store[`agent:main:subagent:worker-${index}`] = {
843+
sessionId: `worker-${index}`,
844+
updatedAt: index,
845+
};
846+
}
847+
await saveSessionStore(storePath, store, { skipMaintenance: true });
848+
849+
const maintenance = resolveMaintenanceConfigFromInput({
850+
maxDiskBytes: 200_000,
851+
highWaterBytes: 0,
852+
});
853+
const result = await enforceSessionDiskBudget({
854+
store,
855+
storePath,
856+
maintenance: {
857+
maxDiskBytes: maintenance.maxDiskBytes,
858+
highWaterBytes: maintenance.highWaterBytes,
859+
},
860+
warnOnly: false,
861+
commitEvictedIndex: async () => {
862+
await fs.writeFile(storePath, JSON.stringify(store, null, 2), "utf-8");
863+
},
864+
});
865+
866+
// The resolved high-water mark is this loop's stop condition, so a zero
867+
// mark is unreachable while any data remains and every session would be
868+
// evicted. The default target stops the sweep with history intact.
869+
expect(maintenance.highWaterBytes).toBe(160_000);
870+
expectBudgetResult(result);
871+
expect(result.totalBytesAfter).toBeLessThanOrEqual(160_000);
872+
expect(store).toHaveProperty("agent:main:subagent:worker-4");
873+
await expectPathExists(path.join(dir, "worker-4.jsonl"));
874+
});
875+
});
834876
});
835877

836878
describe("pruneUnreferencedSessionArtifacts", () => {

‎src/config/sessions/store-maintenance.ts‎

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -120,34 +120,25 @@ function resolveHighWaterBytes(
120120
maintenance: SessionMaintenanceConfig | undefined,
121121
maxDiskBytes: number | null,
122122
): number | null {
123-
const computeDefault = () => {
124-
if (maxDiskBytes == null) {
125-
return null;
126-
}
127-
if (maxDiskBytes <= 0) {
128-
return 0;
129-
}
130-
return Math.max(
131-
1,
132-
Math.min(
133-
maxDiskBytes,
134-
Math.floor(maxDiskBytes * DEFAULT_SESSION_DISK_BUDGET_HIGH_WATER_RATIO),
135-
),
136-
);
137-
};
138123
if (maxDiskBytes == null) {
139124
return null;
140125
}
126+
const defaultHighWaterBytes = Math.max(
127+
1,
128+
Math.min(maxDiskBytes, Math.floor(maxDiskBytes * DEFAULT_SESSION_DISK_BUDGET_HIGH_WATER_RATIO)),
129+
);
141130
const raw = maintenance?.highWaterBytes;
142131
const normalized = normalizeStringifiedOptionalString(raw);
143132
if (!normalized) {
144-
return computeDefault();
133+
return defaultHighWaterBytes;
145134
}
146135
try {
147136
const parsed = parseByteSize(normalized, { defaultUnit: "b" });
148-
return Math.min(parsed, maxDiskBytes);
137+
// A zero target cannot stop cleanup while any bytes remain, so use the
138+
// default instead of evicting every unprotected session and archive.
139+
return parsed > 0 ? Math.min(parsed, maxDiskBytes) : defaultHighWaterBytes;
149140
} catch {
150-
return computeDefault();
141+
return defaultHighWaterBytes;
151142
}
152143
}
153144

‎src/config/sessions/store.pruning.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -979,6 +979,30 @@ describe("resolveMaintenanceConfigFromInput", () => {
979979
});
980980
});
981981

982+
it.each([
983+
["the number 0", 0],
984+
["the string '0'", "0"],
985+
["the byte string '0b'", "0b"],
986+
["a byte string that rounds to zero", "0.4b"],
987+
])("falls back to the default high-water mark when highWaterBytes is %s", (_label, raw) => {
988+
const maintenance = resolveMaintenanceConfigFromInput({
989+
maxDiskBytes: "500mb",
990+
highWaterBytes: raw,
991+
});
992+
993+
expect(maintenance.maxDiskBytes).toBe(500 * 1024 * 1024);
994+
expect(maintenance.highWaterBytes).toBe(Math.floor(500 * 1024 * 1024 * 0.8));
995+
});
996+
997+
it("keeps an explicit positive highWaterBytes", () => {
998+
const maintenance = resolveMaintenanceConfigFromInput({
999+
maxDiskBytes: "500mb",
1000+
highWaterBytes: "300mb",
1001+
});
1002+
1003+
expect(maintenance.highWaterBytes).toBe(300 * 1024 * 1024);
1004+
});
1005+
9821006
it("force-gates the unset model-run prune default to the cap-eviction threshold", () => {
9831007
const defaultMaintenance = resolveMaintenanceConfigFromInput({ maxEntries: 50 });
9841008
expect(resolveSessionEntryMaintenanceHighWater(50)).toBe(75);

‎src/config/types.base.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,8 @@ export type SessionMaintenanceConfig = {
267267
maxDiskBytes?: number | string | false;
268268
/**
269269
* Target size after disk-budget cleanup (high-water mark), e.g. "400mb".
270-
* Default: 80% of maxDiskBytes.
270+
* Default: 80% of maxDiskBytes. A value that resolves to zero falls back to
271+
* the default instead of clearing history; negative values are invalid.
271272
*/
272273
highWaterBytes?: number | string;
273274
};

‎src/config/zod-schema.session-maintenance-extensions.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,16 @@ describe("SessionSchema maintenance extensions", () => {
7373
).toBe(true);
7474
});
7575

76+
it.each([0, "0", "0b", "0.4b"])("accepts zero-resolving highWaterBytes: %s", (highWaterBytes) => {
77+
expect(SessionSchema.safeParse({ maintenance: { highWaterBytes } }).success).toBe(true);
78+
});
79+
80+
it.each([-1, "-1", "-1b", "-0.4b"])("rejects negative highWaterBytes: %s", (highWaterBytes) => {
81+
const result = SessionSchema.safeParse({ maintenance: { highWaterBytes } });
82+
expect(result.success).toBe(false);
83+
expect(result.error?.issues[0]?.path).toContain("highWaterBytes");
84+
});
85+
7686
it("accepts resetArchiveRetention: false (documented disable)", () => {
7787
expect(SessionSchema.safeParse({ maintenance: { resetArchiveRetention: false } }).success).toBe(
7888
true,

0 commit comments

Comments
 (0)