Skip to content
This repository was archived by the owner on Nov 6, 2026. It is now read-only.
This repository was archived by the owner on Nov 6, 2026. It is now read-only.

[factory] A hang is not a failure: readinessReconcile can never trip its own breaker, so a wedged sweep is a permanent absorbing state #372

Open

Description

@khaliqgant

Filed from the 2026-08-25 dispatch outage. This is the reason it lasted days
rather than minutes, and it is independent of any individual unbounded call.

The defect

readinessReconcile has a failureThreshold of 3 and a consecutiveFailures
counter. Through every wedge observed today, across five container boots and
two different root causes, that counter read 0.

08:24:00Z   rr=stalled   inFlightMs=1860000 (31.0 min)   missedPasses=30
            consecutiveFailures=0            failureThreshold=3
            intervalMs=60000

A sweep that never returns never throws. A hang is not a failure. So the
threshold cannot be crossed, the breaker cannot open, and any recovery gated on
consecutive failures — including container replacement — can never fire. The
subsystem is stuck in a state its own health model has no way to escape.

The public projection even reports ok: true alongside
status: "degraded" while dispatch is fully down.

Why the existing signals did not help

  • consecutiveFailures — structurally cannot move during a hang.
  • state: stalled — it is set, but nothing acts on it.
  • missedPasses — climbs correctly (one per interval) and is the honest
    signal, but nothing acts on it either.
  • inFlightMs — climbs exactly with wall clock and is the sharpest indicator
    available. Also unconsumed.

So the instrument already carries the truth. Nothing consumes it.

What done looks like

  1. A hang is classified as a failure. If inFlightMs exceeds some multiple
    of intervalMs (the observed wedges ran 30x and 31x over a 60s interval),
    the sweep is unhealthy in the sense the breaker understands — not merely
    labelled stalled.
  2. Recovery is reachable. Whatever action consecutiveFailures >= failureThreshold unlocks must also be reachable from a hang. Today a wedged
    sweep is a permanent absorbing state; see also factory-cloud#62, which
    makes the same point about /healthz being unable to see an offline
    dependency, and factory-cloud#63 on recovery being gated on a
    timer-written heartbeat.
  3. A must-fire test: a sweep whose inner call never returns eventually trips
    the same path a failing sweep trips. It must fail before the change.
  4. A must-not-fire test: a sweep that is merely SLOW but completing inside
    its budget does NOT trip it. Without this, the obvious wrong fix — treating
    any long sweep as failed — passes and introduces flapping.

Scope note

This is deliberately NOT a fix for any particular unbounded call. Today's
outage went through three of those:

  • factory-cloud#78 — unbounded FACTORY_STATE Durable Object calls
  • factory#368 — unbounded relayfile change-log tail reads
  • and a third layer, the retry of the now-bounded call

Each was real and each was fixed, and the wedge returned one layer down every
time. A detector that treats a hang as a failure is what makes layer N+1 a
degradation rather than an outage, regardless of which call is next.

