fix(process): retain the monotonic startup deadline budget

Recheck the absolute monotonic deadline when an early timer fires, and keep
polling waits pending until their own target or the shared deadline arrives.
Preserve caller cancellation, disposal and the unchanged real-timer assertion.
This replaces the earlier remainingMs workaround: an early callback must not
classify an unexpired deadline as a timeout.

Adapt the production fix and regression cases from nosmile99 PR #2793 at
546001693636f13700d86c6e93b6086abba2b7d6, including the independently reported
both-timers-early reproduction. Preserve the prior contributor's commit.

Fixes #2760

Co-authored-by: nosmile99 <147114285+nosmile99@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
N0zoM1z0
2026-10-13 13:37:54 +00:00
co-authored by nosmile99 Kaoru0822
parent 27cc6c8e23
commit d02ebca539
2 changed files with 185 additions and 20 deletions
+134 -5
View File
@@ -34,14 +34,34 @@ it("aborts a bounded wait when its real monotonic deadline expires", async () =>
}
});
it("reports no remaining time once its timer fires before the monotonic deadline", () => {
it("does not expire a future monotonic deadline on an early timer callback", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const now = vi.spyOn(performance, "now").mockReturnValue(1_000);
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const deadline = new ProviderStartupDeadline(40);
try {
// Timers may fire while the monotonic clock is still just short of the deadline.
now.mockReturnValue(1_039.6);
vi.advanceTimersByTime(40);
monotonic = 39;
await vi.advanceTimersByTimeAsync(40);
expect(deadline.remainingMs()).toBe(1);
expect(deadline.signal.aborted).toBe(false);
expect(deadline.interruption).toBeUndefined();
} finally {
deadline.dispose();
vi.useRealTimers();
}
});
it("aborts when the re-armed timer reaches the absolute deadline", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const deadline = new ProviderStartupDeadline(40);
try {
monotonic = 39;
await vi.advanceTimersByTimeAsync(40);
expect(deadline.signal.aborted).toBe(false);
monotonic = 40;
await vi.advanceTimersByTimeAsync(1);
expect(deadline.signal.aborted).toBe(true);
expect(deadline.interruption).toBe("timeout");
expect(deadline.remainingMs()).toBe(0);
@@ -50,3 +70,112 @@ it("reports no remaining time once its timer fires before the monotonic deadline
vi.useRealTimers();
}
});
it("reports a wait that resolves at the deadline as aborted, not elapsed", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const deadline = new ProviderStartupDeadline(40);
try {
const pending = deadline.wait(500);
monotonic = 40;
await vi.advanceTimersByTimeAsync(40);
await expect(pending).resolves.toBe("aborted");
} finally {
deadline.dispose();
vi.useRealTimers();
}
});
it("resolves a polling interval shorter than the budget as elapsed", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const deadline = new ProviderStartupDeadline(40);
try {
const pending = deadline.wait(10);
monotonic = 10;
await vi.advanceTimersByTimeAsync(10);
await expect(pending).resolves.toBe("elapsed");
expect(deadline.signal.aborted).toBe(false);
expect(deadline.remainingMs()).toBe(30);
} finally {
deadline.dispose();
vi.useRealTimers();
}
});
it("keeps caller cancellation classified without reporting an exhausted budget", () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const caller = new AbortController();
const deadline = new ProviderStartupDeadline(40, caller.signal);
try {
monotonic = 20;
caller.abort(new Error("caller stopped startup"));
expect(deadline.signal.aborted).toBe(true);
expect(deadline.interruption).toBe("cancelled");
expect(deadline.remainingMs()).toBe(20);
} finally {
deadline.dispose();
vi.useRealTimers();
}
});
// Probe from issue #2760 review: both the abort timer and the clamped polling
// timer can fire early at the same monotonic instant. The full-budget wait must
// stay pending until the absolute deadline expires.
it("keeps a full-budget wait pending when both timers fire early", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const caller = new AbortController();
const deadline = new ProviderStartupDeadline(40, caller.signal);
let outcome: string | undefined;
const pending = deadline.wait(500).then((result) => {
outcome = result;
return result;
});
try {
monotonic = 39;
await vi.advanceTimersByTimeAsync(40);
expect(deadline.signal.aborted).toBe(false);
expect(deadline.remainingMs()).toBe(1);
expect(outcome).toBeUndefined();
monotonic = 40;
await vi.advanceTimersByTimeAsync(1);
await expect(pending).resolves.toBe("aborted");
expect(deadline.remainingMs()).toBe(0);
} finally {
caller.abort();
deadline.dispose();
vi.useRealTimers();
}
});
it("releases the timer and listener on dispose with a pending wait", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
let monotonic = 0;
vi.spyOn(performance, "now").mockImplementation(() => monotonic);
const caller = new AbortController();
const deadline = new ProviderStartupDeadline(40, caller.signal);
try {
const pending = deadline.wait(500);
deadline.dispose();
// The external abort listener is removed: caller cancellation after
// dispose must not abort the deadline or classify it as cancelled.
caller.abort(new Error("caller stopped startup"));
expect(deadline.signal.aborted).toBe(false);
expect(deadline.interruption).toBeUndefined();
monotonic = 100;
await vi.advanceTimersByTimeAsync(100);
expect(deadline.signal.aborted).toBe(false);
// The deadline expired while disposed, so the clamped wait resolves
// "aborted" from the monotonic clock instead of polling past expiry.
await expect(pending).resolves.toBe("aborted");
} finally {
deadline.dispose();
vi.useRealTimers();
}
});
+51 -15
View File
@@ -61,13 +61,7 @@ export class ProviderStartupDeadline {
return;
}
signal?.addEventListener("abort", this.#onExternalAbort, { once: true });
this.#timer = setTimeout(() => {
if (this.#controller.signal.aborted) return;
this.#interruption = "timeout";
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
);
}, timeoutMs);
this.#armDeadlineTimer(timeoutMs);
}
/** Composite signal aborted by either the caller or the absolute deadline. */
@@ -85,18 +79,39 @@ export class ProviderStartupDeadline {
/** Milliseconds still available to the next startup phase. */
remainingMs(): number {
// Node timers can fire a fraction of a millisecond before the monotonic
// deadline, so an elapsed timer must not report time left to spend.
if (this.#interruption === "timeout") return 0;
return Math.max(0, Math.ceil(this.#deadlineAt - performance.now()));
}
/** Wait for at most one polling interval under the shared deadline signal. */
/**
* Wait for at most one polling interval under the shared deadline signal.
*
* Both timers may fire before their monotonic targets. Retain the earlier
* of the polling target and deadline, and wait again for any residual time.
*/
wait(milliseconds: number): Promise<AbortableWaitResult> {
return waitForAbortableDelay(
Math.min(milliseconds, this.remainingMs()),
this.signal,
);
const startedAt = performance.now();
// Absolute target: the earlier of the requested polling interval and the
// absolute monotonic deadline.
const targetAt = Math.min(startedAt + milliseconds, this.#deadlineAt);
const poll = (): Promise<AbortableWaitResult> => {
const budget = this.remainingMs();
const residual = Math.max(0, targetAt - performance.now());
return waitForAbortableDelay(
Math.min(residual, budget),
this.signal,
).then((result) => {
if (result === "aborted") return "aborted";
const now = performance.now();
// The monotonic deadline expired: a full-budget wait resolves as an
// abort so polling stops at the boundary.
if (now >= this.#deadlineAt) return "aborted";
// The polling interval elapsed without expiring the deadline.
if (now >= targetAt) return "elapsed";
// A timer fired before the absolute target; keep waiting.
return poll();
});
};
return poll();
}
/** Release the deadline timer and external abort listener. */
@@ -115,4 +130,25 @@ export class ProviderStartupDeadline {
if (this.#timer !== undefined) clearTimeout(this.#timer);
this.#timer = undefined;
}
/**
* Arm (or re-arm) the timer that expires the absolute monotonic deadline.
*
* Re-check the clock before classifying expiry, and retain the residual
* budget when the timer arrives early.
*/
#armDeadlineTimer(milliseconds: number): void {
this.#timer = setTimeout(() => {
this.#timer = undefined;
if (this.#controller.signal.aborted) return;
if (performance.now() >= this.#deadlineAt) {
this.#interruption = "timeout";
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
);
return;
}
this.#armDeadlineTimer(this.remainingMs());
}, milliseconds);
}
}