Skip to content

Commit 5ff8721

Browse files
steipeteVACInc
andcommitted
fix(state): preserve device identity migration receipt integrity
Reuse canonical SQLite identity validation and retain incomplete receipts for preserved divergent claims. Co-authored-by: Vito Cappello <[email protected]>
1 parent a7b423d commit 5ff8721

3 files changed

Lines changed: 61 additions & 27 deletions

File tree

‎src/infra/state-migrations.device-identity.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,28 @@ describe("legacy device identity Doctor migration", () => {
735735
expect(retry.notices?.join("\n")).toContain("canonical SQLite identity remains authoritative");
736736
await expect(fsp.readFile(sourcePath, "utf8")).resolves.toBe(replacement);
737737
expect(identityRow(env)?.created_at_ms).toBe(CREATED_AT_MS);
738+
expect(receipt(env)).toMatchObject({ removed_source: 1 });
739+
});
740+
741+
it("does not mark a divergent preserved claim as removed", async () => {
742+
const { env, stateDir } = useStateDir();
743+
const sourcePath = await writeLegacy({ stateDir });
744+
await migrate(stateDir, env, {
745+
removeSource: () => {
746+
throw new Error("simulated unlink failure");
747+
},
748+
});
749+
const claimPath = `${sourcePath}.doctor-importing`;
750+
const replacement = `${JSON.stringify({ version: 1, ...anotherIdentity() })}\n`;
751+
await fsp.writeFile(claimPath, replacement, "utf8");
752+
753+
closeOpenClawStateDatabaseForTest();
754+
const retry = await migrate(stateDir, env);
755+
756+
expect(retry.warnings).toEqual([]);
757+
expect(retry.notices?.join("\n")).toContain("canonical SQLite identity remains authoritative");
758+
await expect(fsp.readFile(claimPath, "utf8")).resolves.toBe(replacement);
759+
expect(receipt(env)).toMatchObject({ removed_source: 0 });
738760
});
739761

740762
it("keeps the divergent-file warning fatal when the canonical row is invalid", async () => {

‎src/infra/state-migrations.device-identity.ts‎

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
type NormalizedLegacyDeviceIdentity,
1212
} from "./device-identity-legacy.js";
1313
import {
14+
readStoredDeviceIdentityReadOnly,
1415
resolveDeviceIdentityStore,
1516
validateStoredDeviceIdentity,
1617
type DeviceIdentity,
@@ -165,20 +166,6 @@ function verifyCanonicalIdentity(
165166
}
166167
}
167168

168-
/** A valid canonical row keeps runtime identity authoritative over retired JSON (#120610). */
169-
function canonicalRowIsValid(
170-
identity: NormalizedLegacyDeviceIdentity,
171-
env: NodeJS.ProcessEnv,
172-
): boolean {
173-
try {
174-
const { db } = openOpenClawStateDatabase({ env });
175-
const row = readCanonicalIdentity(db);
176-
return row !== undefined && classifyCanonicalRow(row, identity) !== "invalid";
177-
} catch {
178-
return false;
179-
}
180-
}
181-
182169
function importAndRecordReceipt(params: {
183170
env: NodeJS.ProcessEnv;
184171
sourcePath: string;
@@ -348,19 +335,21 @@ async function cleanupReceiptSources(params: {
348335
continue;
349336
}
350337
if (snapshot.sha256 !== params.receipt.sourceSha256) {
351-
// #120610 made the canonical SQLite row authoritative over retired JSON, so a
352-
// divergent preserved file is inert while that row is valid. A warning here trips
353-
// the startup-migration readiness gate and crash-loops the gateway over a file
354-
// runtime never reads; only a missing/invalid canonical row keeps this fatal.
355-
if (canonicalRowIsValid(snapshot.identity, params.env)) {
356-
notices.push(
357-
`Preserved retired device identity ${candidate}: bytes differ from the migration receipt; the canonical SQLite identity remains authoritative. Archive or delete the file to clear this notice.`,
358-
);
359-
} else {
360-
warnings.push(
361-
`Retired device identity cleanup preserved ${candidate}: bytes differ from the migration receipt.`,
362-
);
338+
// SQLite owns runtime identity; warning about inert retired bytes would
339+
// make startup refuse an otherwise healthy gateway.
340+
try {
341+
if (readStoredDeviceIdentityReadOnly({ env: params.env, identityKey: IDENTITY_KEY })) {
342+
notices.push(
343+
`Preserved retired device identity ${candidate}: bytes differ from the migration receipt; the canonical SQLite identity remains authoritative. Archive or delete the file to clear this notice.`,
344+
);
345+
continue;
346+
}
347+
} catch {
348+
// Invalid canonical identity must retain its readiness-blocking warning.
363349
}
350+
warnings.push(
351+
`Retired device identity cleanup preserved ${candidate}: bytes differ from the migration receipt.`,
352+
);
364353
continue;
365354
}
366355
try {
@@ -371,7 +360,13 @@ async function cleanupReceiptSources(params: {
371360
warnings.push(`Retired device identity cleanup failed for ${candidate}: ${String(error)}`);
372361
}
373362
}
374-
if (warnings.length === 0 && (!params.receipt.removedSource || removed > 0)) {
363+
// A divergent preserved claim cannot complete its interrupted receipt unless
364+
// receipt-covered original bytes were actually removed during this pass.
365+
if (
366+
warnings.length === 0 &&
367+
(!params.receipt.removedSource || removed > 0) &&
368+
(notices.length === 0 || removed > 0)
369+
) {
375370
markLegacyMigrationSourceRemoved(params.receipt.sourceKey, params.env);
376371
}
377372
if (removed > 0) {

‎src/node-host/startup-state-migrations.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,23 @@ describe("node-host startup state migrations", () => {
128128
expect(log.warn).not.toHaveBeenCalled();
129129
});
130130

131+
it("reports a recreated divergent identity as a notice while preserving the canonical identity", async () => {
132+
const { env, stateDir } = useStateDir();
133+
const { deviceId } = await writeDeviceIdentity(stateDir);
134+
await runStartupMigrations({ env, log });
135+
vi.clearAllMocks();
136+
137+
const { sourcePath } = await writeDeviceIdentity(stateDir);
138+
await runStartupMigrations({ env, log });
139+
140+
expect(fs.existsSync(sourcePath)).toBe(true);
141+
expect(loadDeviceIdentityIfPresent({ env })?.deviceId).toBe(deviceId);
142+
expect(log.info).toHaveBeenCalledWith(
143+
expect.stringContaining("canonical SQLite identity remains authoritative"),
144+
);
145+
expect(log.warn).not.toHaveBeenCalled();
146+
});
147+
131148
it("preserves a pending native device identity claim and continues", async () => {
132149
const { env, stateDir } = useStateDir();
133150
const { sourcePath } = await writeDeviceIdentity(stateDir);

0 commit comments

Comments
 (0)