Skip to content

Commit eee9059

Browse files
VACIncsteipete
andauthored
fix(state): keep divergent retired device identity from blocking gateway readiness (#126748)
* fix(state): keep divergent retired device identity from blocking gateway readiness Classify a divergent retired identity file as a startup notice when the canonical SQLite identity remains valid and authoritative under #120610. Preserve the fatal warning for missing or invalid canonical state, so the readiness gate itself remains unchanged. Fixes #117270. Release note: prevents gateway crash loops caused by a recreated retired device identity JSON after a verified SQLite migration. * 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]> --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent 89bb601 commit eee9059

4 files changed

Lines changed: 103 additions & 4 deletions

File tree

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

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,58 @@ describe("legacy device identity Doctor migration", () => {
708708
expect(receipt(env)).toMatchObject({ removed_source: 1 });
709709
});
710710

711-
it("does not discard recreated bytes that differ from the receipt", async () => {
711+
it("preserves a divergent recreated identity as a boot-safe notice while the canonical row is valid", async () => {
712+
const { env, stateDir } = useStateDir();
713+
const sourcePath = await writeLegacy({ stateDir });
714+
await migrate(stateDir, env, {
715+
removeSource: () => {
716+
throw new Error("simulated unlink failure");
717+
},
718+
});
719+
const divergent = anotherIdentity();
720+
const replacement = `${JSON.stringify({
721+
version: 1,
722+
deviceId: divergent.deviceId,
723+
publicKeyPem: divergent.publicKeyPem,
724+
privateKeyPem: divergent.privateKeyPem,
725+
createdAtMs: divergent.createdAtMs,
726+
})}\n`;
727+
await fsp.writeFile(sourcePath, replacement, "utf8");
728+
729+
closeOpenClawStateDatabaseForTest();
730+
const retry = await migrate(stateDir, env);
731+
732+
// The startup readiness gate hard-fails on any migration warning, so this exact
733+
// classification is what keeps a divergent inert file from crash-looping the gateway.
734+
expect(retry.warnings).toEqual([]);
735+
expect(retry.notices?.join("\n")).toContain("canonical SQLite identity remains authoritative");
736+
await expect(fsp.readFile(sourcePath, "utf8")).resolves.toBe(replacement);
737+
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 });
760+
});
761+
762+
it("keeps the divergent-file warning fatal when the canonical row is invalid", async () => {
712763
const { env, stateDir } = useStateDir();
713764
const sourcePath = await writeLegacy({ stateDir });
714765
await migrate(stateDir, env, {
@@ -718,13 +769,21 @@ describe("legacy device identity Doctor migration", () => {
718769
});
719770
const replacement = `${JSON.stringify({ ...nodeIdentity(), createdAtMs: CREATED_AT_MS + 1 })}\n`;
720771
await fsp.writeFile(sourcePath, replacement, "utf8");
772+
const db = database(env);
773+
executeSqliteQuerySync(
774+
db,
775+
getNodeSqliteKysely<MigrationDatabase>(db)
776+
.updateTable("device_identities")
777+
.set({ public_key_pem: "invalid-public-key", private_key_pem: "invalid-private-key" })
778+
.where("identity_key", "=", "primary"),
779+
);
721780

722781
closeOpenClawStateDatabaseForTest();
723782
const retry = await migrate(stateDir, env);
724783

725784
expect(retry.warnings.join("\n")).toContain("bytes differ from the migration receipt");
785+
expect(retry.notices ?? []).toEqual([]);
726786
await expect(fsp.readFile(sourcePath, "utf8")).resolves.toBe(replacement);
727-
expect(identityRow(env)?.created_at_ms).toBe(CREATED_AT_MS);
728787
});
729788

730789
it("rejects symlinked, hardlinked, oversized, non-UTF-8, and invalid sources", async () => {

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

Lines changed: 22 additions & 2 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,
@@ -316,6 +317,7 @@ async function cleanupReceiptSources(params: {
316317
}
317318
const changes: string[] = [];
318319
const warnings: string[] = [];
320+
const notices: string[] = [];
319321
let removed = 0;
320322
for (const candidate of [params.detected.sourcePath, params.detected.claimPath]) {
321323
if (!(await params.stateRoot.exists(relativeLegacyPath(params.stateDir, candidate)))) {
@@ -333,6 +335,18 @@ async function cleanupReceiptSources(params: {
333335
continue;
334336
}
335337
if (snapshot.sha256 !== params.receipt.sourceSha256) {
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.
349+
}
336350
warnings.push(
337351
`Retired device identity cleanup preserved ${candidate}: bytes differ from the migration receipt.`,
338352
);
@@ -346,13 +360,19 @@ async function cleanupReceiptSources(params: {
346360
warnings.push(`Retired device identity cleanup failed for ${candidate}: ${String(error)}`);
347361
}
348362
}
349-
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+
) {
350370
markLegacyMigrationSourceRemoved(params.receipt.sourceKey, params.env);
351371
}
352372
if (removed > 0) {
353373
changes.push("Removed retired device identity JSON covered by its SQLite receipt.");
354374
}
355-
return { changes, warnings };
375+
return { changes, warnings, notices };
356376
}
357377

358378
async function migrateWithExclusiveStateOwnership(params: {

‎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);

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ async function reportMigration(
2626
for (const change of result?.changes ?? []) {
2727
log.info(change);
2828
}
29+
for (const notice of result?.notices ?? []) {
30+
log.info(notice);
31+
}
2932
for (const warning of result?.warnings ?? []) {
3033
log.warn(warning);
3134
}

0 commit comments

Comments
 (0)