Skip to content

dispatch

dispatch

Baton dispatch logic — ready sheet resolution and dispatch.

Called after every event in the baton's main loop. Finds sheets that are ready to execute and dispatches them via a callback, respecting:

  • Global concurrency limit (max_concurrent_sheets)
  • Per-instrument concurrency limits
  • Instrument rate limit state
  • Circuit breaker state
  • Cost limits (future — checked but not enforced here)
  • Backpressure (checked via baton._shutting_down)

The dispatch function is stateless — it reads baton state, makes decisions, and calls the dispatch callback. It does not own any state of its own.

Design notes: - dispatch_ready() is a free function, not a method on BatonCore. This keeps the core focused on state management and event handling. The conductor calls dispatch_ready() after the baton processes each event. - The dispatch callback is async to allow backend acquisition and task creation. - Sheets are marked as 'dispatched' by the callback, not by dispatch_ready(). This ensures that only actually-dispatched sheets consume concurrency slots.

See: docs/plans/2026-03-26-baton-design.md — Dispatch Logic section

Attributes

Classes

DispatchConfig dataclass

DispatchConfig(max_concurrent_sheets=10, instrument_concurrency=dict(), model_concurrency=dict(), rate_limited_instruments=set(), open_circuit_breakers=set(), stagger_delay_ms=0, job_max_concurrent=dict(), job_stagger_delay_ms=dict(), active_executions=None, time_fn=monotonic)

Configuration for the dispatch logic.

Attributes:

Name Type Description
max_concurrent_sheets int

Global ceiling on concurrent sheet tasks.

instrument_concurrency dict[str, int]

Per-instrument concurrency limits (fallback when no model-specific limit exists).

model_concurrency dict[str, int]

Per-(instrument, model) concurrency limits. Keys are "instrument:model" strings. Takes priority over instrument_concurrency when the sheet has a known model.

rate_limited_instruments set[str]

Set of instrument names currently rate-limited.

open_circuit_breakers set[str]

Set of instrument names with open circuit breakers.

stagger_delay_ms int

Minimum spacing (ms) between dispatches of sheets sharing an instrument (#340). 0 = no stagger (all same-instrument ready sheets dispatch in one cycle, the historical behavior).

time_fn Callable[[], float]

Monotonic clock source for the stagger gate. Injectable for deterministic tests; defaults to time.monotonic.

job_max_concurrent dict[str, int]

Per-job ceilings for parallel-enabled jobs only.

job_stagger_delay_ms dict[str, int]

Per-job same-instrument stagger policy.

active_executions dict[tuple[str, int], tuple[str, str | None]] | None

Physical musician occupancy keyed by job/sheet, with the actual instrument/model acquired for that task. None preserves state-based behavior for direct and legacy callers.

DispatchResult dataclass

DispatchResult(dispatched_count=0, dispatched_sheets=list(), blocked_sheets=list(), skipped_reasons=dict())

Result of a dispatch_ready() call.

Provides feedback on what happened: how many sheets were dispatched, which ones, and why others were skipped.

Methods:
record_dispatch
record_dispatch(job_id, sheet_num)

Record a successful dispatch.

Source code in src/marianne/daemon/baton/dispatch.py
def record_dispatch(self, job_id: str, sheet_num: int) -> None:
    """Record a successful dispatch."""
    self.dispatched_count += 1
    self.dispatched_sheets.append((job_id, sheet_num))
record_skip
record_skip(reason, *, job_id=None, sheet_num=None, blocked_changed=False)

Record a skipped sheet with reason.

Source code in src/marianne/daemon/baton/dispatch.py
def record_skip(
    self,
    reason: str,
    *,
    job_id: str | None = None,
    sheet_num: int | None = None,
    blocked_changed: bool = False,
) -> None:
    """Record a skipped sheet with reason."""
    self.skipped_reasons[reason] = self.skipped_reasons.get(reason, 0) + 1
    if blocked_changed and job_id is not None and sheet_num is not None:
        self.blocked_sheets.append((job_id, sheet_num))

Functions:

dispatch_ready async

dispatch_ready(baton, config, callback)

Find and dispatch all sheets that are ready to execute.

Called after every event in the baton's main loop. This is the only place where sheets move from 'pending'/'ready' to 'dispatched'.

Parameters:

Name Type Description Default
baton BatonCore

The baton core (provides sheet state and job registry).

required
config DispatchConfig

Dispatch configuration (concurrency limits, etc.).

required
callback DispatchCallback

Async function called for each sheet to dispatch. Receives (job_id, sheet_num, sheet_state).

required

Returns:

Type Description
DispatchResult

DispatchResult with counts of dispatched and skipped sheets.

Source code in src/marianne/daemon/baton/dispatch.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
async def dispatch_ready(
    baton: BatonCore,
    config: DispatchConfig,
    callback: DispatchCallback,
) -> DispatchResult:
    """Find and dispatch all sheets that are ready to execute.

    Called after every event in the baton's main loop. This is the
    only place where sheets move from 'pending'/'ready' to 'dispatched'.

    Args:
        baton: The baton core (provides sheet state and job registry).
        config: Dispatch configuration (concurrency limits, etc.).
        callback: Async function called for each sheet to dispatch.
            Receives (job_id, sheet_num, sheet_state).

    Returns:
        DispatchResult with counts of dispatched and skipped sheets.
    """
    result = DispatchResult()

    # Don't dispatch during shutdown
    if baton._shutting_down:
        return result

    # #340: dispatch stagger — `now` and the skip flag drive the per-instrument
    # last-dispatch-time gate below.
    now = config.time_fn()
    # Wake requests retain the generation that encountered the gate because a
    # later callback can deregister or replace the job before timer scheduling.
    stagger_wake_delays: dict[str, tuple[float, int]] = {}

    # Track running counts per model key (instrument:model or just instrument)
    occupied = _occupied_executions(baton, config)
    model_running = _count_occupied_per_model(occupied)
    job_running = _count_occupied_per_job(occupied)
    global_running = len(occupied)

    for job_id in list(baton._jobs.keys()):
        job = baton._jobs.get(job_id)
        if job is None:
            continue

        if job.paused:
            continue

        ready = baton.get_ready_sheets(job_id)
        if ready:
            _logger.info(
                "dispatch.ready_sheets",
                extra={
                    "job_id": job_id,
                    "ready_count": len(ready),
                    "global_running": global_running,
                    "max_concurrent": config.max_concurrent_sheets,
                    "rate_limited": list(config.rate_limited_instruments),
                },
            )
        for sheet in ready:
            registration_token = job.registration_token
            event_generation = job.event_generation
            # A rate-limit/fallback transition may relabel a sheet PENDING while
            # its original musician is still exiting. Never dispatch the same
            # sheet again until physical task authority is released.
            if (job_id, sheet.sheet_num) in occupied:
                _record_dispatch_block(
                    result,
                    job_id=job_id,
                    sheet=sheet,
                    reason="active_execution",
                    skip_key="active_execution",
                )
                continue

            # Check global concurrency
            if global_running >= config.max_concurrent_sheets:
                _logger.debug(
                    "dispatch.skip.global_concurrency",
                    extra={
                        "job_id": job_id,
                        "sheet_num": sheet.sheet_num,
                        "global_running": global_running,
                        "limit": config.max_concurrent_sheets,
                    },
                )
                _record_dispatch_block(
                    result,
                    job_id=job_id,
                    sheet=sheet,
                    reason="global_concurrency",
                    skip_key="global_concurrency",
                    details={
                        "global_running": global_running,
                        "limit": config.max_concurrent_sheets,
                    },
                )
                return result  # Hard stop — can't dispatch more

            # A score may use fewer slots than the daemon's global ceiling.
            # Continue to the next job when this one is full so it cannot
            # consume or strand another job's capacity.
            job_limit = config.job_max_concurrent.get(job_id)
            current_job_running = job_running.get(job_id, 0)
            if job_limit is not None and current_job_running >= job_limit:
                _record_dispatch_block(
                    result,
                    job_id=job_id,
                    sheet=sheet,
                    reason="job_concurrency",
                    skip_key=f"job_concurrency:{job_id}",
                    details={
                        "job_running": current_job_running,
                        "limit": job_limit,
                    },
                )
                continue

            # `balance` alias modifier (#473): before the capacity checks, start
            # this sheet on whichever chain entry carries the least live load,
            # measured as occupied slots over that entry's cap. Only a sheet
            # still on its primary with no attempt yet is rebalanced, so a
            # sheet that already ran (or fell back) keeps its route; the
            # choice is recorded in the fallback history as "balance".
            if (
                sheet.balance_chain
                and sheet.current_instrument_index == 0
                and not sheet.attempt_history
                and sheet.fallback_chain
            ):
                _balance_chain(sheet, config, model_running)

            # Check per-model concurrency (falls back to per-instrument)
            instrument = sheet.instrument_name or ""
            model_key = f"{instrument}:{sheet.model}" if sheet.model else instrument
            model_limit = config.model_concurrency.get(model_key)
            if model_limit is None:
                model_limit = config.instrument_concurrency.get(instrument)
            model_count = model_running.get(model_key, 0)
            if model_limit is not None and model_count >= model_limit:
                _logger.info(
                    "dispatch.skip.model_concurrency",
                    extra={
                        "job_id": job_id,
                        "sheet_num": sheet.sheet_num,
                        "model_key": model_key,
                        "model_count": model_count,
                        "model_limit": model_limit,
                    },
                )
                _record_dispatch_block(
                    result,
                    job_id=job_id,
                    sheet=sheet,
                    reason="model_concurrency",
                    skip_key=f"model_concurrency:{model_key}",
                    details={
                        "instrument": instrument,
                        "model_key": model_key,
                        "model_count": model_count,
                        "model_limit": model_limit,
                    },
                )
                continue

            # Check instrument rate limit. A limit is transient, so a sheet with
            # no fallback waits for RateLimitExpired. A sheet WITH a fallback
            # advances to it here, the same transition _handle_rate_limit_hit
            # makes for an in-flight sheet: a reopened loop member comes back
            # on its primary (reset_for_flow rewinds the chain) and would
            # otherwise wait out the whole limit while its fallbacks sit idle
            # (GH #521: a day-long quota timer, three idle seats).
            if instrument in config.rate_limited_instruments:
                advanced_to = baton._advance_rate_limited_sheet(sheet, job_id, config)
                if advanced_to is not None:
                    instrument = advanced_to
                else:
                    _logger.info(
                        "dispatch.skip.rate_limited",
                        extra={
                            "job_id": job_id,
                            "sheet_num": sheet.sheet_num,
                            "instrument": instrument,
                        },
                    )
                    _record_dispatch_block(
                        result,
                        job_id=job_id,
                        sheet=sheet,
                        reason="rate_limited",
                        skip_key=f"rate_limited:{instrument}",
                        details={"instrument": instrument},
                    )
                    continue

            # Check instrument availability — try fallback chain when
            # circuit breaker is OPEN or instrument is unregistered.
            # Loop to handle chains where multiple fallbacks are also
            # unavailable (e.g., claude-code→gemini-cli→ollama when
            # both claude-code and gemini-cli are OPEN).
            _skipped = False
            capacity_checked_instrument = instrument
            while (
                instrument in config.open_circuit_breakers
                or instrument not in baton._instruments
            ):
                if baton._check_and_fallback_unavailable(sheet, job_id):
                    instrument = sheet.instrument_name or ""
                    # Check if the new instrument is rate-limited
                    if instrument in config.rate_limited_instruments:
                        _record_dispatch_block(
                            result,
                            job_id=job_id,
                            sheet=sheet,
                            reason="rate_limited",
                            skip_key=f"rate_limited:{instrument}",
                            details={"instrument": instrument},
                        )
                        _skipped = True
                        break
                    # Loop continues to check the new instrument
                else:
                    _record_dispatch_block(
                        result,
                        job_id=job_id,
                        sheet=sheet,
                        reason="circuit_breaker",
                        skip_key=f"circuit_breaker:{instrument}",
                        details={"instrument": instrument},
                    )
                    _skipped = True
                    _logger.warning(
                        "baton.dispatch.all_instruments_circuit_broken",
                        extra={
                            "job_id": job_id,
                            SHEET_NUM_KEY: sheet.sheet_num,
                            "instrument": instrument,
                        },
                    )
                    break
            if _skipped:
                continue
            if instrument != capacity_checked_instrument:
                model_key = f"{instrument}:{sheet.model}" if sheet.model else instrument
                model_limit = config.model_concurrency.get(model_key)
                if model_limit is None:
                    model_limit = config.instrument_concurrency.get(instrument)
                model_count = model_running.get(model_key, 0)
                if model_limit is not None and model_count >= model_limit:
                    _logger.info(
                        "dispatch.skip.model_concurrency",
                        extra={
                            "job_id": job_id,
                            "sheet_num": sheet.sheet_num,
                            "model_key": model_key,
                            "model_count": model_count,
                            "model_limit": model_limit,
                        },
                    )
                    _record_dispatch_block(
                        result,
                        job_id=job_id,
                        sheet=sheet,
                        reason="model_concurrency",
                        skip_key=f"model_concurrency:{model_key}",
                        details={
                            "instrument": instrument,
                            "model_key": model_key,
                            "model_count": model_count,
                            "model_limit": model_limit,
                        },
                    )
                    continue

            # #340: stagger gate — skip if a sheet on this instrument was
            # dispatched within the stagger window. Spreads a burst of
            # simultaneously-ready same-instrument sheets to avoid a
            # same-provider API burst. A sheet arriving more than stagger_delay
            # after the previous dispatch passes immediately (collision-only).
            has_job_stagger = job_id in config.job_stagger_delay_ms
            stagger_delay_ms = config.job_stagger_delay_ms.get(
                job_id, config.stagger_delay_ms
            )
            if stagger_delay_ms > 0:
                if has_job_stagger:
                    last_dispatch_at = baton._job_last_dispatch_at.get(
                        (job_id, instrument), 0.0
                    )
                else:
                    inst_state = baton.get_instrument_state(instrument)
                    last_dispatch_at = inst_state.last_dispatch_at if inst_state else 0.0
                elapsed = now - last_dispatch_at
                if elapsed < stagger_delay_ms / 1000.0:
                    remaining_ms = max(
                        0,
                        int(
                            stagger_delay_ms
                            - elapsed * 1000.0
                        ),
                    )
                    _record_dispatch_block(
                        result,
                        job_id=job_id,
                        sheet=sheet,
                        reason="stagger",
                        skip_key=f"stagger:{instrument}",
                        details={
                            "instrument": instrument,
                            "stagger_delay_ms": stagger_delay_ms,
                            "remaining_ms": remaining_ms,
                        },
                    )
                    remaining_seconds = max(0.0, stagger_delay_ms / 1000.0 - elapsed)
                    wake_key = job_id if has_job_stagger else "__legacy__"
                    wake_generation = registration_token if has_job_stagger else 0
                    previous = stagger_wake_delays.get(wake_key)
                    if previous is None or remaining_seconds < previous[0]:
                        stagger_wake_delays[wake_key] = (
                            remaining_seconds,
                            wake_generation,
                        )
                    continue

            # Dispatch!
            try:
                dispatch_accepted = await callback(job_id, sheet.sheet_num, sheet)
                # The callback may await backend acquisition or cleanup.
                # Validate before every outcome branch: if this job ID was
                # reused, the remainder of the old ready snapshot is invalid.
                if not baton.is_job_registration_current(
                    job_id, registration_token
                ):
                    break
                if dispatch_accepted is False:
                    continue
                if baton.get_sheet_state(job_id, sheet.sheet_num) is not sheet:
                    continue
                sheet.clear_dispatch_block()
                # Status set through event handler for traceability.
                # Called synchronously so concurrency counting works
                # within this dispatch cycle.
                baton._handle_sheet_dispatched(SheetDispatched(
                    job_id=job_id,
                    sheet_num=sheet.sheet_num,
                    instrument=instrument,
                    event_generation=event_generation,
                ))
                result.record_dispatch(job_id, sheet.sheet_num)
                global_running += 1
                job_running[job_id] = current_job_running + 1
                model_running[model_key] = model_count + 1
                # Job-configured stagger is isolated. Direct callers that only
                # use DispatchConfig.stagger_delay_ms retain the historical
                # shared-instrument behavior.
                if has_job_stagger:
                    baton._job_last_dispatch_at[(job_id, instrument)] = now
                else:
                    inst_state = baton.get_instrument_state(instrument)
                    if inst_state is not None:
                        inst_state.last_dispatch_at = now
            except Exception:
                # Exception is another post-await continuation. Stop the old
                # snapshot before logging/continuing if the callback reused ID.
                if not baton.is_job_registration_current(
                    job_id, registration_token
                ):
                    break
                _logger.error(
                    "baton.dispatch.callback_failed",
                    extra={
                        "job_id": job_id,
                        SHEET_NUM_KEY: sheet.sheet_num,
                        "instrument": instrument,
                    },
                    exc_info=True,
                )

            # Recheck global limit after each dispatch
            if global_running >= config.max_concurrent_sheets:
                return result

    # #340: if any sheet was held back purely by the stagger gate, schedule a
    # one delayed wake per affected job so the loop re-evaluates after each
    # job's own window elapses
    # (liveness — no other event may arrive in an idle system). The gate keeps
    # all sheets in the ready pool (no deferred state), so the wake just re-runs
    # a normal dispatch cycle. Guarded so repeated cycles within a window don't
    # accumulate timers; each job key clears when its DispatchRetry is handled.
    if baton._timer is not None:
        for wake_key, (delay_seconds, generation) in stagger_wake_delays.items():
            if wake_key in baton._stagger_wake_handles:
                continue
            event_job_id = None if wake_key == "__legacy__" else wake_key
            if (
                event_job_id is not None
                and not baton.is_job_registration_current(event_job_id, generation)
            ):
                continue
            handle = baton._timer.schedule(
                delay_seconds,
                DispatchRetry(
                    stagger_job_id=event_job_id,
                    stagger_generation=generation,
                ),
            )
            baton._stagger_wake_handles[wake_key] = handle

    if result.dispatched_count > 0:
        _logger.info(
            "baton.dispatch.cycle_complete",
            extra={
                "dispatched": result.dispatched_count,
                "skipped": sum(result.skipped_reasons.values()),
            },
        )

    return result