Skip to content

Turn start blocks the event loop for seconds on long threads: pendingStoppedDelegatedTasks scans every attempt for every run #45603

Done

Description

@Dropje97

What happens

On a long orchestrator thread, each turn start blocks the server's event loop for 2–6 s. Every connected client waits meanwhile: thread switches, snapshots and live updates stall.

Cause

pendingStoppedDelegatedTasks (apps/server/src/orchestration-v2/RestartBackgroundNote.ts) builds toldRunRequests with input.attempts.some(...) per run of the provider thread, so runs × attempts, once the thread has a stopped run. Each candidate task then scans toldRunRequests again. It is the pattern #39241 removed from the restart-note functions (#39231); #34499, merged after it, added this function with it. The thread here has 13,553 runs and 13,553 attempts. The code is the same on main.

Measured

A 15-minute CPU profile of the server (0.1.14-nightly.20261128.5385) had 11.1 s of self time in this function, in blocks of 2–5.9 s, one per turn start on that thread.

Fix

The same approach as #39241: one pass over the attempts into a set, and the latest qualifying request time instead of the list:

const runsWithCompletedAttempt = new Set(
  input.attempts.filter((attempt) => completedAttemptIds.has(attempt.id)).map((attempt) => attempt.runId),
);
const latestToldRequest = input.runs
  .filter((run) => run.providerThreadId === input.providerThreadId &&
    !input.compactionMessageIds.has(run.userMessageId) && runsWithCompletedAttempt.has(run.id))
  .reduce((latest, run) => Math.max(latest, DateTime.toEpochMillis(run.requestedAt)), -Infinity);
// per task, replacing the toldRunRequests.some(...) check:
//   task.completedAt !== null && !(latestToldRequest > DateTime.toEpochMillis(task.completedAt))

Patched locally with a test that counts reads of attempt.runId; the existing RestartBackgroundNote and ThreadStop tests pass. Happy to open a PR.

Measured and written by Claude (Opus 5.5) in T3 Code; posted with the owner's approval.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions