Skip to content

Commit 458ad41

Browse files
committed
fix(channels): keep started ingress deliveries admissible after their inherited root releases
1 parent 921e945 commit 458ad41

2 files changed

Lines changed: 127 additions & 2 deletions

File tree

‎src/channels/message/ingress-drain.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@
66
*/
77
import { sleepWithAbort } from "@openclaw/retry";
88
import { formatErrorMessage, toErrorObject } from "../../infra/errors.js";
9-
import { GatewayDrainingError } from "../../process/gateway-work-admission.js";
9+
import {
10+
GatewayDrainingError,
11+
retainGatewayRootWorkAdmissionContinuation,
12+
runOutsideGatewayRootWorkAdmission,
13+
} from "../../process/gateway-work-admission.js";
1014
import {
1115
createIngressDrainOwnerId,
1216
deregisterLiveIngressDrainInstance,
@@ -546,9 +550,20 @@ export function createChannelIngressDrain<
546550
armStallWatchdog(state);
547551
armClaimRefresh(state);
548552

553+
// drainOnce starts dispatches without awaiting them, so this task outlives
554+
// the admission context it inherits (a detached pump root or the transport
555+
// request that enqueued the event). Retain a live root until the task
556+
// settles; when the inherited root is already released, dispatch outside it
557+
// so the dead lease cannot make session admission refuse the turn as
558+
// draining. A real restart drain still refuses both paths at admission.
559+
const releaseRootWork = retainGatewayRootWorkAdmissionContinuation();
549560
state.task = (async () => {
550561
try {
551-
const result = await options.dispatchClaimedEvent(claim, lifecycle);
562+
const result = await (releaseRootWork
563+
? options.dispatchClaimedEvent(claim, lifecycle)
564+
: runOutsideGatewayRootWorkAdmission(() =>
565+
options.dispatchClaimedEvent(claim, lifecycle),
566+
));
552567
// dispose() leaves claims for recovery. Session abort mid-flight
553568
// (skipped/void) also leaves the claim; a terminal completed/failed
554569
// result still settles even if abort raced the return.
@@ -616,6 +631,8 @@ export function createChannelIngressDrain<
616631
await state.settleOnce(async () => {
617632
await applyFailureDisposition(claim, err);
618633
});
634+
} finally {
635+
releaseRootWork?.();
619636
}
620637
})();
621638

‎src/channels/message/ingress-monitor.test.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
22
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
33
import {
44
GatewayDrainingError,
5+
isGatewaySubordinateWorkAdmissionClosed,
56
markGatewayRestartDraining,
67
resetGatewayWorkAdmission,
78
runWithGatewayIndependentRootWorkAdmission,
9+
runWithGatewayIndependentRootWorkContinuation,
810
} from "../../process/gateway-work-admission.js";
911
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
1012
import { sleep } from "../../utils/sleep.js";
@@ -68,6 +70,7 @@ function createMonitor(
6870
waitForDeliveryIdleBeforeRepump?: boolean;
6971
waitForDeliveryIdleOnStop?: boolean;
7072
retryPolicy?: IngressRetryPolicyConfig;
73+
runPumpTask?: (work: () => Promise<void>) => Promise<void>;
7174
},
7275
onError?: (error: unknown) => void,
7376
abortSignal?: AbortSignal,
@@ -655,6 +658,111 @@ describe("channel ingress monitor", () => {
655658
});
656659
});
657660

