Skip to content

Rescan a queue whose dispatch admission expired - #4538

Open
yohamta0 wants to merge 9 commits into
mainfrom
fix/rescan-lost-dispatch-admission
Open

yohamta0 wants to merge 9 commits into
mainfrom
fix/rescan-lost-dispatch-admission

Conversation

@yohamta0

@yohamta0 yohamta0 commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

When a coordinator binds a queue admission after it has expired, it deletes the admission and refuses the handoff with dispatch admission not found. The run stays queued, but nothing in the queue's state changes, so the queue scan waited out the 30 s fallback interval before it tried again. On a loaded CI runner this made TestDistributedRun_WorkerCrash_MarkedFailed flaky (PR #4535, Ubuntu job): the scheduler reserved at 16:41:24.675, the coordinator bound at 16:41:29.864, after the test's 3 s TTL, and the run missed its 15 s deadline.

Changes

  • The scheduler now treats a refusal for a lost admission as "rescan now". The next queue pass, still held to the 3 s minimum processing interval, reserves a new admission and dispatches the run again.
    • Before: Failed to dispatch DAG; leaving it queued for the next scan, then Queue scan parked until relevant state changes for up to 30 s.
    • After: the same warning, then the next pass dispatches the run.
  • Other dispatch failures still wait for a queue, worker, or capacity change, or for the fallback interval. The rescan covers the whole queue, so when a lost admission and another failure land in the same pass, both runs retry on the next pass.
  • Test helper: the dispatch store's reservation TTL is set by a new option, test.WithDispatchReservationTTL. Previously it reused the lease threshold from test.WithStaleThresholds, whose signature is unchanged. Only the two tests that check behavior past the reservation TTL set it.
    • This TTL controls only the coordinator's bind check. The scheduler still passes LeaseStaleAfter (3 s in these tests) as StaleThreshold to ReserveAdmission, and its CleanupAdmissions can drop an admission older than that if no execution has started. A later reservation can therefore still remove a 3 s old admission in the zombie tests. The rescan in this PR dispatches that run again.

Core change

The dispatcher already belongs to a single scan. It now records that the coordinator refused a handoff because the admission was gone. When the batch is done, the scan sets its retry deadline to now instead of now plus the fallback interval. The next pass then unparks even though the queue generation has not changed.

internal/service/scheduler/queue_dispatcher.go:1022

		if isDispatchAdmissionLost(err) {
			d.admissionLost.Store(true)
		}
		logger.Warn(ctx, "Failed to dispatch DAG; leaving it queued for the next scan", tag.Error(err))

internal/service/scheduler/queue_dispatcher.go:1684

var dispatchAdmissionLostMessage = "failed to enqueue task: " + dispatch.ErrDispatchAdmissionNotFound.Error()

func isDispatchAdmissionLost(err error) bool {
	var withStatus interface{ GRPCStatus() *status.Status }
	if !errors.As(err, &withStatus) {
		return false
	}
	st := withStatus.GRPCStatus()
	return st.Code() == codes.FailedPrecondition && st.Message() == dispatchAdmissionLostMessage
}

internal/service/scheduler/queue_processor.go:645

	retryAt := time.Now().Add(p.fallbackInterval)
	if dispatcher.admissionLost.Load() {
		retryAt = time.Now()
	}
	q.deferScan(generation, retryAt)

Testing

  • New TestQueueProcessor_RedispatchesAfterAdmissionExpires (scheduler package). The first handoff deletes the admission and returns the coordinator's error, and the test then runs two queue passes. It fails without the fix: the second pass stays parked, giving 1 dispatch instead of 2, and the item remains queued.
  • TestQueueProcessor_DefersUnchangedDistributedDispatchFailure still passes, so other dispatch failures are still deferred. A new case there sends a different FailedPrecondition refusal whose message contains "dispatch admission not found"; it stays deferred because the match must equal the coordinator's exact message.
  • go test ./internal/service/scheduler/ passes.
  • Ran locally in internal/intg/distr: the zombie recovery tests, TestExecution_QueuedDispatch_WaitsForBusyWorker, TestSubDAG_WaitsForBusyWorker, and TestDistributedRun_ServiceDAGRestartsOnAnotherWorkerAfterCrash. All pass.

Performance

Low risk. The change only affects a scan in which the coordinator refused a handoff for a lost admission. Production admissions expire after 90 s, so that happens only when a handoff takes longer than that. Such a scan reruns after the 3 s minimum processing interval instead of 30 s. It does one bounded queue page read and one admission reservation per retried run, and each reservation scans the shared admission records. Other runs that failed in the same pass retry with it. It stops once the run is dispatched. Nothing new is persisted, no ticker or watcher is added, and the cost does not depend on stored runs or DAG count.

Review guide

