Skip to content

Commit be71261

Browse files
committed
fix(state): renew maintenance before v17 preflight
1 parent ec15b0b commit be71261

2 files changed

Lines changed: 104 additions & 1 deletion

File tree

‎src/infra/state-migrations.media-persistence.additive-schema.test.ts‎

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import { afterEach, describe, expect, it } from "vitest";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
22
import { cleanupTempDirs, makeTempDir } from "../../test/helpers/temp-dir.js";
33
import { AGENT_MEDIA_SCHEMA_VERSION } from "../state/openclaw-agent-db-contract.js";
4+
import * as agentDatabaseLease from "../state/openclaw-agent-db-lease.js";
5+
import * as sessionMigrations from "../state/openclaw-agent-db-session-migrations.js";
46
import {
57
closeOpenClawAgentDatabasesForTest,
68
OPENCLAW_AGENT_SCHEMA_VERSION,
@@ -39,6 +41,8 @@ function createV17AdditiveFixture(options: { schemaDrift?: "missing-cache-table"
3941

4042
describe("legacy media persistence additive schema repair", () => {
4143
afterEach(() => {
44+
vi.useRealTimers();
45+
vi.restoreAllMocks();
4246
closeOpenClawAgentDatabasesForTest();
4347
closeOpenClawStateDatabaseForTest();
4448
cleanupTempDirs(tempDirs);
@@ -131,6 +135,104 @@ describe("legacy media persistence additive schema repair", () => {
131135
}
132136
});
133137

138+
it("renews maintenance before the v17 validity projection preflight", async () => {
139+
vi.useFakeTimers();
140+
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
141+
const stateDir = makeTempDir(tempDirs, "media-persistence-v17-lease-renewal-");
142+
const env = { OPENCLAW_STATE_DIR: stateDir };
143+
const opened = openOpenClawAgentDatabase({ agentId: "main", env });
144+
const databasePath = opened.path;
145+
opened.db
146+
.prepare(
147+
`INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at)
148+
VALUES (?, ?, ?, ?)`,
149+
)
150+
.run(
151+
"agent:main:v17-lease-renewal",
152+
"v17-lease-renewal",
153+
JSON.stringify({ sessionId: "v17-lease-renewal", updatedAt: 1 }),
154+
1,
155+
);
156+
closeOpenClawAgentDatabasesForTest();
157+
closeOpenClawStateDatabaseForTest();
158+
159+
const { DatabaseSync } = requireNodeSqlite();
160+
const database = new DatabaseSync(databasePath);
161+
try {
162+
database.exec(`
163+
DROP TABLE session_participants;
164+
DROP TRIGGER session_conversations_route_context_invalidate_after_update;
165+
DROP INDEX idx_agent_session_conversations_conversation;
166+
ALTER TABLE session_conversations DROP COLUMN route_context_json;
167+
DROP TRIGGER session_nodes_entry_valid_after_insert;
168+
DROP TRIGGER session_nodes_entry_valid_after_entry_update;
169+
DROP TRIGGER session_nodes_entry_valid_after_identity_update;
170+
DROP INDEX idx_agent_session_nodes_entry_valid_pending;
171+
DROP TABLE session_key_contract;
172+
ALTER TABLE session_nodes DROP COLUMN entry_valid;
173+
PRAGMA user_version = ${AGENT_MEDIA_SCHEMA_VERSION};
174+
UPDATE schema_meta
175+
SET schema_version = ${AGENT_MEDIA_SCHEMA_VERSION}
176+
WHERE meta_key = 'primary';
177+
`);
178+
} finally {
179+
database.close();
180+
}
181+
182+
const events: string[] = [];
183+
const originalAuthorityCheck = agentDatabaseLease.assertAgentDatabaseMaintenanceAuthority;
184+
let firstAuthorityCheck = true;
185+
vi.spyOn(agentDatabaseLease, "assertAgentDatabaseMaintenanceAuthority").mockImplementation(
186+
() => {
187+
originalAuthorityCheck();
188+
if (firstAuthorityCheck) {
189+
firstAuthorityCheck = false;
190+
// Leave less than one lease interval before the v17 preflight starts.
191+
vi.setSystemTime(Date.now() + 59_000);
192+
}
193+
},
194+
);
195+
const originalRenew = agentDatabaseLease.renewAgentDatabaseMaintenanceAuthorityIfPresent;
196+
vi.spyOn(
197+
agentDatabaseLease,
198+
"renewAgentDatabaseMaintenanceAuthorityIfPresent",
199+
).mockImplementation(() => {
200+
events.push("renew");
201+
originalRenew();
202+
});
203+
const originalProjection = sessionMigrations.ensureSessionEntryValidityProjection;
204+
let projectionCalls = 0;
205+
vi.spyOn(sessionMigrations, "ensureSessionEntryValidityProjection").mockImplementation((db) => {
206+
projectionCalls += 1;
207+
if (projectionCalls === 1) {
208+
events.push("v17-preflight");
209+
// The real projection is synchronous, so the heartbeat cannot run here.
210+
vi.setSystemTime(Date.now() + 2_000);
211+
}
212+
originalProjection(db);
213+
});
214+
215+
const result = await migrateLegacyMediaPersistence({ env });
216+
217+
expect(result.warnings).toEqual([]);
218+
expect(events.slice(0, 2)).toEqual(["renew", "v17-preflight"]);
219+
expect(projectionCalls).toBeGreaterThanOrEqual(1);
220+
closeOpenClawAgentDatabasesForTest();
221+
const repaired = new DatabaseSync(databasePath, { readOnly: true });
222+
try {
223+
expect(repaired.prepare("PRAGMA user_version").get()).toEqual({
224+
user_version: OPENCLAW_AGENT_SCHEMA_VERSION,
225+
});
226+
expect(
227+
repaired
228+
.prepare("SELECT entry_valid FROM session_nodes WHERE session_key = ?")
229+
.get("agent:main:v17-lease-renewal"),
230+
).toEqual({ entry_valid: 1 });
231+
} finally {
232+
repaired.close();
233+
}
234+
});
235+
134236
it("rolls back v17 additive preflight when canonical validation rejects drift", async () => {
135237
const stateDir = makeTempDir(tempDirs, "media-persistence-v17-rollback-");
136238
const env = { OPENCLAW_STATE_DIR: stateDir };

‎src/state/openclaw-agent-db-schema.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,7 @@ function ensureAgentSchema(
587587
}
588588
migrateRetiredAgentStateLeaseSchema(db, pathname, targetVersion);
589589
if (previousVersion === AGENT_MEDIA_SCHEMA_VERSION) {
590+
maintenanceAuthority.renewAgentDatabaseMaintenanceAuthorityIfPresent();
590591
ensureOpenClawAgentV17MediaPreflightInTransaction(db, { agentId, pathname });
591592
}
592593
if (previousVersion === targetVersion) {

0 commit comments

Comments
 (0)