Repository navigation
fix(throttler): keep scheduling queued tasks after a task fails - #11060
Ishkirat-Singh wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request ensures that the throttler continues scheduling queued tasks after a task fails by calling this.process() in onTaskFailed. However, the reviewer pointed out that this change can cause this.finish() to be called multiple times, leading to memory leaks and redundant execution because this.waits is never cleared. It is recommended to clear this.waits inside this.finish() to resolve this issue.
| this.finish(error); | ||
| // A failed task frees its concurrency slot just like a fulfilled one. Without this, | ||
| // tasks still waiting behind it are never scheduled and their promises never settle. | ||
| this.process(); |
There was a problem hiding this comment.
With the introduction of this.process() in onTaskFailed, the throttler will now continue to execute remaining tasks after a failure. This means this.finish() can be called multiple times (either via subsequent failures or when the queue eventually becomes idle and calls finishIfIdle()).
Currently, this.finish() iterates over this.waits but never clears the array:
private finish(err?: TaskError): void {
this.waits.forEach((p) => {
if (err) {
return p.reject(err);
}
this.finished = true;
return p.resolve();
});
}Because this.waits is not cleared, this leads to:
- Memory Leak: References to already-settled promises and their handlers are retained in
this.waitsindefinitely. - Redundant Execution / Double Settling: Subsequent calls to
finish()will attempt to resolve or reject the same already-settled promises again. - Inconsistent Behavior: If a caller calls
wait()after a failure has occurred but before the queue is idle, that new promise will be resolved successfully when the queue becomes idle, despite the earlier failure.
Recommendation:
Please update this.finish() to clear the this.waits array after settling them:
private finish(err?: TaskError): void {
this.waits.forEach((p) => {
if (err) {
return p.reject(err);
}
this.finished = true;
return p.resolve();
});
this.waits = [];
}There was a problem hiding this comment.
Done in 428c571: finish() now hands the registered waiters off before settling them, with a test asserting they are released.
428c571 to
37061f4
Compare
onTaskFulfilled calls process() to start the next waiting task, but onTaskFailed did not. A task that exhausted its retries (or timed out) therefore released its concurrency slot without refilling it, so any task still waiting behind it was never scheduled and its promise never settled. For QueueExecutor callers that means a deploy can hang on an unsettled promise and, once nothing else is pending, exit without reporting an error. Related: firebase#11040
finish() can now run more than once, so hand the registered waiters off before settling them instead of keeping them for the throttler's lifetime.
37061f4 to
d7164a2
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #11060 +/- ##
=======================================
Coverage ? 60.39%
=======================================
Files ? 650
Lines ? 43512
Branches ? 8946
=======================================
Hits ? 26277
Misses ? 15039
Partials ? 2196 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
IzaakGough
left a comment
There was a problem hiding this comment.
Thanks for chasing this one down, and for the write-up linking it back to #11040.
The core fix looks right to me. A failed task frees its concurrency slot exactly like a fulfilled one, so process() belongs in onTaskFailed. I checked out the head and could not break it: Queue and Stack both resume scheduling, active accounting stays balanced, and there is no double-scheduling or synchronous recursion. The throttler, hosting uploader, operation-poller, functions-release and extensions specs are all green.
My comments are on the second change in finish() and on the CHANGELOG, plus two smaller notes.
| const waits = this.waits; | ||
| this.waits = []; | ||
| waits.forEach((p) => { | ||
| if (err) { | ||
| return p.reject(err); | ||
| } |
There was a problem hiding this comment.
Clearing waits here has a knock-on effect on finished. this.finished = true is assigned inside the forEach body, so once finish(error) empties the array, the later no-error finish() from finishIfIdle() iterates nothing and finished stays false for the rest of the run.
I checked with a small script: concurrency 5, task 1 rejects, task 2 resolves, then close() and wait(). Task outcomes are identical either way (complete: 2 success: 1 errored: 1), but the flag differs:
- merge base:
FINISHED FLAG: true - this branch:
FINISHED FLAG: false
I did not run a hosting deploy, but statusMessage() in src/deploy/hosting/uploader.ts branches on exactly this flag, so after a single hash/populate/upload task exhausts its retries the progress line would stay on "hashing files ..." rather than advancing to the later stages.
The clearing does not look load-bearing for the main fix, since resolve() on an already-rejected waiter was already a no-op. Hoisting the assignment out of the loop keeps your new waits.length === 0 assertion and restores the flag:
const waits = this.waits;
this.waits = [];
if (!err) {
this.finished = true;
}
waits.forEach((p) => {
if (err) {
return p.reject(err);
}
return p.resolve();
});With that applied the probe prints true again, and throttler.spec.ts, queue.spec.ts and stack.spec.ts come out at 41 passing.
| - [fixed] Fail fast with an actionable error and remediation instructions when declarative security APIs (IAM and Cloud Resource Manager) are disabled on the project. | ||
| - Updated Pub/Sub emulator to version 0.8.36. | ||
| - [fixed] Clean up managed service accounts when opting out of declarative security alongside a filtered codebase deploy. | ||
| - ext:uninstall --immediate now warns about secrets bound to the extension that will be deleted and offers a migration path. | ||
| - [fixed] Generate deterministic unsalted ETags for declarative security roles. |
There was a problem hiding this comment.
I think these five lines belong to other PRs. This branch's merge base is 38 commits behind origin/main, and main's CHANGELOG was reset by the 15.31.0 release, so it currently holds just the Cloud Functions prompts line.
As it stands, merging would republish entries that already shipped (declarative security APIs, Pub/Sub emulator 0.8.36, managed service account cleanup, ext:uninstall --immediate, unsalted ETags) in the next release notes. Rebasing on origin/main and keeping only the last line should sort it.
| const result = await Promise.race([ | ||
| second, | ||
| new Promise((_, reject) => | ||
| setTimeout(() => reject(new Error("task 2 was never scheduled")), 100), | ||
| ), | ||
| ]); |
There was a problem hiding this comment.
This decides pass/fail on a 100 ms wall-clock timer racing a real promise, and the timer is never cleared when second wins. On a loaded CI runner that is the shape that tends to flake.
createTask earlier in this file gives you an externally resolvable promise plus startExecutePromise, so the test could await task 2 actually starting rather than timing it. That also asserts the thing you care about more directly than a deadline does.
| // A failed task frees its concurrency slot just like a fulfilled one. Without this, | ||
| // tasks still waiting behind it are never scheduled and their promises never settle. | ||
| this.process(); |
There was a problem hiding this comment.
Worth a deliberate decision rather than something I would call a bug: the description reasons about run()-style callers, but this also changes add()-style callers, where a failure previously stopped the queue from scheduling anything further.
From reading the callers (I have not run either deploy path), src/deploy/extensions/release.ts would now keep creating, updating and deleting extension instances after await deploymentPromise has already thrown and saveEtags() was skipped, and the hosting uploader would keep uploading queued files after the deploy errored. In the CLI that window is bounded by the 250 ms in errorOut(), but embedders (library, VS Code, MCP) have no such bound.
If halting is still wanted for those callers, it may be better to make that explicit rather than leave it as a side effect of this change.
|
Thanks for the thorough review, @IzaakGough, and sorry I didn't get back to you sooner. #11248 has since landed the same The only part left would be the waiter hand-off in |
Description
Throttler.onTaskFulfilledcallsprocess()so the next waiting task is scheduled, butonTaskFaileddid not. A task that exhausted its retries (or timed out) therefore released its concurrency slot without refilling it, and any task still waiting behind it was never scheduled. Forrun()-style callers such asQueueExecutor, that task's promise never settles: a deploy can hang on an unsettled promise and, once nothing else is pending, exit without ever reporting an error.This makes
onTaskFailedresume scheduling the same wayonTaskFulfilleddoes.finish(error)still rejectswait()callers first, so their behaviour is unchanged; the difference is that tasks already added to the throttler keep running, which is what theclose()docstring promises ("any tasks already added to the throttler will continue to run").Related: #11040. The source-token deadlock described there was addressed in #11044; this is a separate defect in the throttler with the same "silent hang, exit 0" signature, found while investigating that report.
Scenarios Tested
should keep scheduling waiting tasks after a task failstosrc/throttler/throttler.spec.ts; it runs for bothQueueandStack. Withconcurrency: 1, task 1 fails and task 2 is queued behind it; the test asserts task 2's promise settles.npx mocha src/throttler/throttler.spec.ts src/throttler/queue.spec.ts src/throttler/stack.spec.ts: 39 passing. Without the fix the new test fails (2 failing, one per implementation).Sample Commands
N/A.