The dispatch retry flow changes. Only the dashed edge is new.

flowchart LR
  A[Scan reserves admission] --> B[Handoff to coordinator]
  B -->|bound| C[Dequeue item]
  B -->|admission not found| D[Item stays queued]
  B -->|other failure| E[Item stays queued]
  E --> F[Wait for state change or 30 s fallback]
  D -.->|new: retryAt = now| G[Next pass after 3 s min interval]
  G --> A
  F --> A
Loading
  • Needs judgment: queue_dispatcher.go, which classifies the error, and queue_processor.go, which sets the retry deadline.
  • Mechanical: internal/test/helper.go and internal/intg/distr/*, which separate the reservation TTL from the lease threshold.

Agent

Claude Code, claude-opus-5-5, high

@yohamta0 yohamta0 added perf:network May change UI polling, SSE traffic, or worker and coordinator messages perf:disk-io May read run or DAG files on a request or tick path perf:cpu May add a ticker, watcher, scan, or hot-path work, or idle cost labels Dec 2, 2026
@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 4b945731-5edb-4f1f-a92f-c6379278754b

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The test helper now configures dispatch reservation TTL separately from stale thresholds. When distributed handoff reports that admission was lost, the scheduler records that state and schedules the next queue scan immediately.

Changes: Dispatch admission and queue recovery

Layer / File(s) Summary
Configure dispatch reservation TTL
internal/test/helper.go, internal/intg/distr/fixtures_test.go, internal/intg/distr/zombie_recovery_test.go, internal/intg/distr/queue_recovery_test.go, internal/intg/distr/subdag_test.go
Test options and fixtures now pass a separate dispatch reservation TTL. Busy-worker tests use that TTL for their wait durations.
Retry queue dispatch after lost admission
internal/service/scheduler/queue_dispatcher.go, internal/service/scheduler/queue_processor.go, internal/service/scheduler/queue_processor_test.go
The dispatcher records missing admission errors, and the queue processor schedules an immediate scan when admission was lost. A test verifies that the queued item is dispatched and removed.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

Possibly related PRs

Merge Risk: Minimal · previous review 265ef

The change makes the scheduler rescan a queue immediately when a dispatch admission has expired, and it gives distributed tests an independent reservation TTL. Source inspection found no concrete defect, so merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Rescan a queue whose dispatch admission expired" names the main change: when a coordinator refuses a handoff because the queue admission expired, the scheduler rescans immediately instead o…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the template's main sections: Summary, Changes, Core change, Testing, and Performance. It also includes a Review guide and an Agent line. It explains the problem, the fix, the …
Full details: Title check

Explanation

The title "Rescan a queue whose dispatch admission expired" names the main change: when a coordinator refuses a handoff because the queue admission expired, the scheduler rescans immediately instead of waiting for the fallback interval. It is specific, concise, and matches the scheduler and queue processor changes. It does not mention the helper signature change, which is a secondary change.

Full details: Description check

Explanation

The description follows the template's main sections: Summary, Changes, Core change, Testing, and Performance. It also includes a Review guide and an Agent line. It explains the problem, the fix, the new helper option, and the test results. Two template items are missing or weak: the Related Issues section is absent, and the Checklist from the template is not carried over. The Summary does not state the PR number clearly, though it cites PR #4535 as the flaky test's source while the objectives cite #4538 as this PR. The Changes section does not show user-visible before and after behavior beyond log messages, which is acceptable because the change is internal scheduler behavior.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 0f4e242c-0f72-4f8e-b43e-f31d744651ec
Commits

Reviewing files that changed from the base of the PR and between 50ab52a and 265efa1.

Files selected for processing: 8

  • internal/intg/distr/fixtures_test.go
  • internal/intg/distr/queue_recovery_test.go
  • internal/intg/distr/subdag_test.go
  • internal/intg/distr/zombie_recovery_test.go
  • internal/service/scheduler/queue_dispatcher.go
  • internal/service/scheduler/queue_processor.go
  • internal/service/scheduler/queue_processor_test.go
  • internal/test/helper.go

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@greptile-apps

greptile-apps Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge.

Summary

Queued runs retry on the next queue pass when the coordinator rejects an expired or missing admission.

  • The scheduler retries runs after their queue admission expires.
  • Distributed tests set dispatch expiry separately from lease timing.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Reserve admission] --> B[Coordinator handoff]
  B -->|Accepted| C[Remove queue item]
  B -->|Admission missing| D[Keep queue item]
  D -.->|New: retry next pass| A
  B -->|Other failure| E[Wait for state change or fallback]
  E --> A
Loading

Reviews (1) · Last reviewed commit: "Give distributed tests their own reserva..." · Reviewed by Greptile

@yohamta0 yohamta0 added the full-ci Run the Windows, conformance, and E2E checks on this pull request label Dec 2, 2026

@yohamta0 yohamta0 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

// isDispatchAdmissionLost reports a handoff the coordinator refused because
// its queue admission had expired or been released before it was bound.
func isDispatchAdmissionLost(err error) bool {
if errors.Is(err, dispatch.ErrDispatchAdmissionNotFound) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

Claude Opus 5.5 with xhigh responding on behalf of Yota

nit: This errors.Is branch never matches. Only the coordinator calls BindAdmission, so the sentinel always reaches the scheduler as a gRPC status. The new test also covers only the status branch. Consider dropping it so the helper describes the one path that exists.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

Claude Opus 5.5 with high responding on behalf of Yota

Dropped the errors.Is branch in 509c3d8. The helper now checks only the gRPC status path that the coordinator returns.

// withDispatchReservationTTL sets how long a task claim or queue admission
// may go without its worker's acceptance before the dispatch store releases
// it.
func withDispatchReservationTTL(ttl time.Duration) fixtureOption {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

Claude Opus 5.5 with xhigh responding on behalf of Yota

nit: This TTL now drives only the coordinator's bind check. The scheduler still passes LeaseStaleAfter (3 s in these tests) as StaleThreshold to ReserveAdmission, and its CleanupAdmissions deletes any admission older than that which has no execution evidence. So in the zombie tests, a later reservation can still drop a 3 s old admission, and the rescan in this PR is what recovers it. Consider stating that here, or softening the PR body's "no longer also shorten admission expiry". Otherwise the next flake from that path looks like a TTL regression.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

Claude Opus 5.5 with high responding on behalf of Yota

Fixed in 8fc6592. The fixture comment now says this TTL controls only the coordinator's bind check, that the scheduler's ReserveAdmission cleanup still uses LeaseStaleAfter, and that the rescan dispatches the run again. The PR body states the same and no longer says admission expiry is decoupled.

Comment thread internal/test/helper.go Outdated
// WithStaleThresholds overrides the worker heartbeat, run lease, and dispatch
// reservation staleness thresholds used by distributed test helpers. A zero
// value keeps the default.
func WithStaleThresholds(heartbeat, lease, reservation time.Duration) HelperOption {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

Claude Opus 5.5 with xhigh responding on behalf of Yota

nit: Three positional time.Durations are easy to transpose, and the fixture already exposes the TTL as its own option. A separate WithDispatchReservationTTL(ttl) here would match withDispatchReservationTTL and leave this signature as it was.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

Claude Opus 5.5 with high responding on behalf of Yota

Done in 8fc6592. Added test.WithDispatchReservationTTL(ttl), and WithStaleThresholds has its original two-argument signature again.

A coordinator that receives a handoff after its queue admission expired
deletes the admission and refuses with "dispatch admission not found".
The run stays queued, but nothing about the queue's state changes, so
the scan stayed deferred for the 30 s fallback interval before trying
again. On a loaded host that delay outlasted run deadlines.

Record the lost admission during the scan and schedule the next pass
at once, still held to the minimum processing interval, so the run is
dispatched again under a new admission.
The test helper reused the stale lease threshold as the dispatch
reservation TTL, so every test that shortened lease expiry to 3 s also
expired queue admissions after 3 s. A worker-crash test then failed on
a slow runner when the coordinator bound its admission too late.

Add the reservation TTL as a separate stale threshold that defaults to
the store's own, and set it only in the tests that check behavior past
the reservation TTL.
Only the coordinator binds admissions, so the scheduler always sees the
not-found refusal as a gRPC status. The direct sentinel check could
never match.
Three positional durations are easy to transpose. A separate helper
option keeps WithStaleThresholds as it was and matches the fixture's
own option. The fixture comment now states that the scheduler's
admission cleanup still follows the lease threshold.
@yohamta0
yohamta0 force-pushed the fix/rescan-lost-dispatch-admission branch from 8fc6592 to d60a84b Compare December 3, 2026 01:38

@yohamta0 yohamta0 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

Bind applies only to queue admissions. An expired task claim returns
to pending through the dispatch store's own claim logic, so the fixture
comment now names each path.
The check matched any FailedPrecondition status whose message contained
"dispatch admission not found", so an unrelated refusal that mentions
those words, such as a missing dependency file, rescanned the queue
every few seconds instead of waiting for the fallback interval. Compare
the coordinator's status message itself against its bind refusal.

This branch has not been deployed

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

Labels

full-ci Run the Windows, conformance, and E2E checks on this pull request perf:cpu May add a ticker, watcher, scan, or hot-path work, or idle cost perf:disk-io May read run or DAG files on a request or tick path perf:network May change UI polling, SSE traffic, or worker and coordinator messages

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant