@devries-cameron20 / t3code-1 / commits / a3ca1a57d6
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): keep compaction cadence across restarts (#21880)

Julius Marminge committed Oct 19, 2026 at 20:13 UTC a3ca1a57d65093c3f19d83f2c2b6d63663a380e1
2 files changed +138 -8
apps/server/src/persistence/DatabaseStorage.test.ts
+106
@@ -1,10 +1,13 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 +import * as Clock from "effect/Clock";
4 +import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Option from "effect/Option";
9 import * as Path from "effect/Path";
10 +import * as Queue from "effect/Queue";
11 import * as Stream from "effect/Stream";
12 import * as TestClock from "effect/testing/TestClock";
13 import * as SqlClient from "effect/sql/SqlClient";
@@ -108,3 +111,106 @@ it.effect("publishes nothing when doctor would repair a different database", ()
111 ),
112 ),
113 );
114 +
115 +const compactionLayer = (
116 + compactEventStore: ProjectionMaintenance.ProjectionMaintenanceV2["Service"]["compactEventStore"],
117 +) =>
118 + DatabaseStorage.layer.pipe(
119 + Layer.provide(
120 + Layer.succeed(ProjectionMaintenance.ProjectionMaintenanceV2, {
121 + compactEventStore,
122 + verify: Effect.die("unexpected verification"),
123 + rebuild: Effect.die("unexpected rebuild"),
124 + }),
125 + ),
126 + Layer.provide(Sqlite.layerMemory),
127 + );
128 +
129 +const minute = 60_000;
130 +const hour = 60 * minute;
131 +const startupTime = Date.UTC(2026, 9, 19);
132 +const emptyCompaction = { deletedEventCount: 0, deletedReceiptCount: 0, reclaimableBytes: 0 };
133 +
134 +it.effect.each([
135 + { name: "recent success", saved: String(startupTime - 2 * hour), delay: 4 * hour },
136 + { name: "overdue success", saved: String(startupTime - 7 * hour), delay: minute },
137 + { name: "nearly due success", saved: String(startupTime - 6 * hour + 1), delay: minute },
138 + { name: "future timestamp", saved: String(startupTime + hour), delay: 6 * hour },
139 + { name: "missing timestamp", saved: undefined, delay: minute },
140 + { name: "invalid timestamp", saved: "not a timestamp", delay: minute },
141 + { name: "unreadable timestamp", saved: undefined, delay: minute },
142 +])("schedules startup compaction after $name", ({ name, saved, delay }) =>
143 + Effect.gen(function* () {
144 + yield* TestClock.setTime(startupTime);
145 + const fs = yield* FileSystem.FileSystem;
146 + const path = yield* Path.Path;
147 + const config = yield* ServerConfig.ServerConfig;
148 + const timestampPath = path.join(path.dirname(config.dbPath), "compacted-at");
149 + if (name === "unreadable timestamp") yield* fs.makeDirectory(timestampPath);
150 + else if (saved !== undefined) yield* fs.writeFileString(timestampPath, saved);
151 + const started = yield* Deferred.make<number>();
152 + const compact = Clock.currentTimeMillis.pipe(
153 + Effect.flatMap((now) => Deferred.succeed(started, now)),
154 + Effect.as(emptyCompaction),
155 + );
156 + yield* Effect.gen(function* () {
157 + yield* TestClock.adjust(delay - 1);
158 + assert.isFalse(yield* Deferred.isDone(started));
159 + yield* TestClock.adjust(1);
160 + assert.equal(yield* Deferred.await(started), startupTime + delay);
161 + }).pipe(Effect.provide(compactionLayer(compact)));
162 + }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
163 +);
164 +
165 +it.effect.each(["success", "compaction failure", "timestamp write failure"] as const)(
166 + "keeps the six-hour cadence after %s and remembers only successful completion",
167 + (outcome) =>
168 + Effect.gen(function* () {
169 + yield* TestClock.setTime(startupTime);
170 + const fs = yield* FileSystem.FileSystem;
171 + const path = yield* Path.Path;
172 + const config = yield* ServerConfig.ServerConfig;
173 + const timestampPath = path.join(path.dirname(config.dbPath), "compacted-at");
174 + const previous = String(startupTime - 7 * hour);
175 + if (outcome === "timestamp write failure") yield* fs.makeDirectory(timestampPath);
176 + else yield* fs.writeFileString(timestampPath, previous);
177 + const starts = yield* Queue.unbounded<number>();
178 + const finish = yield* Queue.unbounded<void>();
179 + const writeFinished = yield* Deferred.make<void>();
180 + const compact = Effect.gen(function* () {
181 + yield* Queue.offer(starts, yield* Clock.currentTimeMillis);
182 + yield* Queue.take(finish);
183 + if (outcome === "compaction failure") {
184 + return yield* new ProjectionMaintenance.ProjectionMaintenanceError({ operation: "test" });
185 + }
186 + return emptyCompaction;
187 + });
188 + yield* Effect.gen(function* () {
189 + yield* TestClock.adjust(minute);
190 + assert.equal(yield* Queue.take(starts), startupTime + minute);
191 + yield* TestClock.adjust(2 * minute);
192 + if (outcome !== "timestamp write failure") {
193 + assert.equal(yield* fs.readFileString(timestampPath), previous);
194 + }
195 + yield* Queue.offer(finish, undefined);
196 + if (outcome !== "compaction failure") yield* Deferred.await(writeFinished);
197 + yield* TestClock.adjust(6 * hour - 1);
198 + assert.equal(yield* Queue.size(starts), 0);
199 + yield* TestClock.adjust(1);
200 + assert.equal(yield* Queue.take(starts), startupTime + 3 * minute + 6 * hour);
201 + }).pipe(
202 + Effect.provide(compactionLayer(compact)),
203 + Effect.provideService(FileSystem.FileSystem, {
204 + ...fs,
205 + writeFileString: (file, content, options) =>
206 + fs
207 + .writeFileString(file, content, options)
208 + .pipe(Effect.ensuring(Deferred.succeed(writeFinished, undefined))),
209 + }),
210 + );
211 + if (outcome !== "timestamp write failure") {
212 + const saved = Number(yield* fs.readFileString(timestampPath));
213 + assert.equal(saved, outcome === "success" ? startupTime + 3 * minute : Number(previous));
214 + }
215 + }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
216 +);
apps/server/src/persistence/DatabaseStorage.ts
+32 -8
@@ -1,7 +1,10 @@
1 import type { DatabaseStorageStatus } from "@t3tools/contracts";
2 +import * as Clock from "effect/Clock";
3 import * as Context from "effect/Context";
4 +import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Equal from "effect/Equal";
7 +import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Path from "effect/Path";
10 import * as Schedule from "effect/Schedule";
@@ -16,6 +19,7 @@ import { forkParked } from "../serverActivation.ts";
19
20 /** Pages returned per reclaim pass; one minute of churn, not a backlog. */
21 const RECLAIM_PAGES_PER_PASS = 1024;
22 +const COMPACTION_INTERVAL = Duration.hours(6);
23
24 export class DatabaseStorage extends Context.Service<
25 DatabaseStorage,
@@ -37,6 +41,7 @@ const make = Effect.gen(function* () {
41 const sql = yield* SqlClient.SqlClient;
42 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
43 const config = yield* ServerConfig.ServerConfig;
44 + const fs = yield* FileSystem.FileSystem;
45 const path = yield* Path.Path;
46 const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
47
@@ -89,21 +94,40 @@ const make = Effect.gen(function* () {
94 Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
95 );
96
92 - const compact = maintenance.compactEventStore.pipe(
93 - Effect.tap((result) =>
94 - result.deletedEventCount > 0 || result.deletedReceiptCount > 0
95 - ? Effect.logInfo("Compacted orchestration history", result)
96 - : Effect.void,
97 - ),
97 + // Even a pass that deletes nothing scans the event store. Persist completion
98 + // so restarting does not trigger another scan before the six-hour interval.
99 + const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at");
100 + const compact = Effect.gen(function* () {
101 + const result = yield* maintenance.compactEventStore;
102 + const completedAt = yield* Clock.currentTimeMillis;
103 + yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
104 + if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
105 + yield* Effect.logInfo("Compacted orchestration history", result);
106 + }
107 + }).pipe(
108 Effect.catch((cause) =>
109 Effect.logWarning("Orchestration history compaction failed", { cause }),
110 ),
111 );
112 + const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
113 + Effect.map(Number),
114 + Effect.orElseSucceed(() => Number.NaN),
115 + );
116 + const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
117 + const untilDueMs = Number.isFinite(lastCompactedAt)
118 + ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
119 + : 0;
120 + const firstCompactionDelay = Duration.millis(
121 + Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
122 + );
123
124 yield* forkParked(
104 - Effect.sleep("1 minute").pipe(
125 + Effect.sleep(firstCompactionDelay).pipe(
126 Effect.andThen(
106 - compact.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("6 hours"))),
127 + compact.pipe(
128 + Effect.andThen(publishStatus),
129 + Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
130 + ),
131 ),
132 ),
133 );