Skip to content

Commit 50dee05

Browse files
authored
refactor(delivery): prevent duplicate and lost scheduled deliveries (#114479)
* refactor(delivery): make cron delivery durable and recoverable * fix(delivery): preserve immutable staged media during stable reuse * fix(delivery): fence platform attempt settlement and ambiguous batches * fix(delivery): preserve legacy queues and fence bounded terminal states * fix(delivery): retain ambiguous partial abort and rejection evidence * fix(delivery): never impersonate active bounded delivery owners * fix(delivery): narrow optional durable queue custody * fix(delivery): enforce admission and stable-owner recovery fences * fix(delivery): fence explicitly reusable permanent producer intents * refactor(delivery): split durable queue owners and remove cycle * fix(delivery): fence permanent recovery and in-flight producer leases * fix(delivery): limit active recovery leases to explicit producers
1 parent 5aac6d4 commit 50dee05

22 files changed

Lines changed: 3668 additions & 861 deletions

‎src/cron/isolated-agent.delivery-awareness.test.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import { createCliDeps, mockAgentPayloads } from "./isolated-agent.delivery.test
1010
import { runCronIsolatedAgentTurn } from "./isolated-agent.js";
1111
import { makeCfg, makeJob, withTempCronHome } from "./isolated-agent.test-harness.js";
1212
import { setupIsolatedAgentTurnMocks } from "./isolated-agent.test-setup.js";
13-
import { resetCompletedDirectCronDeliveriesForTests } from "./isolated-agent/delivery-dispatch.test-support.js";
1413

1514
async function writeDefaultAgentSessionStoreEntries(
1615
entries: Record<string, Record<string, unknown>>,
@@ -51,7 +50,6 @@ async function runAnnounceTurn(params: {
5150
describe("runCronIsolatedAgentTurn cron delivery awareness", () => {
5251
beforeAll(async () => {
5352
setupIsolatedAgentTurnMocks();
54-
resetCompletedDirectCronDeliveriesForTests();
5553
resetSystemEventsForTest();
5654
await withTempCronHome(async (home) => {
5755
const storePath = await writeDefaultAgentSessionStoreEntries({});
@@ -67,7 +65,6 @@ describe("runCronIsolatedAgentTurn cron delivery awareness", () => {
6765

6866
beforeEach(() => {
6967
setupIsolatedAgentTurnMocks();
70-
resetCompletedDirectCronDeliveriesForTests();
7168
resetSystemEventsForTest();
7269
});
7370

‎src/cron/isolated-agent/delivery-dispatch-policy.ts‎

Lines changed: 54 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,14 @@ import type { OpenClawConfig } from "../../config/types.openclaw.js";
1010
import type { TtsAutoMode } from "../../config/types.tts.js";
1111
import { isSuppressedControlReplyText } from "../../gateway/control-reply-text.js";
1212
import { sleepWithAbort } from "../../infra/backoff.js";
13+
import {
14+
getDeliveryQueueEntryStatus,
15+
loadDeliveryQueueEntry,
16+
type DeliveryQueueCompletionRetention,
17+
} from "../../infra/delivery-queue-sqlite.js";
1318
import { isProvenDeliveryNotSentError } from "../../infra/delivery-recovery.shared.js";
1419
import { isFastTestRuntimeEnv } from "../../infra/env.js";
15-
import type { OutboundDeliveryResult } from "../../infra/outbound/deliver.js";
20+
import { OUTBOUND_DELIVERY_QUEUE_NAME } from "../../infra/outbound/delivery-queue-media-staging.js";
1621
import { normalizeTargetForProvider } from "../../infra/outbound/target-normalization.js";
1722
import { retryAsync } from "../../infra/retry.js";
1823
import { stringifyRouteThreadId } from "../../plugin-sdk/channel-route.js";
@@ -26,6 +31,12 @@ import { cleanupCronRunSessionAfterRun } from "./session-cleanup.js";
2631

2732
type SuccessfulDeliveryTarget = Extract<DeliveryTargetResolution, { ok: true }>;
2833

34+
export const DIRECT_CRON_DELIVERY_COMPLETION_RETENTION = {
35+
idPrefix: "cron-direct-delivery:v1:",
36+
maxAgeMs: 24 * 60 * 60_000,
37+
maxEntries: 2_000,
38+
} as const satisfies DeliveryQueueCompletionRetention;
39+
2940
/** Deletes or retires ephemeral direct-delivery cron sessions for delete-after-run jobs. */
3041
export async function cleanupDirectCronSession(params: {
3142
job: CronJob;
@@ -105,11 +116,6 @@ const PERMANENT_DIRECT_CRON_DELIVERY_ERROR_PATTERNS: readonly RegExp[] = [
105116

106117
const STALE_CRON_DELIVERY_MAX_START_DELAY_MS = 3 * 60 * 60_000;
107118

108-
type CompletedDirectCronDelivery = {
109-
ts: number;
110-
results: OutboundDeliveryResult[];
111-
};
112-
113119
const deliveryLoggerRuntimeLoader = createLazyImportLoader(
114120
() => import("./delivery-logger.runtime.js"),
115121
);
@@ -118,8 +124,6 @@ const deliverySubagentRegistryRuntimeLoader = createLazyImportLoader(
118124
() => import("./delivery-subagent-registry.runtime.js"),
119125
);
120126

121-
const COMPLETED_DIRECT_CRON_DELIVERIES = new Map<string, CompletedDirectCronDelivery>();
122-
123127
async function loadDeliveryLoggerRuntime(): Promise<typeof import("./delivery-logger.runtime.js")> {
124128
return await deliveryLoggerRuntimeLoader.load();
125129
}
@@ -150,39 +154,6 @@ export function logCronDeliveryErrorDeferred(message: string): void {
150154
});
151155
}
152156

153-
function cloneDeliveryResults(
154-
results: readonly OutboundDeliveryResult[],
155-
): OutboundDeliveryResult[] {
156-
return results.map((result) => ({
157-
...result,
158-
...(result.meta ? { meta: { ...result.meta } } : {}),
159-
}));
160-
}
161-
162-
function pruneCompletedDirectCronDeliveries(now: number) {
163-
const ttlMs = isFastTestRuntimeEnv() ? 60_000 : 24 * 60 * 60 * 1000;
164-
for (const [key, entry] of COMPLETED_DIRECT_CRON_DELIVERIES) {
165-
if (now - entry.ts >= ttlMs) {
166-
COMPLETED_DIRECT_CRON_DELIVERIES.delete(key);
167-
}
168-
}
169-
const maxEntries = 2000;
170-
if (COMPLETED_DIRECT_CRON_DELIVERIES.size <= maxEntries) {
171-
return;
172-
}
173-
const entries = [...COMPLETED_DIRECT_CRON_DELIVERIES.entries()].toSorted(
174-
(a, b) => a[1].ts - b[1].ts,
175-
);
176-
const toDelete = COMPLETED_DIRECT_CRON_DELIVERIES.size - maxEntries;
177-
for (let i = 0; i < toDelete; i += 1) {
178-
const oldest = entries[i];
179-
if (!oldest) {
180-
break;
181-
}
182-
COMPLETED_DIRECT_CRON_DELIVERIES.delete(oldest[0]);
183-
}
184-
}
185-
186157
export function resolveCronDeliveryScheduledAtMs(params: {
187158
job: CronJob;
188159
runStartedAt: number;
@@ -202,32 +173,6 @@ export function isStaleCronDelivery(params: { job: CronJob; runStartedAt: number
202173
return resolveCronDeliveryStartDelayMs(params) > STALE_CRON_DELIVERY_MAX_START_DELAY_MS;
203174
}
204175

205-
export function rememberCompletedDirectCronDelivery(
206-
idempotencyKey: string,
207-
results: readonly OutboundDeliveryResult[],
208-
) {
209-
// Cache completed sends by idempotency key so retry paths can report the
210-
// original delivery result instead of double-announcing a cron run.
211-
const now = Date.now();
212-
COMPLETED_DIRECT_CRON_DELIVERIES.set(idempotencyKey, {
213-
ts: now,
214-
results: cloneDeliveryResults(results),
215-
});
216-
pruneCompletedDirectCronDeliveries(now);
217-
}
218-
219-
export function getCompletedDirectCronDelivery(
220-
idempotencyKey: string,
221-
): OutboundDeliveryResult[] | undefined {
222-
const now = Date.now();
223-
pruneCompletedDirectCronDeliveries(now);
224-
const cached = COMPLETED_DIRECT_CRON_DELIVERIES.get(idempotencyKey);
225-
if (!cached) {
226-
return undefined;
227-
}
228-
return cloneDeliveryResults(cached.results);
229-
}
230-
231176
export async function maybeApplyTtsToCronPayloads(params: {
232177
cfg: OpenClawConfig;
233178
payloads: ReplyPayload[];
@@ -276,25 +221,52 @@ export function buildDirectCronDeliveryIdempotencyKey(params: {
276221
: (stringifyRouteThreadId(params.delivery.threadId) ?? "");
277222
const accountId = params.delivery.accountId?.trim() ?? "";
278223
const normalizedTo = normalizeDeliveryTarget(params.delivery.channel, params.delivery.to);
279-
return `cron-direct-delivery:v1:${executionId}:${params.delivery.channel}:${accountId}:${normalizedTo}:${threadId}`;
280-
}
281-
282-
/** Clears the direct-delivery idempotency cache for deterministic tests. */
283-
function resetCompletedDirectCronDeliveriesForTests() {
284-
COMPLETED_DIRECT_CRON_DELIVERIES.clear();
224+
// Escape route fields independently so colon-bearing identities cannot
225+
// collide while ordinary shipped channel and target keys stay unchanged.
226+
const routeIdentity = [params.delivery.channel, accountId, normalizedTo, threadId]
227+
.map(encodeURIComponent)
228+
.join(":");
229+
return `${DIRECT_CRON_DELIVERY_COMPLETION_RETENTION.idPrefix}${executionId}:${routeIdentity}`;
285230
}
286231

287-
/** Returns the direct-delivery idempotency cache size for tests. */
288-
function getCompletedDirectCronDeliveriesCountForTests(): number {
289-
return COMPLETED_DIRECT_CRON_DELIVERIES.size;
232+
/** Receipts own recipient delivery; projections never stand in for custody. */
233+
export function isCompletedDirectCronDelivery(id: string): boolean {
234+
return getDeliveryQueueEntryStatus(OUTBOUND_DELIVERY_QUEUE_NAME, id) === "completed";
290235
}
291236

292-
if (process.env.VITEST || process.env.NODE_ENV === "test") {
293-
(globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.cronDeliveryDispatchTestApi")] =
294-
{
295-
resetCompletedDirectCronDeliveriesForTests,
296-
getCompletedDirectCronDeliveriesCountForTests,
297-
};
237+
/** Wait only for an active recipient owner, never for crashed ambiguous sends. */
238+
export async function waitForCompletedDirectCronDelivery(params: {
239+
id: string;
240+
signal?: AbortSignal;
241+
}): Promise<boolean> {
242+
// SQLite producer leases fence cross-process sends for at most 30 seconds.
243+
for (let attempt = 0; attempt < 120; attempt += 1) {
244+
const status = getDeliveryQueueEntryStatus(OUTBOUND_DELIVERY_QUEUE_NAME, params.id);
245+
if (status === "completed") {
246+
return true;
247+
}
248+
const owner =
249+
status === "pending" ? loadDeliveryQueueEntry(OUTBOUND_DELIVERY_QUEUE_NAME, params.id) : null;
250+
if (!owner && status === "pending") {
251+
// Completion can replace a pending row between the two indexed reads.
252+
return isCompletedDirectCronDelivery(params.id);
253+
}
254+
if (
255+
!owner ||
256+
(owner.recoveryState === "send_attempt_started"
257+
? typeof owner.platformSendStartedAt !== "number" ||
258+
owner.platformSendStartedAt <= Date.now() - 30_000
259+
: owner.recoveryState !== "producer_claimed" ||
260+
typeof owner.availableAt !== "number" ||
261+
owner.availableAt <= Date.now())
262+
) {
263+
return false;
264+
}
265+
if (attempt < 119) {
266+
await sleepWithAbort(250, params.signal);
267+
}
268+
}
269+
return false;
298270
}
299271

300272
function summarizeDirectCronDeliveryError(error: unknown): string {
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { ReplyPayload } from "../../auto-reply/reply-payload.js";
2+
import type { CliDeps } from "../../cli/outbound-send-deps.js";
3+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
4+
import type { TtsAutoMode } from "../../config/types.tts.js";
5+
import type { SourceDeliveryOutcome } from "../../infra/outbound/source-delivery-plan.js";
6+
import type { CronJob, CronRunTelemetry } from "../types.js";
7+
import type { DeliveryTargetResolution } from "./delivery-target.js";
8+
import type { RunCronAgentTurnResult } from "./run.types.js";
9+
10+
export type SuccessfulCronDeliveryTarget = Extract<DeliveryTargetResolution, { ok: true }>;
11+
12+
export type DispatchCronDeliveryParams = {
13+
cfg: OpenClawConfig;
14+
cfgWithAgentDefaults: OpenClawConfig;
15+
deps: CliDeps;
16+
job: CronJob;
17+
agentId: string;
18+
agentSessionKey: string;
19+
runSessionKey: string;
20+
sessionId: string;
21+
lifecycleRevision: string;
22+
sessionUpdatedAt: number;
23+
beforeSessionDelete?: () => void;
24+
runStartedAt: number;
25+
runEndedAt: number;
26+
timeoutMs: number;
27+
resolvedDelivery: DeliveryTargetResolution;
28+
deliveryRequested: boolean;
29+
skipHeartbeatDelivery: boolean;
30+
sourceDeliveryOutcome: SourceDeliveryOutcome;
31+
deliveryBestEffort: boolean;
32+
deliveryPayloadHasStructuredContent: boolean;
33+
deliveryPayloads: ReplyPayload[];
34+
synthesizedText?: string;
35+
ttsAuto?: TtsAutoMode;
36+
summary?: string;
37+
outputText?: string;
38+
telemetry?: CronRunTelemetry;
39+
abortSignal?: AbortSignal;
40+
isAborted: () => boolean;
41+
abortReason: () => string;
42+
withRunSession: (
43+
result: Omit<RunCronAgentTurnResult, "sessionId" | "sessionKey">,
44+
) => RunCronAgentTurnResult;
45+
};
46+
47+
/** Mutable delivery-dispatch accumulator returned to the isolated cron runner. */
48+
export type DispatchCronDeliveryState = {
49+
result?: RunCronAgentTurnResult;
50+
delivered: boolean;
51+
deliveryAttempted: boolean;
52+
deliveryError?: string;
53+
cronRunSessionCleanupAttempted: boolean;
54+
summary?: string;
55+
outputText?: string;
56+
synthesizedText?: string;
57+
deliveryPayloads: ReplyPayload[];
58+
};

0 commit comments

Comments
 (0)