Skip to content

fix(throttler): keep scheduling queued tasks after a task fails - #11060

Closed
Ishkirat-Singh wants to merge 2 commits into
firebase:mainfrom
Ishkirat-Singh:fix/throttler-resume-after-failure
Closed

Ishkirat-Singh wants to merge 2 commits into
firebase:mainfrom
Ishkirat-Singh:fix/throttler-resume-after-failure

Conversation

@Ishkirat-Singh

Copy link
Copy Markdown
Contributor

Description

Throttler.onTaskFulfilled calls process() so the next waiting task is scheduled, but onTaskFailed did 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. For run()-style callers such as QueueExecutor, 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 onTaskFailed resume scheduling the same way onTaskFulfilled does. finish(error) still rejects wait() callers first, so their behaviour is unchanged; the difference is that tasks already added to the throttler keep running, which is what the close() 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

  • Added should keep scheduling waiting tasks after a task fails to src/throttler/throttler.spec.ts; it runs for both Queue and Stack. With concurrency: 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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 300 to +303
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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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:

  1. Memory Leak: References to already-settled promises and their handlers are retained in this.waits indefinitely.
  2. Redundant Execution / Double Settling: Subsequent calls to finish() will attempt to resolve or reject the same already-settled promises again.
  3. 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 = [];
  }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 428c571: finish() now hands the registered waiters off before settling them, with a test asserting they are released.

@Ishkirat-Singh
Ishkirat-Singh force-pushed the fix/throttler-resume-after-failure branch 2 times, most recently from 428c571 to 37061f4 Compare September 13, 2026 15:55
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.
@Ishkirat-Singh
Ishkirat-Singh force-pushed the fix/throttler-resume-after-failure branch from 37061f4 to d7164a2 Compare September 14, 2026 23:04
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@3c56c2b). Learn more about missing BASE report.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@IzaakGough IzaakGough left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +231 to 236
const waits = this.waits;
this.waits = [];
waits.forEach((p) => {
if (err) {
return p.reject(err);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread CHANGELOG.md
Comment on lines +2 to +6
- [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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +424 to +429
const result = await Promise.race([
second,
new Promise((_, reject) =>
setTimeout(() => reject(new Error("task 2 was never scheduled")), 100),
),
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +303 to +305
// 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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Ishkirat-Singh

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @IzaakGough, and sorry I didn't get back to you sooner. #11248 has since landed the same process() call in onTaskFailed on main, so I'm closing this one rather than rebasing it.

The only part left would be the waiter hand-off in finish(). As you showed, that clears waits and leaves finished stuck at false. It isn't load-bearing on main, where resolving an already-rejected waiter is a no-op, so I'll leave finish() as it is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants