Skip to content
This repository was archived by the owner on Nov 8, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 140 additions & 5 deletions deploy/cloudflare-resident/reset.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NativeOperationJournal, nativeOperationRecordSchema, validNativeOperationKey } from "./nativeOperation.js";
import { nativeOperatorScopeClosing, nativeOperatorScopeKey } from "./nativeScope.js";
import { selectedResidentMember } from "../../src/execution/residentMembers";
import { runInNewContext } from "node:vm";
import ts from "typescript";
Expand Down Expand Up @@ -400,7 +401,7 @@ describe("archive teardown exclusion", () => {
},
);

it("discards one exact unknown restore only after confirmed runtime destruction", async () => {
it("discards exact unknown restore and refresh fetch records only after confirmed runtime destruction", async () => {
const ref = {
version: 1,
kind: "operation",
Expand Down Expand Up @@ -468,6 +469,8 @@ describe("archive teardown exclusion", () => {
NativeOperationJournal,
NATIVE_OPERATION_PREFIX: "native-operation:",
nativeOperationRecordSchema,
nativeOperatorScopeClosing,
nativeOperatorScopeKey,
CLEANUP_PENDING_KEY: "cleanup",
RESOURCE_KEY: "resource",
NATIVE_EMERGENCY_DISCARD_PREFIX: "native-emergency-discard:",
Expand Down Expand Up @@ -507,19 +510,19 @@ describe("archive teardown exclusion", () => {
resident.swapIncarnation = () => {};

await expect(resident.teardown({ key, recordHash: "0".repeat(64) })).rejects.toThrow(
"exact closed native restore changed or another hold remains (holds=1, eligible=true, hashMatch=false)",
"exact closed native operation changed or another hold remains (holds=1, eligible=true, hashMatch=false)",
);
rows.set("native-operation:op:other", structuredClone(rows.get(key)));
await expect(resident.teardown({ key, recordHash })).rejects.toThrow(
"exact closed native restore changed or another hold remains (holds=2, eligible=true, hashMatch=true)",
"exact closed native operation changed or another hold remains (holds=2, eligible=true, hashMatch=true)",
);
rows.delete("native-operation:op:other");
const ineligible = structuredClone(rows.get(key)) as { native: { closed: boolean } };
ineligible.native.closed = false;
rows.set(key, ineligible);
const ineligibleHash = (await new NativeOperationJournal(storage).list()).operations[0]!.recordHash;
await expect(resident.teardown({ key, recordHash: ineligibleHash })).rejects.toThrow(
"exact closed native restore changed or another hold remains (holds=1, eligible=false, hashMatch=true)",
"exact closed native operation changed or another hold remains (holds=1, eligible=false, hashMatch=true)",
);
rows.set(key, structuredClone(initialRows.get(key)));
expect(effects).toEqual([]);
Expand Down Expand Up @@ -642,6 +645,131 @@ describe("archive teardown exclusion", () => {
expect(rows.has(key)).toBe(true);
expect(rows.has(otherKey)).toBe(true);
expect(effects).toEqual(["destroy"]);

// A refresh fetch can retain an opaque native effect beside an opaque
// archive restore. The full reset must name both original records.
rows.clear();
for (const [name, value] of initialRows) rows.set(name, value);
const fetchKey = "native-operation:op:fetch";
const fetchScope = {
version: 1,
kind: "operation",
id: "77777777-7777-4777-8777-777777777777",
boot: ref.boot,
owner: { opOwner: "op:fetch" },
};
rows.set(fetchKey, {
opOwner: "op:fetch",
origin: {
producer: "refresh-step",
resource,
callId: "66666666-6666-4666-8666-666666666666",
sourceId: "fetch",
actor: "system",
traceId: null,
parentSourceId: "refresh_test_1",
build: "test-build",
workerVersion: null,
startedAt: 0,
},
native: {
version: 1,
closed: true,
scope: fetchScope,
pending: { "88888888-8888-4888-8888-888888888888": { kind: "opaque" } },
},
});
rows.set(nativeOperatorScopeKey({ opOwner: "op:fetch" }), {
kind: "operation",
id: fetchScope.id,
owner: fetchScope.owner,
boot: fetchScope.boot,
closing: true,
closed: false,
bootstrap: "ready",
});
const fetchHash = (await new NativeOperationJournal(storage).list()).operations.find(
(row) => row.key === fetchKey,
)!.recordHash;
const mixedTargets = [
{ key, recordHash },
{ key: fetchKey, recordHash: fetchHash, unknownEffect: { originBuild: "test-build" } },
];
effects.length = 0;
lateRecordWrite = false;
await expect(
resident.teardown([mixedTargets[0], { ...mixedTargets[1], recordHash: "0".repeat(64) }]),
).rejects.toThrow("resident-cleanup-refused");
expect(effects).toEqual([]);
await expect(
resident.teardown([
{ key, recordHash },
{ key: fetchKey, recordHash: fetchHash },
]),
).rejects.toThrow("eligible=false, hashMatch=true");
await expect(
resident.teardown([mixedTargets[0], { ...mixedTargets[1], unknownEffect: { originBuild: "other-build" } }]),
).rejects.toThrow("eligible=false, hashMatch=true");
expect(effects).toEqual([]);
const scopeKey = nativeOperatorScopeKey({ opOwner: "op:fetch" });
const originalScope = rows.get(scopeKey) as Record<string, unknown>;
rows.set(scopeKey, { ...originalScope, id: "99999999-9999-4999-8999-999999999999" });
await expect(resident.teardown(mixedTargets)).rejects.toThrow("eligible=false, hashMatch=true");
expect(effects).toEqual([]);
rows.set(scopeKey, originalScope);
rows.delete(key);
await expect(resident.teardown(mixedTargets[1])).rejects.toThrow("eligible=false, hashMatch=true");
expect(effects).toEqual([]);
rows.set(key, initialRows.get(key));
const fetchRecord = rows.get(fetchKey);
const unrelated = structuredClone(fetchRecord) as { origin: { sourceId: string } };
unrelated.origin.sourceId = "snapshot";
rows.set(fetchKey, unrelated);
const unrelatedHash = (await new NativeOperationJournal(storage).list()).operations.find(
(row) => row.key === fetchKey,
)!.recordHash;
await expect(
resident.teardown([
mixedTargets[0],
{ key: fetchKey, recordHash: unrelatedHash, unknownEffect: { originBuild: "test-build" } },
]),
).rejects.toThrow("eligible=false, hashMatch=true");
expect(effects).toEqual([]);
rows.set(fetchKey, fetchRecord);
const mixedInitialRows = new Map(rows);
destroyFails = true;
await expect(resident.teardown(mixedTargets)).rejects.toThrow("runtime destruction unconfirmed");
expect([...rows.values()]).toContainEqual(
expect.objectContaining({
key: fetchKey,
unknownEffect: { originBuild: "test-build" },
originalOperationOutcome: "unknown",
state: "prepared",
}),
);
rows.clear();
for (const [name, value] of mixedInitialRows) rows.set(name, value);
destroyFails = false;
effects.length = 0;
expect(await resident.teardown(mixedTargets)).toMatchObject({
containerStopped: true,
storageCleared: true,
discardedUnknownNatives: mixedTargets,
errors: [],
});
expect(effects).toEqual(["destroy"]);
for (const target of mixedTargets) {
expect(rows.has(target.key)).toBe(false);
expect([...rows.values()]).toContainEqual(
expect.objectContaining({
key: target.key,
recordHash: target.recordHash,
...(target.unknownEffect ? { unknownEffect: target.unknownEffect } : {}),
originalOperationOutcome: "unknown",
state: "runtime-destroyed",
}),
);
}
});
});

Expand Down Expand Up @@ -1007,13 +1135,20 @@ describe("full resident reset", () => {
expect(await invalid.json()).toEqual({ error: "one exact native key and record hash are required" });
const targets = [
{ key: "native-operation:op:archive", recordHash: "a".repeat(64) },
{ key: "native-operation:op:other", recordHash: "b".repeat(64) },
{ key: "native-operation:op:other", recordHash: "b".repeat(64), unknownEffect: { originBuild: "build-1" } },
];
const duplicate = await endpoint({}, { resource, discardUnknownNative: [targets[0], targets[0]] });
expect(duplicate.status).toBe(400);
expect(await duplicate.json()).toEqual({
error: "two to 64 distinct exact native keys and record hashes are required",
});
const missingBuild = await endpoint(
{},
{ resource, discardUnknownNative: [targets[0], { ...targets[1], unknownEffect: {} }] },
);
expect(missingBuild.status).toBe(400);
const singleUnknown = await endpoint({}, { resource, discardUnknownNative: targets[1] });
expect(singleUnknown.status).toBe(400);
const selectedPlan = await endpoint({}, { resource, dryRun: true, discardUnknownNative: targets });
expect(selectedPlan.status).toBe(200);
expect(await selectedPlan.json()).toMatchObject({ dryRun: true, originalOperationOutcome: "unknown" });
Expand Down
91 changes: 69 additions & 22 deletions deploy/cloudflare-resident/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import {
NativeRunScopes,
CloudflareNativeScopeTransport,
type NativeScopeTransport,
nativeOperatorScopeClosing,
nativeOperatorScopeKey,
nativeScopeRetirementKey,
NATIVE_SCOPE_CONTROL_MS,
type NativeScopeRef,
Expand Down Expand Up @@ -3595,7 +3597,7 @@ const DESTROY_UNCONFIRMED_KEY = "resident:destroyUnconfirmed";
const CLEANUP_PENDING_KEY = "resident:cleanupPending";
/** Retain the exact unknown-effect record after an explicitly selected full reset. */
const NATIVE_EMERGENCY_DISCARD_PREFIX = "native-emergency-discard:";
type NativeDiscardTarget = { key: string; recordHash: string };
type NativeDiscardTarget = { key: string; recordHash: string; unknownEffect?: { originBuild: string } };
type NativeDiscardSelection = NativeDiscardTarget | NativeDiscardTarget[];
const RECREATE_ADMISSION_KEY = "resident:recreateAdmission";
/** The row under RUNTIME_UNREACHABLE_KEY: the count and both instants, so the
Expand Down Expand Up @@ -15945,6 +15947,7 @@ export class ResidentDO extends Sandbox<Env> {
resource: string;
key: string;
recordHash: string;
unknownEffect?: { originBuild: string };
original: unknown;
originalOperationOutcome: string;
state: string;
Expand All @@ -15955,17 +15958,45 @@ export class ResidentDO extends Sandbox<Env> {
targets.length > 0 && unresolved.size === 0 && audits.every(({ old }) => old?.state === "runtime-destroyed");
if (targets.length) {
const hashes = await journal.fingerprints(NATIVE_OPERATION_PREFIX);
const eligible = targets.every((target) => {
const parsed = nativeOperationRecordSchema.safeParse(unresolved.get(target.key));
return (
parsed.success &&
"opOwner" in parsed.data &&
parsed.data.native.closed === true &&
!!parsed.data.native.scope &&
Object.values(parsed.data.native.pending).some((attempt) => attempt.restore) &&
!Object.values(parsed.data.native.pending).some((attempt) => !attempt.restore)
);
});
const eligible = (
await Promise.all(
targets.map(async (target) => {
const parsed = nativeOperationRecordSchema.safeParse(unresolved.get(target.key));
if (!parsed.success || !("opOwner" in parsed.data)) return false;
const record = parsed.data;
const pending = Object.values(record.native.pending);
// The journal cannot name the opaque effect. The operator must select
// its original build explicitly and keep its result unknown.
const unknownFetch =
targets.length >= 2 &&
!!target.unknownEffect &&
target.unknownEffect.originBuild === record.origin?.build &&
target.key === `native-operation:${record.opOwner}` &&
!!record.native.scope &&
nativeOperatorScopeClosing(
await this.ctx.storage.get(nativeOperatorScopeKey({ opOwner: record.opOwner })),
{ opOwner: record.opOwner },
record.native.scope,
) &&
record.origin?.producer === "refresh-step" &&
record.origin.resource === resource &&
record.origin.sourceId === "fetch" &&
record.origin.actor === "system" &&
pending.length === 1 &&
pending[0].kind === "opaque" &&
!pending[0].process &&
!pending[0].restore;
return (
record.native.closed === true &&
!!record.native.scope &&
(unknownFetch ||
(!target.unknownEffect &&
pending.some((attempt) => attempt.restore) &&
!pending.some((attempt) => !attempt.restore)))
);
}),
)
).every(Boolean);
const hashMatch = targets.every((target) => hashes[target.key] === target.recordHash);
if (
!resumeWithoutRecord &&
Expand All @@ -15976,7 +16007,7 @@ export class ResidentDO extends Sandbox<Env> {
!hashMatch)
)
throw new Error(
`resident-cleanup-refused: exact closed native restore changed or another hold remains (holds=${unresolved.size}, eligible=${eligible}, hashMatch=${hashMatch})`,
`resident-cleanup-refused: exact closed native operation changed or another hold remains (holds=${unresolved.size}, eligible=${eligible}, hashMatch=${hashMatch})`,
);
}
for (const [key, value] of unresolved) {
Expand All @@ -15996,6 +16027,7 @@ export class ResidentDO extends Sandbox<Env> {
(old.resource !== resource ||
old.key !== target.key ||
old.recordHash !== target.recordHash ||
JSON.stringify(old.unknownEffect ?? null) !== JSON.stringify(target.unknownEffect ?? null) ||
old.original === undefined ||
old.originalOperationOutcome !== "unknown" ||
!["prepared", "runtime-destroyed"].includes(old.state)),
Expand Down Expand Up @@ -16024,6 +16056,7 @@ export class ResidentDO extends Sandbox<Env> {
resource,
key: target.key,
recordHash: target.recordHash,
...(target.unknownEffect ? { unknownEffect: target.unknownEffect } : {}),
original: current.get(target.key),
originalOperationOutcome: "unknown",
state: "prepared",
Expand All @@ -16043,6 +16076,7 @@ export class ResidentDO extends Sandbox<Env> {
resource,
key: target.key,
recordHash: target.recordHash,
...(target.unknownEffect ? { unknownEffect: target.unknownEffect } : {}),
original: current.get(target.key),
originalOperationOutcome: "unknown",
state: "runtime-destroyed",
Expand Down Expand Up @@ -17257,21 +17291,34 @@ async function handleReset(env: Env, body: Record<string, unknown>): Promise<Res
if (body.dryRun !== undefined && typeof body.dryRun !== "boolean")
return json({ error: "dryRun must be a boolean" }, 400);
const discard = body.discardUnknownNative;
const validDiscardTarget = (value: unknown): value is NativeDiscardTarget =>
!!value &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value).sort().join(",") === "key,recordHash" &&
validNativeOperationKey((value as { key?: unknown }).key) &&
typeof (value as { recordHash?: unknown }).recordHash === "string" &&
/^[a-f0-9]{64}$/.test((value as { recordHash: string }).recordHash);
const validDiscardTarget = (value: unknown): value is NativeDiscardTarget => {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const target = value as { key?: unknown; recordHash?: unknown; unknownEffect?: unknown };
const keys = Object.keys(value).sort().join(",");
if (
!validNativeOperationKey(target.key) ||
typeof target.recordHash !== "string" ||
!/^[a-f0-9]{64}$/.test(target.recordHash)
)
return false;
if (keys === "key,recordHash") return true;
if (keys !== "key,recordHash,unknownEffect" || !target.unknownEffect || typeof target.unknownEffect !== "object")
return false;
const unknownEffect = target.unknownEffect as { originBuild?: unknown };
return (
Object.keys(unknownEffect).join(",") === "originBuild" &&
typeof unknownEffect.originBuild === "string" &&
unknownEffect.originBuild.length > 0 &&
unknownEffect.originBuild.length <= 128
);
};
const validDiscard = Array.isArray(discard)
? discard.length >= 2 &&
discard.length <= 64 &&
discard.every(validDiscardTarget) &&
new Set(discard.map((target: NativeDiscardTarget) => target.key)).size === discard.length &&
new Set(discard.map((target: NativeDiscardTarget) => target.recordHash)).size === discard.length
: validDiscardTarget(discard);
: validDiscardTarget(discard) && !discard.unknownEffect;
if (discard !== undefined && !validDiscard)
return json(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Keep Kill scoped to one run. Do not use a full resident reset as its automatic f

The one-record rule protects exact selection, unknown outcomes and the original archive evidence. It does not handle two closed opaque restores on one resident: neither single-record selector can pass the other hold. Keep the same full-reset boundary and allow a complete set of two to 64 exact key and hash pairs. The Worker rejects any omitted, duplicate, changed or ineligible record before destruction. It writes all prepared audits in one storage transaction, confirms one runtime destruction, and writes all destruction audits in one transaction. The hardest race is a late original restore reply during backup cleanup. The final transaction compares every selected record and removes the set only when all hashes still match; one changed record leaves the whole set in place. An uncertain destroy or mixed audit state still refuses a repeat. This extension retains the original reason for the decision: no result is credited to an opaque restore, and no runtime evidence is deleted without confirmed destruction.

## Amended 2026-10-23

The complete-set guard can meet a closed refresh fetch beside a closed dependency restore. The fetch can retain an opaque native effect with no process handle or restore identity. A process Kill has no identity to target, and the journal does not identify the action or destination. Admit that fetch only inside a complete set through a new explicit unknown-effect selection that quotes its original build and exact key and hash. The Worker checks the selected build, system `refresh-step`/`fetch` origin, resource, one pending opaque non-restore effect, and the embedded scope against the original closing scope row. Every other opaque non-restore record stays ineligible. This is deliberate disposal of unknown evidence after a full resident reset, not proof that the fetch effect was local or ended. The reset still requires the complete exact set, confirms container destruction, and retains each original and its unknown-effect selection in the audit. After backup cleanup, one transaction checks all selected hashes and the whole unresolved count, so a late reply or new record leaves the set in place. The original reason for the decision still applies: no unknown result is credited, and no resident state is removed without confirmed destruction. A remote effect may survive, and a separate deployment permit remains a separate obligation.

## Consequences

The explicit mode deletes every workspace, thread binding and backup on that resident. It does not prove the original restore ended or repair remote effects. An older Worker cannot run the mode. The deployment fence still refuses until the hold is removed, so a separate qualified installation path is required before this mode can resolve a hold on an older serving Worker.
Expand Down
Loading