Skip to content

Commit 417f3ac

Browse files
authored
fix(cron): isolated heartbeat recovers after session archival (#120314)
* fix(cron): recover archived heartbeat sessions * fix(cron): preserve heartbeat initialization guard
1 parent 3a45060 commit 417f3ac

3 files changed

Lines changed: 108 additions & 5 deletions

File tree

‎src/cron/isolated-agent/session.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,60 @@ describe("resolveCronSession", () => {
167167
expect(clearBootstrapSnapshot).not.toHaveBeenCalled();
168168
});
169169

170+
it("rolls an archived isolated heartbeat session into a fresh run", () => {
171+
const result = resolveWithStoredEntry({
172+
sessionKey: "agent:main:main:heartbeat",
173+
entry: {
174+
sessionId: "archived-heartbeat-session-id",
175+
updatedAt: NOW_MS - 1000,
176+
archivedAt: NOW_MS,
177+
heartbeatIsolatedBaseSessionKey: "agent:main:main",
178+
},
179+
forceNew: true,
180+
});
181+
182+
expect(result.isNewSession).toBe(true);
183+
expect(result.previousSessionId).toBe("archived-heartbeat-session-id");
184+
expect(result.sessionEntry.sessionId).not.toBe("archived-heartbeat-session-id");
185+
expect(result.sessionEntry.archivedAt).toBeUndefined();
186+
expect(result.sessionEntry.heartbeatIsolatedBaseSessionKey).toBeUndefined();
187+
});
188+
189+
it("keeps an initializing isolated heartbeat blocked during forced rollover", () => {
190+
expect(() =>
191+
resolveWithStoredEntry({
192+
sessionKey: "agent:main:main:heartbeat",
193+
entry: {
194+
sessionId: "initializing-heartbeat-session-id",
195+
updatedAt: NOW_MS - 1000,
196+
archivedAt: NOW_MS,
197+
initializationPending: true,
198+
heartbeatIsolatedBaseSessionKey: "agent:main:main",
199+
},
200+
forceNew: true,
201+
}),
202+
).toThrow(
203+
'Session "agent:main:main:heartbeat" is still initializing. Retry after initialization completes.',
204+
);
205+
expect(clearBootstrapSnapshot).not.toHaveBeenCalled();
206+
});
207+
208+
it("keeps an archived isolated heartbeat read-only without forceNew", () => {
209+
expect(() =>
210+
resolveWithStoredEntry({
211+
sessionKey: "agent:main:main:heartbeat",
212+
entry: {
213+
sessionId: "archived-heartbeat-session-id",
214+
updatedAt: NOW_MS - 1000,
215+
archivedAt: NOW_MS,
216+
heartbeatIsolatedBaseSessionKey: "agent:main:main",
217+
},
218+
}),
219+
).toThrow(
220+
'Session "agent:main:main:heartbeat" is archived. Restore it before starting new work.',
221+
);
222+
});
223+
170224
// New tests for session reuse behavior (#18027)
171225
describe("session reuse for webhooks/cron", () => {
172226
it("reuses existing sessionId when session is fresh", () => {

‎src/cron/isolated-agent/session.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,11 +161,17 @@ export function resolveCronSession(params: {
161161
const sourceSessionDiffers = Boolean(sourceSessionKey && sourceSessionKey !== params.sessionKey);
162162
const targetEntry = store[params.sessionKey];
163163
const entry = store[sourceSessionKey || params.sessionKey];
164-
// Guard the run's target row: archived sessions stay read-only even when a
165-
// differing source session seeds the carried preferences.
166-
const archivedSessionError = resolveSessionWorkStartError(params.sessionKey, targetEntry);
167-
if (archivedSessionError) {
168-
throw new Error(archivedSessionError);
164+
// Guard the run's target row even when a differing source session seeds the
165+
// carried preferences. A forced isolated heartbeat may replace its archived
166+
// synthetic row, but trusted initialization must still finish first.
167+
const canRollArchivedHeartbeat =
168+
params.forceNew === true &&
169+
targetEntry?.archivedAt !== undefined &&
170+
targetEntry.initializationPending !== true &&
171+
Boolean(targetEntry.heartbeatIsolatedBaseSessionKey?.trim());
172+
const sessionWorkStartError = resolveSessionWorkStartError(params.sessionKey, targetEntry);
173+
if (sessionWorkStartError && !canRollArchivedHeartbeat) {
174+
throw new Error(sessionWorkStartError);
169175
}
170176

171177
let sessionId: string;

‎src/infra/heartbeat-runner.isolated-key-stability.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,49 @@ describe("runHeartbeatOnce – isolated session key stability (#59493)", () => {
163163
});
164164
});
165165

166+
it("recovers an archived isolated session on the next heartbeat tick", async () => {
167+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath }) => {
168+
const cfg = makeIsolatedHeartbeatConfig(tmpDir, storePath);
169+
const baseSessionKey = resolveMainSessionKey(cfg);
170+
const isolatedSessionKey = `${baseSessionKey}:heartbeat`;
171+
const nowMs = Date.now();
172+
await seedSessionStore(storePath, isolatedSessionKey, {
173+
sessionId: "archived-heartbeat-session-id",
174+
updatedAt: nowMs - 1000,
175+
archivedAt: nowMs - 500,
176+
heartbeatIsolatedBaseSessionKey: baseSessionKey,
177+
lastChannel: "whatsapp",
178+
lastProvider: "whatsapp",
179+
lastTo: "+1555",
180+
});
181+
const replySpy = vi.spyOn(replyModule, "getReplyFromConfig");
182+
replySpy.mockResolvedValue({ text: "HEARTBEAT_OK" });
183+
184+
const result = await runHeartbeatOnce({
185+
cfg,
186+
agentId: "main",
187+
reason: "interval",
188+
deps: {
189+
getQueueSize: () => 0,
190+
nowMs: () => nowMs,
191+
},
192+
});
193+
194+
expect(result.status).toBe("ran");
195+
expect(replySpy).toHaveBeenCalledTimes(1);
196+
const store = readSessionStoreForTest<{
197+
archivedAt?: number;
198+
heartbeatIsolatedBaseSessionKey?: string;
199+
sessionId?: string;
200+
}>(storePath);
201+
expect(store[isolatedSessionKey]).toMatchObject({
202+
heartbeatIsolatedBaseSessionKey: baseSessionKey,
203+
});
204+
expect(store[isolatedSessionKey]?.archivedAt).toBeUndefined();
205+
expect(store[isolatedSessionKey]?.sessionId).not.toBe("archived-heartbeat-session-id");
206+
});
207+
});
208+
166209
it("stays stable even with multiply-accumulated suffixes", async () => {
167210
await withTempHeartbeatSandbox(async ({ tmpDir, storePath }) => {
168211
const cfg = makeIsolatedHeartbeatConfig(tmpDir, storePath);

0 commit comments

Comments
 (0)