|
| 1 | +import { once } from "node:events"; |
| 2 | +import type { Worker } from "node:worker_threads"; |
| 3 | +import { afterEach, describe, expect, it } from "vitest"; |
| 4 | +import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js"; |
| 5 | +import { |
| 6 | + closeOpenClawStateDatabaseForTest, |
| 7 | + openOpenClawStateDatabase, |
| 8 | + runOpenClawStateWriteTransaction, |
| 9 | +} from "./openclaw-state-db.js"; |
| 10 | +import { withOpenClawStateLease, type OpenClawStateLeaseContext } from "./openclaw-state-lease.js"; |
| 11 | + |
| 12 | +function block(ms: number) { |
| 13 | + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); |
| 14 | +} |
| 15 | + |
| 16 | +function options(env: NodeJS.ProcessEnv, signal?: AbortSignal) { |
| 17 | + return { |
| 18 | + scope: "core:test-maintenance", |
| 19 | + key: "maintenance", |
| 20 | + database: { scope: "shared" as const, options: { env } }, |
| 21 | + leaseMs: 1_000, |
| 22 | + waitMs: 0, |
| 23 | + heartbeat: "worker" as const, |
| 24 | + signal, |
| 25 | + }; |
| 26 | +} |
| 27 | + |
| 28 | +function readLease(env: NodeJS.ProcessEnv) { |
| 29 | + return openOpenClawStateDatabase({ env }) |
| 30 | + .db.prepare( |
| 31 | + "SELECT owner, expires_at, heartbeat_at FROM state_leases WHERE scope = ? AND lease_key = ?", |
| 32 | + ) |
| 33 | + .get("core:test-maintenance", "maintenance"); |
| 34 | +} |
| 35 | + |
| 36 | +afterEach(() => { |
| 37 | + closeOpenClawStateDatabaseForTest(); |
| 38 | +}); |
| 39 | + |
| 40 | +describe("maintenance lease heartbeat", () => { |
| 41 | + it("retains ownership while synchronous maintenance exceeds the lease duration", async () => { |
| 42 | + await withOpenClawTestState({ label: "maintenance-lease-blocked" }, async (state) => { |
| 43 | + await withOpenClawStateLease(options(state.env), async (lease) => { |
| 44 | + block(1_250); |
| 45 | + expect(() => lease.renew?.()).not.toThrow(); |
| 46 | + expect(() => lease.assertOwned()).not.toThrow(); |
| 47 | + expect(lease.signal.aborted).toBe(false); |
| 48 | + }); |
| 49 | + }); |
| 50 | + }); |
| 51 | + |
| 52 | + it("acknowledges ownership checks while the parent holds a state write transaction", async () => { |
| 53 | + await withOpenClawTestState({ label: "maintenance-lease-transaction" }, async (state) => { |
| 54 | + await withOpenClawStateLease(options(state.env), async (lease) => { |
| 55 | + runOpenClawStateWriteTransaction( |
| 56 | + ({ db }) => { |
| 57 | + lease.assertOwnedInTransaction(db); |
| 58 | + block(450); |
| 59 | + lease.assertOwnedInTransaction(db); |
| 60 | + }, |
| 61 | + { env: state.env }, |
| 62 | + ); |
| 63 | + }); |
| 64 | + }); |
| 65 | + }); |
| 66 | + |
| 67 | + it("rejects a terminated worker before its queued exit event reaches the parent", async () => { |
| 68 | + await withOpenClawTestState({ label: "maintenance-lease-worker-loss" }, async (state) => { |
| 69 | + const spawned = once(process, "worker") as Promise<[Worker]>; |
| 70 | + await expect( |
| 71 | + withOpenClawStateLease({ ...options(state.env), leaseMs: 10_000 }, async (lease) => { |
| 72 | + const [worker] = await spawned; |
| 73 | + void worker.terminate(); |
| 74 | + block(100); |
| 75 | + expect(Number(readLease(state.env)?.expires_at)).toBeGreaterThan(Date.now()); |
| 76 | + expect(() => lease.assertOwned()).toThrowError( |
| 77 | + expect.objectContaining({ code: "OPENCLAW_STATE_LEASE_LOST" }), |
| 78 | + ); |
| 79 | + // The database alone still grants the old lease: only fresh worker |
| 80 | + // liveness can reject this assertion before the queued exit callback. |
| 81 | + expect(Number(readLease(state.env)?.expires_at)).toBeGreaterThan(Date.now()); |
| 82 | + }), |
| 83 | + ).rejects.toMatchObject({ code: "OPENCLAW_STATE_LEASE_LOST" }); |
| 84 | + expect(readLease(state.env)).toBeUndefined(); |
| 85 | + }); |
| 86 | + }); |
| 87 | + |
| 88 | + it("does not enter maintenance when its heartbeat exits before readiness", async () => { |
| 89 | + await withOpenClawTestState({ label: "maintenance-lease-startup-loss" }, async (state) => { |
| 90 | + const terminate = (worker: Worker) => { |
| 91 | + void worker.terminate(); |
| 92 | + }; |
| 93 | + process.once("worker", terminate); |
| 94 | + let entered = false; |
| 95 | + try { |
| 96 | + await expect( |
| 97 | + withOpenClawStateLease(options(state.env), async () => { |
| 98 | + entered = true; |
| 99 | + }), |
| 100 | + ).rejects.toMatchObject({ code: "OPENCLAW_STATE_LEASE_LOST" }); |
| 101 | + expect(entered).toBe(false); |
| 102 | + expect(readLease(state.env)).toBeUndefined(); |
| 103 | + } finally { |
| 104 | + process.removeListener("worker", terminate); |
| 105 | + } |
| 106 | + }); |
| 107 | + }); |
| 108 | + |
| 109 | + it.each(["replacement", "expiry", "deletion"] as const)( |
| 110 | + "does not resurrect ownership after %s", |
| 111 | + async (failure) => { |
| 112 | + await withOpenClawTestState({ label: `maintenance-lease-${failure}` }, async (state) => { |
| 113 | + let changed: ReturnType<typeof readLease>; |
| 114 | + await expect( |
| 115 | + withOpenClawStateLease(options(state.env), async (lease) => { |
| 116 | + runOpenClawStateWriteTransaction( |
| 117 | + ({ db }) => { |
| 118 | + if (failure === "deletion") { |
| 119 | + db.prepare("DELETE FROM state_leases WHERE scope = ?").run( |
| 120 | + "core:test-maintenance", |
| 121 | + ); |
| 122 | + } else { |
| 123 | + db.prepare( |
| 124 | + `UPDATE state_leases SET ${failure === "replacement" ? "owner = 'successor'" : "expires_at = 0"} WHERE scope = ?`, |
| 125 | + ).run("core:test-maintenance"); |
| 126 | + } |
| 127 | + }, |
| 128 | + { env: state.env }, |
| 129 | + ); |
| 130 | + changed = readLease(state.env); |
| 131 | + block(450); |
| 132 | + expect(() => lease.assertOwned()).toThrowError( |
| 133 | + expect.objectContaining({ code: "OPENCLAW_STATE_LEASE_LOST" }), |
| 134 | + ); |
| 135 | + expect(readLease(state.env)).toEqual(changed); |
| 136 | + }), |
| 137 | + ).rejects.toMatchObject({ code: "OPENCLAW_STATE_LEASE_LOST" }); |
| 138 | + expect(readLease(state.env)).toEqual(failure === "replacement" ? changed : undefined); |
| 139 | + }); |
| 140 | + }, |
| 141 | + ); |
| 142 | + |
| 143 | + it.each(["return", "throw", "abort"] as const)( |
| 144 | + "stops renewal and retained callbacks when an operation ends by %s", |
| 145 | + async (ending) => { |
| 146 | + await withOpenClawTestState({ label: `maintenance-lease-${ending}` }, async (state) => { |
| 147 | + const controller = new AbortController(); |
| 148 | + const spawned = once(process, "worker") as Promise<[Worker]>; |
| 149 | + let retained: OpenClawStateLeaseContext | undefined; |
| 150 | + const operation = withOpenClawStateLease( |
| 151 | + options(state.env, controller.signal), |
| 152 | + async (lease) => { |
| 153 | + retained = lease; |
| 154 | + if (ending === "abort") { |
| 155 | + controller.abort(); |
| 156 | + const stopped = readLease(state.env); |
| 157 | + await new Promise((resolve) => { |
| 158 | + setTimeout(resolve, 450); |
| 159 | + }); |
| 160 | + expect(readLease(state.env)).toEqual(stopped); |
| 161 | + } else if (ending === "throw") { |
| 162 | + throw new Error("operation failed"); |
| 163 | + } |
| 164 | + return "completed"; |
| 165 | + }, |
| 166 | + ); |
| 167 | + if (ending === "return") { |
| 168 | + await expect(operation).resolves.toBe("completed"); |
| 169 | + } else { |
| 170 | + await expect(operation).rejects.toThrow( |
| 171 | + ending === "throw" ? "operation failed" : "was aborted", |
| 172 | + ); |
| 173 | + } |
| 174 | + const [worker] = await spawned; |
| 175 | + expect(worker.threadId).toBe(-1); |
| 176 | + expect(readLease(state.env)).toBeUndefined(); |
| 177 | + expect(retained).toBeDefined(); |
| 178 | + expect(() => retained?.assertOwned()).toThrow(); |
| 179 | + expect(() => retained?.renew?.()).toThrow(); |
| 180 | + }); |
| 181 | + }, |
| 182 | + ); |
| 183 | +}); |
0 commit comments