661+
it("keeps a started delivery admissible after its detached pump root releases", async () => {
662+
await withQueue(async (queue) => {
663+
let releaseDeliver = () => {};
664+
const deliverGate = new Promise<void>((resolve) => {
665+
releaseDeliver = resolve;
666+
});
667+
let admissionClosedDuringDelivery: boolean | undefined;
668+
const deliver = vi.fn(async (_raw: RawEvent, lifecycle: ChannelIngressMonitorLifecycle) => {
669+
await deliverGate;
670+
admissionClosedDuringDelivery = isGatewaySubordinateWorkAdmissionClosed();
671+
await lifecycle.onAdopted();
672+
});
673+
let markPumpTaskSettled = () => {};
674+
const pumpTaskSettled = new Promise<void>((resolve) => {
675+
markPumpTaskSettled = resolve;
676+
});
677+
// Mirror the production webhook-spool combination: the pump runs on its
678+
// own detached root and does not wait for deliveries before returning.
679+
const monitor = createMonitor(queue, deliver, {
680+
waitForDeliveryIdleBeforeRepump: false,
681+
runPumpTask: (work) =>
682+
runWithGatewayIndependentRootWorkContinuation(work).finally(() => markPumpTaskSettled()),
683+
});
684+
monitor.start();
685+
try {
686+
// Admit inside its own root and let it release right away, the way an
687+
// ack-first webhook request root releases once the 200 is written.
688+
await runWithGatewayIndependentRootWorkAdmission(async () => {
689+
await monitor.admit({ id: "event-detached-root", lane: "a", text: "hello" });
690+
});
691+
await vi.waitFor(() => expect(deliver).toHaveBeenCalledOnce());
692+
// The pump returns while the delivery is still in flight; every root
693+
// the dispatch could have inherited is released at this point.
694+
await pumpTaskSettled;
695+
releaseDeliver();
696+
697+
await vi.waitFor(() => expect(admissionClosedDuringDelivery).toBeDefined());
698+
expect(admissionClosedDuringDelivery).toBe(false);
699+
await monitor.waitForIdle();
700+
await expect(queue.listPending()).resolves.toEqual([]);
701+
await expect(queue.listClaims()).resolves.toEqual([]);
702+
} finally {
703+
releaseDeliver();
704+
await monitor.stop();
705+
}
706+
});
707+
});
708+
709+
it("dispatches outside an already-released inherited root instead of refusing", async () => {
710+
await withQueue(async (queue) => {
711+
let releaseDeliver = () => {};
712+
const deliverGate = new Promise<void>((resolve) => {
713+
releaseDeliver = resolve;
714+
});
715+
let admissionClosedDuringDelivery: boolean | undefined;
716+
const deliver = vi.fn(async (_raw: RawEvent, lifecycle: ChannelIngressMonitorLifecycle) => {
717+
await deliverGate;
718+
admissionClosedDuringDelivery = isGatewaySubordinateWorkAdmissionClosed();
719+
await lifecycle.onAdopted();
720+
});
721+
// No runPumpTask: the pump chain inherits the admitting caller's context,
722+
// the way a transport request that enqueues an event does.
723+
const monitor = createMonitor(queue, deliver, {}, undefined, undefined, 60_000);
724+
let markPendingScanStarted = () => {};
725+
const pendingScanStarted = new Promise<void>((resolve) => {
726+
markPendingScanStarted = resolve;
727+
});
728+
let releasePendingScan = () => {};
729+
const pendingScanGate = new Promise<void>((resolve) => {
730+
releasePendingScan = resolve;
731+
});
732+
const listPending = queue.listPending.bind(queue);
733+
let gateNextPendingScan = true;
734+
queue.listPending = async (...args) => {
735+
if (gateNextPendingScan) {
736+
gateNextPendingScan = false;
737+
markPendingScanStarted();
738+
await pendingScanGate;
739+
}
740+
return await listPending(...args);
741+
};
742+
monitor.start();
743+
try {
744+
// Admit inside a root that releases as soon as the enqueue returns;
745+
// the gated scan keeps the claim from happening until after that.
746+
await runWithGatewayIndependentRootWorkAdmission(async () => {
747+
await monitor.admit({ id: "event-released-root", lane: "a", text: "hello" });
748+
await pendingScanStarted;
749+
});
750+
releasePendingScan();
751+
await vi.waitFor(() => expect(deliver).toHaveBeenCalledOnce());
752+
releaseDeliver();
753+
754+
await vi.waitFor(() => expect(admissionClosedDuringDelivery).toBeDefined());
755+
expect(admissionClosedDuringDelivery).toBe(false);
756+
await monitor.waitForIdle();
757+
await expect(queue.listClaims()).resolves.toEqual([]);
758+
} finally {
759+
releaseDeliver();
760+
releasePendingScan();
761+
await monitor.stop();
762+
}
763+
});
764+
});
765+
658766
it("does not let a blocked settlement write wedge stop", async () => {
659767
await withQueue(async (queue) => {
660768
let markReleaseStarted = () => {};

0 commit comments

Comments
 (0)