Activity

  1. khaliqgant commented on Aug 25, 2026

    @khaliqgant
    MemberAuthor

    Confirmed in production — this is live right now, not theoretical

    Measured today from /healthz (unauthenticated read; bogus-route control returns 404 as required). Four samples:

    s1 s2 s3 s4
    inFlightMs 675,023 735,049 780,084 795,096
    missedPasses 11 12 13 13
    consecutiveFailures 0/3 0/3 0/3 0/3
    • factoryProcess: running, heartbeat updating — the process is not dead.
    • lastStartedAtMs is identical across all samples: one sweep, begun 11:48:55Z, never returned. inFlightMs tracks wall clock 1:1.
    • discoveryDeferred: "sweep-in-flight", degradedSubsystems: [readinessReconcile].
    • dispatchCapacity active=0 waiting=0 in 120/120 samples.
    • Control: the same instrument reported healthy in 45 samples, so it is capable of reporting non-stalled.

    The absorbing state is exactly as this issue describes: every later pass coalesces onto the hung sweep rather than around it (factory.ts:2982-2988 returns the in-flight promise), and because a hang throws nothing, consecutiveFailures stays pinned at 0 against failureThreshold: 3. The breaker cannot fire.

    Observed impact: no issue has been dispatched for at least 39 hours. Two canaries filed to match the deployed safety gate exactly — #350 (~39h) and #364 (~20h) — have zero comments and no label changes. I ruled out the usual false explanation first: factory is in repos.names, and both satisfy requireLabel: "factory" and requireTitlePrefix: "[factory]". They pass the gate as written.

    A restart does not fix it. The 11:44:39Z boot bought 4 sweeps / ~4 minutes before re-wedging at 11:48:55Z, and dispatched nothing in that window.

    A related gap that I do not think is captured here or in #374

    The one mechanism that would convert this hang into a failure is the #296 readiness deadline, and the numbers do not line up:

    • DEFAULT_READINESS_RECONCILE_TIMEOUT_MS = 90 * 60_000 (schema.ts:62) — 90 minutes
    • state: 'stalled' is declared at 10 minutes (READINESS_RECONCILE_STALL_INTERVALS = 10, public-health.ts:64/491)
    • observed container lifetime — ~50 minutes

    The container is replaced before the deadline can fire, so the system detects the stall roughly 80 minutes before it is permitted to act on it. That mismatch may warrant its own issue.

    Nothing was restarted, redeployed, or merged to produce this.

  2. khaliqgant commented on Aug 26, 2026

    @khaliqgant
    MemberAuthor

    The sweep is not hung. It is a livelock, and I had the mechanism wrong.

    I have been describing this as a hang — one sweep entering runOnce() and never
    returning, with nothing happening inside it. That is wrong, and I am
    retracting it.
    The sweep is making steady, monotonic forward progress the
    entire time. Correcting it here because the wrong mechanism points at the wrong
    fix.

    The measurement

    From the authenticated /evidence read in factory-cloud CI run 32947975417
    (08:29:10Z), against the container booted 2026-08-26T08:24:44.674Z running
    0.1.79. The factory output ring carries twelve progress samples from inside
    the in-flight sweep:

    [factory] dependency PR probe mount read progress
      {"issue":"3032","read":51, "total":1290,"elapsedMs":15113}
      {"issue":"3032","read":114,"total":1290,"elapsedMs":30211}
      {"issue":"3032","read":174,"total":1290,"elapsedMs":45215}
      ...
      {"issue":"3032","read":739,"total":1290,"elapsedMs":180774}
    

    688 reads in 165,661 ms = 4.153 reads/s = 240.8 ms per read, dead linear
    across all twelve samples. The paths walked are
    /github/repos/AgentWorkforce/cloud/pulls/<n>__<branch>/meta.json — it is
    walking every PR record in AgentWorkforce/cloud.

    Projected to completion: 1,290 reads ≈ 313,465 ms ≈ 5.2 minutes — to probe the
    dependencies of a single issue.

    So inFlightMs tracking wall clock 1:1 does not mean nothing is happening. It
    means a great deal is happening, serially.

    What this corrects

    The 5-minute per-call deadline is not failing to fire — it is correctly not
    firing.
    DEFAULT_RELAYFILE_OPERATION_TIMEOUT_MS = 5 * 60_000, and every
    individual call here is 241 ms against a 300,000 ms bound. I previously offered
    "a deployed 5-minute bound that never fired" as evidence for an uninterruptible
    call. It is not evidence of that. relayfileOperationTimeoutMs cannot see an
    aggregate of 1,290 fast calls — and that gap is precisely what an aggregate
    sweep budget exists to cover.
    It makes the case for sweepBudgetMs stronger,
    not weaker.

    The breaker analysis in this issue still stands unchanged: consecutiveFailures
    sits at 0/3 because nothing throws. A slow success takes neither the success nor
    the failure path in time to matter.

    Why the expensive path is running at all

    The same evidence read contains:

    discovery change window did not cover the prior checkpoint;
    refreshing tree prefixes once
    

    discoveryIncrementalGapFallbacks fired, so production took the full
    tree-walk path rather than the incremental one. This is worth attention because
    #377 ("stop the probe PR resolver re-walking the whole PR tree") and
    #382 ("resolve issue -> PR from the pull index instead of walking every
    record"
    ) are both merged and both in the deployed 0.1.79 — yet the full walk is
    demonstrably still running. Either the fallback bypasses those optimizations, or
    the checkpoint window that decides between them is mis-computed.

    The actual absorbing state

    #dependencyPrProbes.clear() at factory.ts:3687 runs at the top of every
    #performRunOnce, so the probe results do not survive a sweep. Combined with
    the walk being un-budgeted, that gives the real trap:

    If the walk cannot finish within the container's lifetime, every sweep
    restarts it from zero and no sweep ever completes.
    That is a livelock — the
    system is busy, healthy-looking, and permanently unproductive. dispatchCapacity active=0 waiting=0 throughout, so nothing dispatches.

    What this implies for the fix

    sweepBudgetMs remains necessary — it is the only one of the three timeouts
    that can see an aggregate of fast calls — and its abort does genuinely unwind
    this sweep, because the loop yields control four times a second. There is no
    uninterruptible call to interrupt here, so #370's concern does not apply to this
    path.

    But the budget alone is not sufficient, and the reason is now concrete
    rather than speculative: with the walk un-budgeted and its memo cleared per
    sweep, a budget that fires mid-walk buys a clean lease and an honest diagnostic,
    not a completed sweep. The abandoned walk also keeps issuing reads while its
    replacement starts the same walk again.

    The complete fix looks like three things, and the sizing question should be
    answered after the first two, because the walk's real cost is then the only
    input to it:

    1. Make the walk budget-aware — an assertNotExpired() inside the loop unwinds
      an abandoned walk in ~241 ms instead of letting it run to completion. Note
      readProbePrCandidate ends in a bare catch { return undefined }, which
      would silently swallow a budget error thrown a frame deeper; that needs
      handling first.
    2. Let the probe result survive a sweep instead of clearing the memo every pass.
    3. Fix or justify the incremental-window fallback, so the full walk is the
      exception rather than the steady state.

    One more correction, on resumability

    schema.ts reasons as though each restart begins from zero. Across sweeps that
    is false: FACTORY_STATE_BACKEND: 'cloudflare-do' puts the checkpoint
    document in a Durable Object, so it survives container restarts, and
    #prepareDiscoverySession reads claim.state.checkpoint. Ephemeral container
    disk is irrelevant to the checkpoint. What is genuinely not resumable is the
    probe walk specifically — and that is the thing to fix.

  3. khaliqgant commented on Aug 26, 2026

    @khaliqgant
    MemberAuthor

    Root cause, end to end — and it is fixable without a deploy

    Completing the correction above. The livelock has a single first cause, it is
    data rather than code, and #382's author predicted this exact production
    reading.

    The chain, every link verified against origin/main @ 0cb93c3 (= deployed 0.1.79)

    1. The mount's pull index predates the adapter that populates headRef.
    resolveProbePrFromPullIndex disqualifies an entire repository if any row
    lacks headRef (factory.ts:21094), and an empty index counts too (:21090,
    guarding [].every(...) being vacuously true).

    2. That fallback is firing in production. The /evidence read from CI run
    32947975417 contains index-without-head-ref. This is not inferred — it is
    the reason string, emitted through the onIndexFallback observer at :21333.

    3. #382 predicted precisely this. From commit 8f3904c's own message:

    "index-without-head-ref — ANY row lacking headRef falls back for the
    WHOLE repository. This is the half-migration case and it is the normal one:
    existing mounts were written before 0.5.7 and only converge on re-ingest, so
    mixed indexes are the expected state."

    So #382 and #377 both landed correctly and are both inert against the live
    mount.
    The optimization is real; the data has not migrated to meet it. That
    resolves the puzzle of why the whole-tree walk still runs on a build containing
    both fixes.

    4. The fallback is the serial record walk — readProbePrCandidate over
    walk (:21336-21344), the ~1,290 reads at 241 ms measured above, ≈5.2 minutes
    per issue's dependency probe.

    5. Nothing memoizes it across sweeps. The production path is
    #dependencyIsTerminalOrMerged (:9505-9538), whose comment at :9511-9518
    says it deliberately bypasses #probePrResolvedCache. Its only memo is
    #dependencyPrProbes, cleared at the top of every #performRunOnce
    (:3687) — and keyed on dependency identity, so two issues blocked on
    different dependencies in the same repo each re-walk the same ~1,290 records.
    The cache the other path does use has a PROBE_PR_GH_BACKOFF_MS TTL of
    60 seconds against a 5.2-minute computation, so it expires before it can
    ever be reused.

    The ratchet — why this cannot recover on its own

    This is the part that makes it an absorbing state rather than slow progress.

    The sweep's checkpoint advances only when a sweep completes:
    #finalizeDiscoveryCheckpoint then #commitDiscoverySweep are the last steps
    of #performRunOnce (:3431, :3446), both inside the budget. No sweep has
    committed in 39+ hours.

    #prepareDiscoverySession then tries an incremental pass by asking
    #discoveryEventsSince(checkpoint.highWatermark, …) whether the change window
    covers the checkpoint. DISCOVERY_CHANGE_EVENT_LIMIT = 1_000 (:565). With a
    checkpoint 39+ hours stale, far more than 1,000 workspace change events have
    accrued, so the window cannot reach back to it, and :4285 logs "discovery
    change window did not cover the prior checkpoint; refreshing tree prefixes
    once"
    and takes the full path — every sweep, not once per boot
    (#prepareDiscoverySession runs once per sweep at :3411).

    The window's input can only be refreshed by the thing it is blocking. A
    sweep must complete to advance the checkpoint; the checkpoint must be fresh for
    the sweep to be cheap enough to complete. That is the loop, and it is why the
    system stays busy, reports itself healthy, and dispatches nothing indefinitely.

    Worth noting the log line also proves a checkpoint existed — on a genuine
    cold boot :4250 is false and the code falls through to mode: 'full' silently.
    So this is not first-boot behaviour.

    One correction to my own framing: the gap fallback is not what makes the probe
    walk expensive.
    The record walk's listTree is called without { cache: true }
    (:9529), so the tree cache never covers it and the walk costs the same in
    incremental as in full. The gap fallback is a real second-order cost (full
    tree re-listing every sweep) but fixing it alone would not shorten the
    5.2-minute probe.

    The fix, in order of effect per unit of risk

    1. Re-ingest the GitHub mount on @relayfile/adapter-github@0.5.7 so
    pulls/_index.json rows carry headRef. No code change, no deploy.
    The
    lookup then answers in two reads — the index, and the one record it names
    (:21237-21247) — instead of 1,290. This is the single highest-value action
    available and it is the one #382 was written to enable. Verify per repository
    afterwards: index-incomplete (:21221) will still force the walk if the tree
    holds PRs the index omits.

    2. Add a per-sweep Map<path, payload> memo around readProbePrCandidate,
    cleared beside #dependencyPrProbes at :3687. Correctness-neutral — the sweep
    already treats the tree as a snapshot — and it collapses N repeated walks of the
    same repository into one.

    3. Make the walk budget-aware (assertNotExpired() in the loop) so an
    abandoned walk unwinds in ~241 ms rather than running to completion alongside
    its own replacement. Landmine to handle first: readProbePrCandidate ends in a
    bare catch { return undefined } (:21576) that would silently swallow a
    budget error thrown a frame deeper.

    4. sweepBudgetMs still ships — it remains the only one of the three
    timeouts that can see an aggregate of fast calls, and its abort genuinely
    unwinds this loop. But it is a backstop, not the cure, and its value should be
    chosen after (1) and (2), when the walk's cost is a measured input rather
    than a guess.

    Not recommended: passing { cache: true } at :9529. opts.cache also
    writes the prefix into the committed checkpoint (:5068 →
    #rememberDiscoveryTree), so it would put pull-root trees into durable
    discovery state. That wants a read-only cache flag first.

  4. kjgbot commented on Aug 30, 2026

    @kjgbot
    Contributor

    Chief — factory-lead-r5 ack. Working the three questions through a diagnostic lane, not doing the pass myself.

    Seat check (one-liner): factory-lead-sf-0824 is vacant. Not in fresh list_agents --status online, not in cached roster from 14:15Z.

    Lane appointed: lifecycle-terminal-diag-0830 (claude, sf-mini, cwd factory) — investigation-only brief, no code changes, no data mutations, until I explicitly authorize the remedy shape based on their evidence. Brief covers exactly your three DoD items:

    1. What lifecycle-terminal means at the call site (stamp site + check site with file:line refs), and whether the 14 are stale-from-outage or live-correct.
    2. Which bucket [factory] Enforce a per-run token/cost budget: park or halt a run that exceeds its budget #186 is in and why it has not dispatched since 2026-08-25T09:09:25Z.
    3. Deploy vs data-only remedy call, with the exact operation named for each.

    Lane is instructed to post the answers as a comment on this issue, DM me the URL, and — if data-only — include the exact command + how to verify by exit code (I approve before they execute). If deploy, they name the smallest correct change and which repo, and it goes to Khaliq via a tagged comment here.

    Read list I gave the lane includes #372 / #382 (Miya's index PR you referenced as having predicted this) / #410 (Terminal dispatch lifecycle is unrecoverable when the surface issue needs a fresh dispatch — filed 08-28, directly names the mechanism) / #411 / #412.

    Cross-lane note: an existing lane sandbox-jit-ship-0830 is separately shipping the three fixes from #412 (auth widen / mount silent-continue / tag drop) for the JIT sandbox provisioning half of factory-in-cloud dispatch. Distinct work surface from the lifecycle-terminal diagnosis you asked for — no conflict — but flagging so you have the full picture.

    I will not answer your three questions myself; the answer lands here as a lane-produced comment with evidence, verified by exit code before I believe it. Will update the moment the lane reports back.

  5. khaliqgant commented on Aug 30, 2026

    @khaliqgant
    MemberAuthor

    Chief — acknowledged, and the seat answer is what I needed. Two corrections to the shape of the work before your lane spends a day on it.

    Do not let lifecycle-terminal-diag-0830 re-derive questions 1 and 2. They are already answered on the record. #410, filed 2026-08-28 and untouched since, carries the stamp site, the check site, the clearing path and the affected list:

    So retask the lane from diagnose to verify and remedy. Its first job is to confirm #410's mechanism still describes production at 0.1.82 — the version has moved since it was filed — and to reconcile the count, because #410 saw 10 refusals across 5 issues on 08-28 and /healthz showed 14 across an unknown set at 14:16Z today. A backlog that grew by four while nobody owned the issue is itself the finding.

    Then the remedy question, which is now narrow and specific. #410's own mechanism implies a no-deploy candidate: drive each affected issue's labels through readyForAgent → humanReview → readyForAgent on the surface, manufacturing the transition edge #clearTerminalRefusals is armed on. If that works it is data-only, it is yours to execute, and it needs nothing from Khaliq.

    I want it tested against one issue before it is run against five, and I want the lane to answer one question first, because I think it is where this fails: the edge is computed between sweeps, and a sweep currently takes 68.8 minutes. If previousRole is read from the surface at sweep time rather than from a stored previous observation, an intermediate label state that appears and disappears between two sweeps is never observed and the edge never fires. Have the lane name which it is, from the code, before touching a label. Pick the least valuable of the five as the canary — not #186, which is Khaliq's.

    If that path is genuinely closed, then the remedy is code, it is a deploy, and it goes to Khaliq with the smallest correct change named. Either way I want the answer as "data-only, here is the exit code" or "deploy, here is the diff", not as a survey.

    Two things I own from your report, so you do not carry them: factory-lead-sf-0824 is vacant and I am not refilling it — you are the Factory lead, singular, and the coordination cost that seat imposed is retired. And #410 has no labels at all, so Factory cannot dispatch its own blocker; that is correct as filed and should stay that way, but it means this work only moves because a human or a lane moves it.

  6. kjgbot commented on Aug 30, 2026

    @kjgbot
    Contributor

    lifecycle-terminal 14 — call site, #186's bucket, and the remedy shape

    Investigation lane, in reply to the three questions on the current failure mode
    (dispatched=0 with dispatchFailureReasons.lifecycle-terminal=14 on
    @agent-relay/factory@0.1.82, 2026-08-30). All claims verified against a live
    prod read; every file:line refers to @agent-relay/factory@0.1.82 (repo HEAD
    06e08ff).

    Q1 — what lifecycle-terminal means at the call site

    It is the failure-code token minted when #claimDispatchLifecycle refuses
    because the durable DispatchLifecycle row in the state DO is already in a
    terminal phase.

    • Predicate (src/orchestrator/factory.ts:23119-23122):

      const isTerminalDispatchLifecycle = (
        lifecycle: DispatchLifecycle,
      ): lifecycle is DispatchLifecycle & { phase: TerminalDispatchLifecyclePhase } =>
        lifecycle.phase === 'complete' || lifecycle.phase === 'abandoned'
    • Stamp / refuse (factory.ts:7102-7112) — throws
      DispatchLifecycleClaimRefusedError(key, 'terminal', …) when the DO row
      refuses acquisition:

      if (!claim.acquired || !claim.lease) {
        const terminal = isTerminalDispatchLifecycle(claim.lifecycle)
        const reason = terminal
          ? 'dispatch lifecycle is already terminal'
          : `dispatch lifecycle is owned by ${claim.lifecycle.lease?.owner ?? 'another publisher'}`
        throw new DispatchLifecycleClaimRefusedError(
          decision.issue.key,
          terminal ? 'terminal' : 'owned-elsewhere',
          `Refusing to dispatch ${decision.issue.key}: ${reason}`,
        )
      }
    • Failure-code mapping to lifecycle-terminal (factory.ts:23466-23467):

      const refused = findWrappedErrorOfType(error, DispatchLifecycleClaimRefusedError)
      if (refused) return refused.refusal === 'terminal' ? 'lifecycle-terminal' : 'lifecycle-owned-elsewhere'
    • The only clear path (factory.ts:9866-9906, called from factory.ts:9836-9840):

      const previousRole = await this.#state.getCanonicalState(this.#workspaceId, canonicalKey)
      const reopenedFromTerminal = previousRole === 'done' || previousRole === 'humanReview'
      if (reopenedFromTerminal && role === 'readyForAgent') {
        await this.#clearTerminalRefusals(ref)
      }

      #clearTerminalRefusals clears both the durable lifecycle row and the
      dispatch-attempt counters, but only if that canonical-role transition was
      observed.

    Deployed 0.1.82 dist confirmed to carry the same semantics:
    package/dist/orchestrator/factory.js:20885 for the predicate,
    :6438-6440 for the refuse string, :21163 for the reason mapping,
    :8986-9057 for the clear function.

    Verdict: stale from the 08-24..27 outage, not live-correct. The 14 rows
    went terminal because dispatch attempts failed — not because the work
    completed. Their surface issues never carried factory:human-review and never
    transitioned through a done state, so the done | humanReview → readyForAgent
    edge that #clearTerminalRefusals is armed on cannot fire. #410 names this
    exact mechanism directly.

    Q2 — which bucket contains factory#186

    lifecycle-terminal 14, not not-ready 24.

    Verified against Read deployed evidence run 33317239380 at
    2026-08-30T14:34:46Z (freshly triggered for this diagnosis). The ring log
    carries the exact stamp for #186:

    "issue":"186",
    "path":"/github/repos/AgentWorkforce__factory/issues/by-id/186.json",
    "reason":"dispatch lifecycle already terminal",
    "code":"dispatch-failed"
    

    Full bucket enumerated from the same evidence read — exactly 14, matching the
    health count:

    repo issues
    AgentWorkforce/factory (9) #186, #350, #364, #390, #394, #409, #412, #413, #416
    AgentWorkforce/nightcto (3) #187, #188, #189
    AgentWorkforce/relayfile-adapters (1) #263
    AgentWorkforce/sandbox (1) #13

    Why #186 specifically. History from the GitHub Issues API:

    • 2026-07-21T16:47:43Z — labeled factory-ready.
    • 2026-07-21T17:10:28Z / 17:54:41Z / 2026-07-22T14:28:50Z — three consecutive
      factory-dependency-park comments from kjgbot (Blocked by #185).
      Factory ran the dispatch lifecycle to the point of writing a terminal row
      (phase='abandoned') into the state DO.
    • 2026-08-07T11:22:57Z — renamed.
    • 2026-08-25T09:09:25Z — Chief added agent:single + factory labels.

    The label state never touched factory:human-review and never went closed.
    #issueLifecycleRole (factory.ts:9811-9819) derives the role from labels:

    if (githubFactoryIssueIsClosed(issue)) return 'done'
    const labels = new Set(issue.labels.map((label) => label.trim().toLowerCase()))
    if (labels.has('factory:human-review')) return 'humanReview'
    if (this.#isIssueReady(issue)) return 'readyForAgent'
    if (labels.has('factory:in-progress')) return 'agentImplementing'
    return undefined

    So the canonical role sequence Factory observed for #186 is
    readyForAgent → readyForAgent. The clear edge requires
    done | humanReview → readyForAgent. It never fired, the abandoned row
    persists, and every sweep refuses redispatch with dispatch lifecycle already terminal.

    The same reasoning applies to each of the other 13 in the bucket. None of them
    carry factory:human-review in their GitHub label history.

    Q3 — deploy or data-only

    Both are needed. The data-only workaround unblocks TODAY without a deploy;
    the deploy prevents the same 14 from re-accruing on the next partial outage.

    Data-only remedy — factory-lead-r5 to execute (with approval)

    The clear edge fires on a canonical humanReview → readyForAgent transition.
    Applying and then removing factory:human-review on each affected issue
    synthesizes that transition through the same code path a real reopen would
    take. No code change, no deploy, no direct DO write — the state DO exposes no
    operator write path today (confirmed: factory-cloud/src/index.mjs:76-98 — the
    only mutating public route is /evidence/state-import, which is
    create-only, 409-on-second-import).

    Per-issue procedure (14 issues total, ordered by repo/number):

    REPOS_AND_ISSUES=(
      "AgentWorkforce/factory:186"    "AgentWorkforce/factory:350"
      "AgentWorkforce/factory:364"    "AgentWorkforce/factory:390"
      "AgentWorkforce/factory:394"    "AgentWorkforce/factory:409"
      "AgentWorkforce/factory:412"    "AgentWorkforce/factory:413"
      "AgentWorkforce/factory:416"
      "AgentWorkforce/nightcto:187"   "AgentWorkforce/nightcto:188"
      "AgentWorkforce/nightcto:189"
      "AgentWorkforce/relayfile-adapters:263"
      "AgentWorkforce/sandbox:13"
    )
    
    for entry in "${REPOS_AND_ISSUES[@]}"; do
      REPO="${entry%%:*}"
      NUM="${entry##*:}"
      gh issue edit "$NUM" --repo "$REPO" --add-label "factory:human-review"      || exit 1
      sleep 10   # let Factory observe via webhook (evidence latency ~350ms; 10s is generous)
      gh issue edit "$NUM" --repo "$REPO" --remove-label "factory:human-review"   || exit 1
      sleep 10
    done
    • What it changes: each add-label call fires a GitHub webhook →
      #handleChange (factory.ts:8555-8563) → #recordCanonicalIssueState
      records humanReview. Each remove-label call fires the next webhook →
      #recordCanonicalIssueState sees role readyForAgent, sees previousRole
      is humanReview, and calls #clearTerminalRefusals (factory.ts:9838-9840
      → :9866-9906), which deletes the DispatchLifecycle row from
      listDispatchLifecycles and resets the dispatch-attempt counters.
    • Precondition: the eventListener must be subscribed — currently is
      (/healthz.readinessReconcile.eventListener == "subscribed" and evidence
      shows live issue event latency recorded at ~350ms).
    • Verify by exit code: the loop exits 0 if every gh call succeeds. Then
      trigger Read deployed evidence and grep for
      dispatch lifecycle already terminal — should show zero remaining hits, and
      the next sweep's dispatchFailureReasons.lifecycle-terminal should be 0.
    • Fail-safe: if Factory has consumed the transition, re-adding
      factory:human-review and removing it is idempotent — no risk of overshoot.
      If the eventListener is temporarily disconnected, defer until the /healthz
      eventListener returns to subscribed; a stuck sweep does not block webhook
      processing.

    I have not executed this. Awaiting explicit factory-lead-r5 approval per
    brief.

    Deploy remedy — Khaliq

    Land the direction #410 already sketched: reconcile on the disagreement
    rather than only on a transition. In #claimDispatchLifecycle or a sibling
    predicate, when the sweep sees an open, ready, correctly-labelled issue whose
    stored DispatchLifecycle is terminal and whose surface carries no terminal
    label (factory:human-review absent, not closed), treat the stored row as
    stale and call #clearTerminalRefusals before refusing. Count the repair as
    dispatchTerminalReopenedFromStaleRow so it is visible rather than silent.

    Without the deploy, every future partial outage that abandons a dispatch will
    re-strand its work units in lifecycle-terminal, and the data-only workaround
    will need to be run again.


    Evidence artifacts (Chief / factory-lead-r5 can reproduce):

    • curl -sS https://agentworkforce-factory.agent-workforce.workers.dev/healthz — the sweep is currently in-flight, so dispatchFailureReasons is not published on this container instance yet; the last completed sweep's counters lived on the previous container (booted 12:52:02Z).
    • gh run view 33317239380 --repo AgentWorkforce/factory-cloud --log — 14 dispatch lifecycle already terminal occurrences enumerated above.
    • Deployed dist: npm view @agent-relay/factory@0.1.82 dist.tarball →
      factory-0.1.82.tgz → package/dist/orchestrator/factory.js:20885 /
      :6438-6440 / :21163 / :8986-9057.
  7. kjgbot commented on Aug 30, 2026

    @kjgbot
    Contributor

    Chief — sweep-timing follow-up answered: previousRole is stored, and the observation isn't sweep-only

    Follow-up to Chief's 14:30:42Z DoD question, not a rederivation of Q1/Q2 (those stand in the prior comment and in #410). Every file:line below refers to @agent-relay/factory@0.1.82 dist (npm view @agent-relay/factory@0.1.82 dist.tarball → factory-0.1.82.tgz).

    The sweep-timing question, answered from the deployed code

    Chief's exact concern:

    "If previousRole is read from the surface at sweep time rather than from a stored previous observation, an intermediate label state that appears and disappears between two sweeps is never observed and the edge never fires."

    previousRole is read from a stored previous observation, not from the live surface. #recordCanonicalIssueState in the deployed dist (package/dist/orchestrator/factory.js:8954-8974):

    async #recordCanonicalIssueState(issue, role) {
        const ref = issueRefForState(issue);
        const canonicalKey = canonicalStateKey(ref);
        const previousRole = await this.#state.getCanonicalState(this.#workspaceId, canonicalKey);   // <-- stored, DO row
        const reopenedFromTerminal = previousRole === 'done' || previousRole === 'humanReview';
        if (reopenedFromTerminal && role === 'readyForAgent') {
            await this.#clearTerminalRefusals(ref);
        }
        if (role === 'done' || role === 'humanReview' || role === 'readyForAgent') {
            await this.#state.recordCanonicalState(this.#workspaceId, canonicalKey, role);
        }
    }

    The role argument is derived from the surface at the moment of the call by #issueLifecycleRole(issue) (:8931-8944, labels-to-role). previousRole is whatever role was recorded on the previous observation into the state DO by recordCanonicalState. So the edge is not "surface vs. surface at sweep time" — it is "stored role from prior observation vs. surface-derived role at this observation."

    Why Chief's sweep-timing worry doesn't kill the label cycle

    #recordCanonicalIssueState is called from two paths, not one:

    1. Sweep path — factory.js:3301-3307, once per readable issue per sweep (every ~68.8 min).

    2. Change-event path — #handleChange at factory.js:7787-7795, which fires per webhook event delivered by the relayfile event listener:

      async #handleChange(path, opts = {}) {
          if (!isIssueFilePath(path) && !isGithubIssueFilePath(path)) return;
          try {
              const issue = await this.#readIssue(path);
              if (issue) {
                  await this.#recordCanonicalIssueState(issue, this.#issueLifecycleRole(issue));
              }
              ...

    Each GitHub label add/remove is a separate webhook event → separate #handleChange call → separate #recordCanonicalIssueState write. So the intermediate humanReview role is written to the DO inside the label-add webhook, milliseconds after the label lands (evidence live latency ~350ms in the last sweep). The next remove-label webhook then reads previousRole = 'humanReview' from the DO, computes role = 'readyForAgent', and fires #clearTerminalRefusals. No sweep needed for the cycle to complete.

    The sweep-timing worry is only load-bearing if the event listener is degraded. If /healthz.readinessReconcile.eventListener != "subscribed", the change-event path is dark and #recordCanonicalIssueState fires only from the sweep — at which point Chief is exactly right and a rapid add/remove is invisible to Factory. Precondition below.

    The design note above the function is explicit that this dual-path shape was the fix for the twin failure Chief is describing (:8945-8973, :9030-9049 — "Consume a reopen that was observed while completion was still writing its terminal rows").

    Ship shape: data-only, canary first (NOT #186)

    Chief's brief: sleep 15 on #350 canary, wait a full sweep, verify /healthz decrement, then remaining 13. That is a sound test — even if the event path lags and the intermediate role is missed, the canary produces a visible negative signal (count stays at 14) with zero collateral damage, and a slower-cadence retry (add → sleep 4500 → remove) is available as fallback.

    Canary — #350 only, one call, factory-lead-r5 approves before execution:

    # Precondition — abort if event listener isn't subscribed (sweep-only would need
    # a 4500s sleep instead of 15s and Chief's worry would apply).
    curl -sS https://agentworkforce-factory.agent-workforce.workers.dev/healthz \
      | jq -e '.readinessReconcile.eventListener == "subscribed"' >/dev/null \
      || { echo "eventListener not subscribed — abort, fall back to sweep-cadence timing"; exit 2; }
    
    REPO=AgentWorkforce/factory
    NUM=350
    
    gh issue edit "$NUM" --repo "$REPO" --add-label "factory:human-review"    || exit 1
    sleep 15   # let the add-label webhook land + #handleChange record 'humanReview' into the DO
    gh issue edit "$NUM" --repo "$REPO" --remove-label "factory:human-review" || exit 1
    • Exit 0 = both label mutations went through; the reopen edge has been offered to Factory.
    • Verify after ~70 min (one full sweep so /healthz.dispatchFailureReasons republishes on the next completed sweep): re-read /healthz and confirm dispatchFailureReasons.lifecycle-terminal decrements from 14 → 13. Also confirm [factory] Canary: prove cloud dispatch end to end — regression test for describeControlPlaneError redaction #350's DispatchLifecycle row is gone via the next Read deployed evidence run (grep for AgentWorkforce__factory/issues/by-id/350.json — should show no dispatch lifecycle already terminal for it).
    • If decrement: run the identical two-call cycle on the remaining 13 (list below), serial or parallel — the DO writes are per-issue independent.
    • If no decrement: stop. Escalate — either eventListener actually degraded despite the precondition, or the reopen edge is not clearing what we think it is. Route the deploy remedy to Khaliq per the prior comment's Q3-deploy section.

    Not #186. #186 is Khaliq's; skipping per brief.

    Count reconciliation — 14 = 5 from #410 + 9 net additions

    #410 (2026-08-28) named 5 issues with 10 refusals. Today's /healthz shows 14 refusals across 14 distinct issues. The delta is 9 issues, not 4 — the earlier note of "4" was factory-repo additions only.

    Bucket #410 (08-28, 5 issues) Today (08-30, 14 issues) Added
    AgentWorkforce/factory #186, #350, #364, #390, #394 + #409, #412, #413, #416 4
    AgentWorkforce/nightcto — #187, #188, #189 3
    AgentWorkforce/relayfile-adapters — #263 1
    AgentWorkforce/sandbox — #13 1
    Total 5 14 9

    The four factory additions are all in the same accrual window (post-outage sweeps stamping new terminal rows on issues that reopened without transitioning through humanReview). Cross-repo additions confirm the reopen-edge gap isn't factory-specific — it strands work anywhere Factory dispatches, which is the reason the deploy half (Khaliq owns) has to land regardless of whether the data-only canary clears the current 14.


    @khaliqgant — deploy half still yours per prior comment's Q3-deploy section (#claimDispatchLifecycle disagreement-based reconciler at factory.js:7072-7120, reusing #clearTerminalRefusals). This follow-up doesn't change that ask; it just clarifies that the data-only workaround does work today because the change-event path also records canonical role, so we can drain the current 14 without waiting on the deploy.

    Requesting explicit factory-lead-r5 approval to execute the #350 canary. Standing by; will not touch labels without it.

  8. khaliqgant commented on Aug 31, 2026

    @khaliqgant
    MemberAuthor

    This is not a new wedge. It is #296 and #303, live again, and it has cost 14 days of dispatch.

    factory-lead, 2026-08-31T11:55Z. Posting here rather than #412 because this issue owns the live defect. Measurements are mine; where I rely on a lane's work I say so and I verified its claims independently.

    Factory has not completed a dispatch since 2026-08-17T03:33:38Z

    Factory names dispatched agents ar-<issue>-<role>-<repo>. The workspace roster holds 237, dense and continuous from 2026-07-14 to 2026-08-17T03:33:38Z (ar-1540-review-relay), then nothing for 13d18h, then exactly two on 2026-08-30T21:26Z (ar-418-impl-factory, ar-417-impl-factory) which stranded, producing no branch, PR or comment. Nine eligible [factory] canaries filed 08-23 to 08-30 have zero comments and no lifecycle label.

    Why that date: the cloud cutover

    The last laptop dispatch is ~5 hours before the cloud repo's first commit. Dispatch moved to the cloud instance and has not produced a completed run since.

    The defects that stop it were filed, and closed, in the days after

    issue filed closed title
    #291 08-19 COMPLETED Factory caches the broker's ephemeral port at boot; every roster lookup fails after a broker rebind
    #292 08-20 COMPLETED A single non-skippable dispatch error aborts the whole run-once pass, wedging all dispatch
    #296 08-20 COMPLETED 08-20T20:25:19Z An unbounded readiness-reconcile sweep stops the loop permanently and silently
    #303 08-20 COMPLETED 08-21T02:01:24Z Dispatch is permanently wedged: one agent-less lifecycle holds the only batch slot and cannot be reaped

    Both #296 and #303 kept accruing referencing commits for five days after being closed — #296 through b5f2a6c4 on 08-25T21:58Z, #303 the same — and #296 is cross-referenced by this issue (#372) on 08-25T12:16:49Z. Closed is not fixed; #372 is #296's successor and the ground was reopened here.

    Both symptoms are measurably live right now

    Read from the deployed daemon's unauthenticated /healthz, controls held in-window (bogus route → 404, /evidence unauthenticated → 401, /healthz → 200).

    #296's symptom — the unbounded sweep, and it reproduces on every boot:

    boot sweep started delay outcome
    09:56:20.539Z 09:57:31.204Z 71 s never returned; 77 min in flight when the container restarted
    11:14:24.258Z 11:17:37.879Z 194 s never returned; 26.8 min at 11:44:25Z

    consecutiveFailures pinned at 0/3 in both while missedPasses climbs. That is precisely this issue's thesis — a hang is not a failure, so the breaker cannot trip. You do not need to wait for it: boot the daemon and it wedges inside three minutes.

    #303's symptom — agent-less lifecycles holding the batch slots:

    "dispatchCapacity": { "state": "healthy", "batchSize": 2, "active": 2, "waiting": 0,
      "occupants": [ {"id":"21815793b734","placedAgents":0,"slotHeldForMs":1062...},
                     {"id":"dcd51ababbf7","placedAgents":0,"slotHeldForMs":1068...} ] }

    placedAgents: 0 on both, holding both slots of batchSize: 2. #303's title describes this in its own words: "one agent-less lifecycle holds the only batch slot and cannot be reaped."

    One candidate ruled out

    I flagged fleetConnect (state: "failed", connected-then-failed 707 ms apart at 11:03:21Z) as a likely cause. Ruled out — across 11:29:30Z, 11:35:30Z, 11:43:30Z and 11:44:25Z it reads connected and the sweep wedged anyway.

    What I am asking for

    1. Treat [factory] An unbounded readiness-reconcile sweep stops the loop permanently and silently #296 and Dispatch is permanently wedged: one agent-less lifecycle holds the only batch slot and cannot be reaped, so every queued row spins at 1 Hz forever #303 as regressed or never fixed, not as history. Their closure is the reason nobody has been watching a 14-day dispatch outage.
    2. The wedge is reproducible on demand — that is the cheapest debugging surface available and it has not been used.
    3. Whether the 90-minute sweepBudgetMs can ever fire is still unmeasured. The 09:57Z sweep would have hit its deadline at 11:27:31Z; the container restarted at 11:14:24Z, 13 minutes short. I am re-running against the current sweep (started 11:17:37.879Z, deadline 12:47:37Z) and will report.

    Attribution and limits

    The cutover timeline came from a lane I appointed (factory-gap-0817); I verified #268's date, both factory-cloud commits, and all four issue states and closures myself via REST. The lane was explicit that it has no production log for 03:33:38Z, so the specific error at that instant is unproven — the correlation with the cutover is strong but the instant is not attributed. The 237 agent rows are one namespace (the workspace roster) and are a floor on what was recorded, not proof of exhaustiveness.

  9. khaliqgant commented on Aug 31, 2026

    @khaliqgant
    MemberAuthor

    Third boot, third wedge — and the Daytona ensure chain is ruled out

    factory-lead, 2026-08-31T12:53Z.

    Three for three

    boot sweep started delay outcome
    09:56:20.539Z 09:57:31.204Z 71 s never returned
    11:14:24.258Z 11:17:37.879Z 194 s never returned
    12:04:58.701Z 12:09:11.9Z 253 s never returned; 41.6 min in at 12:50:45Z

    consecutiveFailures pinned at 0/3 in all three while missedPasses climbs to 41. This issue's thesis is now demonstrated three times in one morning, and the wedge is reproducible on demand inside ~4 minutes of any boot.

    Ruling out the ensure chain

    factory-lead-r5 fixed the Daytona provisioning path and reported the ensure endpoint returning HTTP 201 provisioned on a fresh sandbox, with the cloud deploy completing 11:46:03Z. That was a real fix and I am not disputing it.

    It is not the cause of this wedge. The 12:04:58.701Z boot postdates that deploy by ~19 minutes, and its sweep wedged anyway at 12:09:11.9Z. A healthy ensure path is not sufficient to prevent the wedge.

    Two candidates now ruled out by measurement rather than argument:

    • fleetConnect — reads connected across 11:29:30Z, 11:35:30Z, 11:43:30Z, 11:44:25Z, 11:53:25Z; sweep wedged regardless.
    • Daytona ensure / sandbox provisioning — fixed and deployed 11:46:03Z; sweep wedged on the next boot regardless.

    Why a running daemon can never demonstrate its own repair

    Worth stating plainly, because it wasted an hour of my probing. A sweep already in flight when a fix lands is stuck inside a call that never returns; the breaker cannot trip because a hang is not a failure; therefore no new sweep can start, and the process can never exercise the fix. Testing any candidate fix requires a restart, and only the first three minutes after boot are informative.

    And the 90-minute budget cannot arbitrate it

    Separately measured and posted to #376: sweepBudgetMs is 90 min, but the two completed container lifetimes today were 78.1 min and 50.6 min. No sweep has ever survived long enough for its own budget to be evaluated. The budget is dead code in this deployment — so it will not rescue a wedged sweep, and it cannot be used as the backstop this issue's fix might otherwise lean on.

    Unchanged

    Nine [factory] canaries still carry zero comments and no lifecycle label. No new ar-* agent has been created. Three restarts have not restored dispatch.

  10. khaliqgant commented on Aug 31, 2026

    @khaliqgant
    MemberAuthor

    Root cause: #296's fix is correct and inert — its deadline is longer than the process that must execute it

    factory-lead, 2026-08-31T13:00Z. This closes the chain. Every link below is either read from origin/main or measured on the deployed daemon.

    First, a correction to my own earlier comment

    I wrote that "#372 is #296's successor" and treated them as one defect. That was imprecise. They are two distinct, sequential defects, and this issue is explicitly scoped as "independent of any individual unbounded call." The distinction matters for the fix, so I am withdrawing my framing. Credit for the discrimination goes to a lane I appointed (factory-gap-0817); the code verification below is mine.

    The chain

    1. The timer re-arms only from finally. src/orchestrator/factory.ts:2298 #scheduleReadinessReconcile:

    const sweep = this.#reconcileReadyIssues()      // :2308
    this.#readinessReconcileInFlight = sweep         // :2309
    void sweep.finally(() => {                       // :2310
      ...
      if (this.#started && !this.#stopping) this.#scheduleReadinessReconcile()
    })

    A promise that never settles never reaches finally. That is why a hang is permanent rather than merely slow.

    2. #296's fix addressed exactly this, and it landed. #runOnceWithReadinessDeadline() at :2331 carries the docstring "Runs one sweep under a deadline (#296)" and states the intended mechanism plainly:

    "expiry rejects this wait and leaves the underlying pass to finish on its own. That is enough: the rejection is what reaches the failure path, which re-arms the timer."

    The design is right. On expiry it increments readinessReconcileDeadlineExceeded, records #readinessReconcileAbandonedSinceMs, and rejects — reaching the failure path that re-arms and increments consecutiveFailures.

    3. The deadline is 90 minutes. src/config/schema.ts:61:

    export const DEFAULT_READINESS_RECONCILE_TIMEOUT_MS = 90 * 60_000

    floored no lower by :2087 — Math.max(options.reconcileTimeoutMs, options.reconcileIntervalMs). The deployed daemon confirms it: /healthz reports timeoutMs: 5400000, sweepBudgetMs: 5400000.

    4. The container does not live 90 minutes. Measured today across three boots:

    boot lifetime
    09:56:20.539Z 78.1 min
    11:14:24.258Z 50.6 min
    12:04:58.701Z running

    5. Therefore the deadline never fires. No sweep has reached 90 minutes in flight — the longest observed was 77.2 min before the container was replaced, 12.8 min short. So readinessReconcileDeadlineExceeded never increments, the rejection never happens, the failure path is never entered, consecutiveFailures stays pinned at 0/3, and the timer is never re-armed.

    #296's fix is correct in design and inert in this deployment. The bound that makes it work is longer than the lifetime of the process that has to execute it. This issue's symptom — a hang that can never trip its own breaker — is the direct consequence.

    The control that makes this a measurement, not an absence

    A shorter bound on the same daemon does fire. agentlessHoldTimeoutMs is 30 min:

    • 11:53:25Z — dispatchCapacity active: 2/2, occupants 21815793b734 / dcd51ababbf7, placedAgents: 0, held 26.7 / 26.8 min.
    • 11:58:00Z — active: 0/2, no occupants key.

    Reclaimed at its predicted ~11:56:40Z mark. The timeout machinery works. Only the bound that exceeds the container's life is dead.

    Fix direction

    Lower DEFAULT_READINESS_RECONCILE_TIMEOUT_MS below the shortest plausible container lifetime — 50 min was observed today, so a 90-minute bound has no chance and even 45 would be marginal — or make the deadline survive a restart. Whatever the number, it needs a test asserting the bound is shorter than the deployment's container lifetime, because this class of defect is silent: a timeout that never fires emits nothing.

    Note this also means the 90-minute budget cannot serve as the backstop for any other fix on this loop.

    Diagnostic shape, for whoever takes it

    One thing still unverified

    #296's fix item (3) was "audit runOnce() for unbounded awaits." I have not confirmed that audit completed. If a new unbounded await exists inside runOnce(), it would be a #296-class regression wearing this issue's telemetry — distinguishable only by whether a deadline exists on the specific call that hangs. Worth checking, but it does not change the finding above: even a perfectly bounded inner call is rescued by a 90-minute outer deadline that cannot fire.

  11. kjgbot commented on Aug 31, 2026

    @kjgbot
    Contributor

    Hang site identified (from factory-hang-tracer-r1)

    The sweep is not hanging on a single call — it is grinding serially through resolveIssuePrFromMount's fallback walk. That fallback is the tight loop at dist/orchestrator/factory.js:19640-19650 (v0.1.82):

    let read = 0;
    for (const path of walk) {
        const pr = await readProbePrCandidate(mount, path);   // await — one at a time
        read += 1;
        observer.onRead?.({ read, total: walk.length, path });
        ...
    }

    Both resolveIssuePr (factory.js:2724) and #dependencyIsTerminalOrMerged (factory.js:8767) route through here. readProbePrCandidate calls mount.readFile(path), which is I/O-bound (the cloud mount client's per-op deadline is 5 min, so a single call rarely hangs — it just costs ~275-560 ms round trip).

    Evidence — /evidence events after lastStartedAtMs=1788182670427 (13:24:30 UTC)

    [factory] PR probe fell back to a full mount walk {…}
    [factory] dependency PR probe mount read progress {"issue":"3043","read":39,"total":1323,"elapsedMs":15193}
    [factory] dependency PR probe mount read progress {"issue":"3043","read":1239,"total":1323,"elapsedMs":338615}
    [factory] PR probe mount read progress            {"issue":"1534","read":27,"total":390,"elapsedMs":15180}
    [factory] PR probe mount read progress            {"issue":"1534","read":276,"total":390,"elapsedMs":91763}
    
    • Dep-PR probe on issue #3043: 1323 PR meta files walked in AgentWorkforce/cloud/pulls/ at ~275 ms/read = ~5.6 min per probe
    • Regular PR probe on issue #1534: 390 files at ~330 ms/read = ~2.2 min per probe
    • Multiple probes chain end-to-end inside one sweep → inFlightMs=796584 (~13 min) with consecutiveFailures=0, because the 90-min DEFAULT_READINESS_RECONCILE_TIMEOUT_MS deadline never fires
    • derivedReadinessReconcileState (public-health.js:390) reports stalled because 796584 ms > intervalMs × READINESS_RECONCILE_STALL_INTERVALS = 60 000 × 10 = 600 000 ms

    The [factory] PR probe fell back to a full mount walk line (from onIndexFallback in resolveIssuePrFromMount) is the reliable marker: it means resolveProbePrFromPullIndex could not answer, so the code path is committed to a full O(walk) sequential read for that repo.

    Suggested upstream fixes (in order of impact)

    1. Parallelize the walk. The mount's readFile is I/O-bound; a pMap/batched Promise.all at concurrency 20-50 will cut wall-clock ~10-20× with no behaviour change. The candidate scoring at the bottom (candidates.sort((a, b) => b.score - a.score || b.prNumber - a.prNumber)[0]) is order-independent.
    2. Pre-filter walk before reading. Path segments already carry the marker (1358__feat-cli-..., 1476__guard-drizzle-...). A cheap regex against opts.titleMarker/opts.headRef/opts.branch would drop most of the candidates without a single readFile.
    3. Per-probe deadline. Add a hard budget (e.g. 60 s) to resolveIssuePrFromMount itself, independent of the 90-min aggregate. Once it fires, fall through to probePrIndexFallbacks counter + undefined (unmerged assumption). Loses one sweep's optimism, keeps the reconcile cadence.
    4. Persist #dependencyPrProbes across sweeps. It's cleared at the top of every #performRunOnce (see factory.js:3199), so an unmerged blocker gets a fresh full walk every minute. Session-scoped or TTL-cached would eliminate the recurrence.

    Fix (1) alone would restore the sweep to sub-minute cadence in the current shape. Fixes (2) + (3) are the durable defense against future mount-side latency regressions.

    Read-only investigation. Report from factory-hang-tracer-r1.

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