Orchestrator¶
Runner¶
runner ¶
Orchestrator actor lifecycle -- the "thinking" layer above workers.
The orchestrator is a longer-lived LLM actor that: - Receives high-level goals (OrchestratorGoal messages) - Decomposes them into subtasks for workers (via decomposer.py) - Dispatches subtasks through the router and collects results - Synthesizes worker outputs into a coherent final answer (via synthesizer.py) - Performs periodic self-summarization checkpoints (via checkpoint.py)
This differs from PipelineOrchestrator in that it uses an LLM to dynamically decide which workers to invoke, rather than following a fixed stage sequence.
Message flow::
heddle.goals.incoming --> OrchestratorActor.handle_message()
--> GoalDecomposer breaks goal into subtasks
--> Publishes TaskMessages to heddle.tasks.incoming (one per subtask)
--> Subscribes to heddle.results.{goal_id} for worker responses
--> ResultSynthesizer combines results into a coherent answer
--> Publishes final TaskResult to heddle.results.{goal_id}
Concurrency model
The max_concurrent_goals config setting (default 1) controls how many
goals a single OrchestratorActor instance can process simultaneously.
With the default of 1, goals are queued and processed one at a time
(strict ordering). Higher values enable concurrent goal processing
within a single instance. For horizontal scaling, run multiple
OrchestratorActor instances with a NATS queue group.
All mutable state (conversation_history, checkpoint_counter) is per-goal
inside GoalState, so concurrent goals are fully isolated — no shared
mutable data, no locks required.
Within a single goal, subtasks are dispatched concurrently (all published to heddle.tasks.incoming at once) and results are collected as they arrive.
State tracking
The orchestrator is the ONLY stateful component in Heddle. It maintains:
- _active_goals: maps goal_id -> GoalState for in-flight goals
Each GoalState carries its own conversation_history and
checkpoint_counter so that concurrent goals never interfere.
Workers and the router are stateless by design.
See Also
heddle.orchestrator.pipeline -- PipelineOrchestrator (fixed stage sequence) heddle.orchestrator.decomposer -- GoalDecomposer (LLM-based task breakdown) heddle.orchestrator.synthesizer -- ResultSynthesizer (result combination) heddle.orchestrator.checkpoint -- CheckpointManager (context compression) heddle.core.messages -- all message schemas
GoalState
dataclass
¶
GoalState(goal: OrchestratorGoal, dispatched_tasks: dict[str, TaskMessage] = dict(), collected_results: dict[str, TaskResult] = dict(), start_time: float = time.monotonic(), conversation_history: list[dict[str, Any]] = list(), checkpoint_counter: int = 0)
Tracks the lifecycle of a single goal through decomposition and collection.
One GoalState exists per in-flight goal. It is created when a goal
arrives, populated during decomposition, updated as results trickle in,
and discarded after synthesis completes.
Conversation history and checkpoint state are per-goal so that concurrent
goals (max_concurrent_goals > 1) maintain fully isolated state — no
shared mutable data, no locks required.
Attributes:
| Name | Type | Description |
|---|---|---|
goal |
OrchestratorGoal
|
The original |
dispatched_tasks |
dict[str, TaskMessage]
|
Maps |
collected_results |
dict[str, TaskResult]
|
Maps |
start_time |
float
|
Monotonic timestamp when processing began. |
conversation_history |
list[dict[str, Any]]
|
Accumulated context entries for checkpoint decisions. Each entry is a compact summary of a completed goal. |
checkpoint_counter |
int
|
Monotonically increasing checkpoint version number for this goal's checkpoint chain. |
OrchestratorActor ¶
OrchestratorActor(actor_id: str, config_path: str, backend: LLMBackend, nats_url: str = 'nats://nats:4222', checkpoint_store: CheckpointStore | None = None, *, bus: Any | None = None)
Bases: BaseActor
Dynamic orchestrator actor -- LLM-driven goal decomposition and synthesis.
Unlike :class:PipelineOrchestrator which follows a fixed stage sequence,
this actor uses an LLM to dynamically reason about which workers to invoke
and how to combine their results.
Lifecycle per goal:
- Receive -- parse the incoming dict as an
OrchestratorGoal. - Decompose -- call :class:
GoalDecomposerto break the goal into a list ofTaskMessagesubtasks. - Dispatch -- publish each subtask to
heddle.tasks.incomingso the router can forward them to the appropriate workers. - Collect -- subscribe to
heddle.results.{goal_id}and gatherTaskResultmessages until all subtasks have responded or the timeout expires. - Synthesize -- call :class:
ResultSynthesizerto combine all collected results into a coherent final answer. - Publish -- send the synthesized
TaskResulttoheddle.results.{goal_id}for the original caller. - Checkpoint (optional) -- if the accumulated conversation history
exceeds the token threshold, compress it via :class:
CheckpointManager.
Parameters¶
actor_id : str
Unique identifier for this actor instance.
config_path : str
Path to the orchestrator YAML config file (e.g.
configs/orchestrators/default.yaml).
backend : LLMBackend
LLM backend used for both decomposition and synthesis. Typically
the same backend instance, but could be different tiers.
nats_url : str
NATS server URL.
checkpoint_store : CheckpointStore | None
Checkpoint persistence backend. Pass None to disable checkpointing.
Example:¶
::
from heddle.worker.backends import OllamaBackend
from heddle.contrib.redis.store import RedisCheckpointStore
backend = OllamaBackend(model="command-r7b:latest")
store = RedisCheckpointStore("redis://localhost:6379")
actor = OrchestratorActor(
actor_id="orchestrator-1",
config_path="configs/orchestrators/default.yaml",
backend=backend,
nats_url="nats://localhost:4222",
checkpoint_store=store,
)
await actor.run("heddle.goals.incoming")
Source code in src/heddle/orchestrator/runner.py
on_reload
async
¶
Re-read the orchestrator config from disk on reload signal.
Updates config-derived settings (timeouts, concurrency limits). Does not rebuild the decomposer or synthesizer — those are constructed from the backend, which doesn't change at runtime.
Source code in src/heddle/orchestrator/runner.py
handle_message
async
¶
Handle an incoming OrchestratorGoal.
This is the main entry point called by :meth:BaseActor._process_one
for every message received on heddle.goals.incoming.
The method orchestrates the full goal lifecycle: parse, decompose,
dispatch, collect, synthesize, publish. Errors at any stage result
in a FAILED TaskResult published to the goal's result subject.
Parameters¶
data : dict[str, Any]
Raw message dict, expected to conform to
:class:OrchestratorGoal schema.
Source code in src/heddle/orchestrator/runner.py
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 | |
Pipeline¶
pipeline ¶
Pipeline orchestrator for multi-stage processing with automatic parallelism.
Executes a defined sequence of stages, passing results from each stage as input to later stages. Each stage maps to a worker_type. Stages can be LLM workers, processor workers, or any other actor — the pipeline doesn't care about the implementation, only the message contract.
Stage dependencies are automatically inferred from input_mapping
paths: if stage B references "A.output.field", then B depends on A.
Stages with no inter-stage dependencies (only goal.* paths) are
independent and execute in parallel. Alternatively, explicit
depends_on lists in the YAML config override automatic inference.
Execution proceeds in levels — each level contains stages whose
dependencies are all satisfied by earlier levels. Stages within a level
run concurrently via asyncio.wait(FIRST_COMPLETED) for incremental
progress reporting.
Pipeline definition comes from YAML config with stages, input mappings, and optional conditions.
Data flow through the pipeline::
OrchestratorGoal arrives at handle_message()
↓
context = { "goal": { "instruction": ..., "context": { ... } } }
↓
Build execution levels from stage dependencies (Kahn's algorithm)
↓
For each level:
For each stage in level (concurrently if >1):
1. Evaluate condition (skip if false)
2. Build payload via input_mapping (dot-notation paths into context)
3. Publish TaskMessage to heddle.tasks.incoming
4. Wait for TaskResult on heddle.results.{goal_id}
5. Store result: context[stage_name] = { "output": ..., ... }
↓
Publish final TaskResult with all stage outputs
Input mapping example (from doc_pipeline.yaml)::
input_mapping:
text_preview: "extract.output.text_preview"
metadata: "extract.output.metadata"
This resolves to::
payload["text_preview"] = context["extract"]["output"]["text_preview"]
payload["metadata"] = context["extract"]["output"]["metadata"]
See Also
heddle.orchestrator.runner — dynamic LLM-based orchestrator heddle.core.messages.OrchestratorGoal — the input message type configs/orchestrators/ — pipeline config YAML files
PipelineStageError ¶
PipelineTimeoutError ¶
Bases: PipelineStageError
Raised when a pipeline stage times out waiting for a result.
Source code in src/heddle/orchestrator/pipeline.py
PipelineValidationError ¶
Bases: PipelineStageError
Raised when input or output schema validation fails for a stage.
Source code in src/heddle/orchestrator/pipeline.py
PipelineWorkerError ¶
Bases: PipelineStageError
Raised when a worker returns FAILED status for a stage.
Source code in src/heddle/orchestrator/pipeline.py
PipelineMappingError ¶
Bases: PipelineStageError
Raised when input_mapping resolution fails for a stage.
Source code in src/heddle/orchestrator/pipeline.py
PipelineOrchestrator ¶
PipelineOrchestrator(actor_id: str, config_path: str, nats_url: str = 'nats://nats:4222', *, bus: Any | None = None)
Bases: BaseActor
Pipeline orchestrator with automatic stage parallelism.
Processes an OrchestratorGoal by running it through a series of stages organized into execution levels based on their dependencies. Stages within the same level run concurrently; levels execute sequentially. Stage outputs are accumulated in a context dict and can be referenced by subsequent stages via input_mapping.
Source code in src/heddle/orchestrator/pipeline.py
on_reload
async
¶
Re-read the pipeline config from disk on reload signal.
handle_message
async
¶
Execute the pipeline for an incoming orchestrator goal.
Source code in src/heddle/orchestrator/pipeline.py
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 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | |
Decomposer¶
decomposer ¶
Task decomposition logic for orchestrators.
Responsible for breaking down complex goals into concrete subtasks that can be routed to individual workers.
This module is used by OrchestratorActor (runner.py), NOT by PipelineOrchestrator (which has its stages pre-defined in YAML).
The GoalDecomposer uses an LLM backend to analyze a high-level goal and produce a list of concrete TaskMessages, each targeting a specific worker_type. The LLM is given the goal instruction, domain context, and a manifest of available workers (names, descriptions, and input schemas) so it can make informed routing decisions and construct valid payloads.
The decomposition prompt asks the LLM to output structured JSON::
[
{"worker_type": "extractor", "payload": {...}, "model_tier": "local"},
{"worker_type": "summarizer", "payload": {...}, "model_tier": "local"},
...
]
Each entry maps directly to a TaskMessage. The parent_task_id is set to the caller-provided value so that worker results route back to the orchestrator via heddle.results.{goal_id}.
See Also
heddle.core.messages.TaskMessage — the output message type heddle.core.messages.OrchestratorGoal — the input message type heddle.worker.backends.LLMBackend — the LLM interface used for decomposition
WorkerDescriptor
dataclass
¶
WorkerDescriptor(name: str, description: str, input_schema: dict[str, Any] = dict(), default_tier: str = 'standard')
Metadata about an available worker type.
Used to ground the LLM's decomposition in what the system can actually
execute. Typically constructed from a worker's YAML config file via the
:meth:GoalDecomposer.from_worker_configs factory method.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The worker_type identifier (e.g. |
description |
str
|
One-line human-readable description of what the worker does. |
input_schema |
dict[str, Any]
|
JSON Schema dict for the worker's expected payload. Included in the LLM prompt so it can construct valid payloads. |
default_tier |
str
|
The default ModelTier string for this worker
( |
to_prompt_block ¶
Format this worker as a multi-line block for the LLM system prompt.
Includes the name, description, expected payload schema, and default model tier so the LLM knows exactly how to construct valid sub-tasks.
Source code in src/heddle/orchestrator/decomposer.py
GoalDecomposer ¶
GoalDecomposer(backend: LLMBackend, workers: list[WorkerDescriptor], *, max_tokens: int = 2000, temperature: float = 0.0)
LLM-based goal decomposition.
Turns a high-level goal string into a list of TaskMessage objects ready for dispatch through the router.
The decomposer asks an LLM to plan which workers to invoke and how to parameterize each one. It then parses the structured JSON response into validated TaskMessage objects.
All parsing and validation failures are handled gracefully -- invalid sub-tasks are logged and skipped rather than crashing the orchestrator. If the entire LLM response is unparseable, an empty list is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
LLMBackend
|
An LLM backend instance (OllamaBackend, AnthropicBackend, etc.) used to generate the decomposition plan. |
required |
workers
|
list[WorkerDescriptor]
|
List of WorkerDescriptor objects describing the available worker types. These are injected into the system prompt so the LLM knows what tools it can plan around. |
required |
max_tokens
|
int
|
Maximum tokens for the LLM response. Should be large enough to accommodate the full JSON plan. Defaults to 2000. |
2000
|
temperature
|
float
|
Sampling temperature. Low values (0.0--0.2) produce more deterministic plans. Defaults to 0.0 for reproducibility. |
0.0
|
Example::
workers = [
WorkerDescriptor(
name="summarizer",
description="Compresses text to structured summary",
input_schema={"type": "object", "required": ["text"], ...},
default_tier="local",
),
WorkerDescriptor(
name="extractor",
description="Extracts structured fields from text",
input_schema={"type": "object", "required": ["text", "fields"], ...},
default_tier="standard",
),
]
decomposer = GoalDecomposer(backend=ollama_backend, workers=workers)
tasks = await decomposer.decompose(
goal="Summarize this report and extract the key dates",
context={"text": "...report content..."},
)
# tasks is a list[TaskMessage] ready for dispatch
Source code in src/heddle/orchestrator/decomposer.py
decompose
async
¶
decompose(goal: str, context: dict[str, Any] | None = None, *, parent_task_id: str | None = None, priority: TaskPriority = TaskPriority.NORMAL) -> list[TaskMessage]
Decompose a high-level goal into a list of TaskMessage objects.
Sends the goal and context to the LLM along with descriptions of all available workers. The LLM returns a JSON plan which is parsed and validated into TaskMessage instances.
This method never raises on LLM or parsing failures -- it logs the error and returns an empty list. The orchestrator can then decide whether to retry with different parameters or report failure upstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
goal
|
str
|
Natural-language description of what needs to be accomplished. |
required |
context
|
dict[str, Any] | None
|
Optional domain-specific data dict (e.g. file references, category lists, full text content). Included verbatim in the LLM prompt so it can construct appropriate payloads. |
None
|
parent_task_id
|
str | None
|
If this decomposition is part of a larger goal,
all generated TaskMessages will carry this as their
|
None
|
priority
|
TaskPriority
|
Default priority for generated tasks. Individual tasks may override this if the LLM specifies a different priority. |
NORMAL
|
Returns:
| Type | Description |
|---|---|
list[TaskMessage]
|
A list of TaskMessage objects ready for dispatch to the router. |
list[TaskMessage]
|
Returns an empty list if: |
list[TaskMessage]
|
|
list[TaskMessage]
|
|
list[TaskMessage]
|
|
list[TaskMessage]
|
|
Source code in src/heddle/orchestrator/decomposer.py
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 | |
from_worker_configs
classmethod
¶
from_worker_configs(backend: LLMBackend, configs: list[dict[str, Any]], **kwargs: Any) -> GoalDecomposer
Build WorkerDescriptors from raw worker config dicts.
This avoids the caller having to manually construct WorkerDescriptor objects when the data is already available as parsed YAML configs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
LLMBackend
|
The LLM backend to use for decomposition. |
required |
configs
|
list[dict[str, Any]]
|
List of worker config dicts, each containing at minimum
|
required |
**kwargs
|
Any
|
Additional keyword arguments forwarded to the
GoalDecomposer constructor (e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
GoalDecomposer
|
A configured GoalDecomposer instance. |
Example::
import yaml
with open("configs/workers/summarizer.yaml") as f:
summarizer_cfg = yaml.safe_load(f)
with open("configs/workers/classifier.yaml") as f:
classifier_cfg = yaml.safe_load(f)
decomposer = GoalDecomposer.from_worker_configs(
backend=ollama_backend,
configs=[summarizer_cfg, classifier_cfg],
)
Source code in src/heddle/orchestrator/decomposer.py
Synthesizer¶
synthesizer ¶
Result aggregation for orchestrators.
Responsible for combining results from multiple workers into a coherent final output.
This module is used by OrchestratorActor (runner.py), NOT by PipelineOrchestrator (which simply collects stage outputs into a dict).
Two modes of operation:
1. **Simple merge** (no LLM backend required)
Partitions results into succeeded/failed, aggregates outputs into a
structured dict with metadata. Fast, deterministic, zero cost.
2. **LLM synthesis** (requires an LLM backend + a goal string)
Sends the collected worker outputs to an LLM with instructions to
produce a coherent narrative synthesis. Use this when the orchestrator
needs to present a unified answer to the user rather than a bag of
sub-results.
Design decisions
- Partial failures are first-class: every output dict contains both
succeededandfailedsections so callers never lose visibility into what went wrong. - The LLM synthesis prompt is kept internal to this module; callers only pass the goal string and the list of TaskResults.
- Token-budget awareness: if the combined result text is very large, the synthesizer truncates individual outputs before sending them to the LLM to avoid blowing the context window.
ResultSynthesizer ¶
Combines multiple worker :class:TaskResult objects into a final output.
The synthesizer operates in one of two modes depending on how it is constructed and invoked:
Simple merge (default, no LLM):
Call :meth:merge or call :meth:synthesize without a goal.
Returns a structured dict with succeeded and failed sections
plus aggregate metadata.
LLM synthesis (requires backend and a goal):
Call :meth:synthesize with a goal string. The LLM receives the
original goal, all worker outputs, and instructions to produce a
unified answer.
Parameters¶
backend : LLMBackend | None
An optional LLM backend (e.g. :class:OllamaBackend,
:class:AnthropicBackend). When provided and a goal is passed
to :meth:synthesize, the synthesizer will use the LLM to produce a
coherent narrative. When None, only deterministic merge is
available.
max_output_chars : int
Per-result character budget when building the LLM prompt. Outputs
longer than this are truncated to avoid exceeding the model's context
window. Defaults to :data:_MAX_OUTPUT_CHARS.
Example:¶
::
# Simple merge (no LLM)
synth = ResultSynthesizer()
merged = synth.merge(results)
# LLM synthesis
synth = ResultSynthesizer(backend=my_ollama_backend)
combined = await synth.synthesize(results, goal="Summarise the document")
Source code in src/heddle/orchestrator/synthesizer.py
merge ¶
Deterministic merge of task results — no LLM involved.
Partitions results into succeeded and failed groups, extracts their outputs (or errors), and returns a structured dict with aggregate metadata.
Parameters¶
results : list[TaskResult] Worker results to merge. May be empty.
Returns:¶
dict[str, Any] A dict with the following top-level keys:
- ``succeeded`` — list of dicts, each containing ``task_id``,
``worker_type``, ``output``, ``model_used``, and
``processing_time_ms`` for every completed result.
- ``failed`` — list of dicts, each containing ``task_id``,
``worker_type``, ``error``, and ``processing_time_ms`` for every
failed result.
- ``in_flight`` — list of dicts, each containing ``task_id``,
``worker_type``, ``status``, and ``processing_time_ms`` for any
task still in a non-terminal state. Empty under the current
dynamic-orchestrator caller (cc49783 converts pending tasks
to synthetic ``FAILED`` placeholders before synthesis).
- ``metadata`` — aggregate statistics: ``total``, ``succeeded``,
``failed``, ``in_flight``, ``total_processing_time_ms``,
``models_used``, and ``total_tokens``.
Source code in src/heddle/orchestrator/synthesizer.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
synthesize
async
¶
Combine worker results into a final coherent output.
If an LLM backend was provided at construction time and a goal
string is supplied, the method delegates to :meth:_llm_synthesize
which asks the LLM to produce a unified narrative. Otherwise it falls
back to :meth:merge.
Parameters¶
results : list[TaskResult] Worker results to synthesize. May be empty (in which case the output will indicate that no results were available). goal : str | None The original high-level goal that spawned these tasks. Required for LLM synthesis mode; ignored in merge mode.
Returns:¶
dict[str, Any]
In merge mode the return value is identical to :meth:merge.
In **LLM mode** the dict contains:
- ``synthesis`` — the LLM's coherent combined answer (str).
- ``confidence`` — ``"high"``, ``"medium"``, or ``"low"`` (str).
- ``conflicts`` — list of contradictions the LLM identified.
- ``gaps`` — list of missing information from failed tasks.
- ``succeeded`` / ``failed`` / ``metadata`` — same as merge mode.
- ``llm_metadata`` — model used and token counts for the synthesis
call itself.
Source code in src/heddle/orchestrator/synthesizer.py
Checkpoint¶
checkpoint ¶
Self-summarization checkpoint system for orchestrators.
The orchestrator's context is precious. This module compresses conversation history into structured state snapshots at defined intervals, allowing the orchestrator to "reboot" with a clean, compact understanding of where things stand.
Checkpoint trigger: when estimated token count exceeds threshold.
Storage: Pluggable via CheckpointStore (see orchestrator/store.py). Keys follow the pattern::
heddle:checkpoint:{goal_id}:{checkpoint_number} — versioned checkpoint
heddle:checkpoint:{goal_id}:latest — pointer to most recent
The orchestrator workflow with checkpoints::
1. Process goal, accumulate conversation_history
2. After each worker result: should_checkpoint(conversation_history)
3. If True: create_checkpoint() → compress state → persist to store
4. Orchestrator "reboots" with: system_prompt + format_for_injection(checkpoint)
+ last N interactions (recent_window_size)
This is conceptually similar to how Claude Code itself handles context compression — the key insight is the same: keep a structured summary + recent window rather than the full history.
This module is used by OrchestratorActor (runner.py).
PipelineOrchestrator does NOT use checkpoints because its sequential stage execution doesn't accumulate unbounded context.
Note: Token counting uses tiktoken with cl100k_base encoding (OpenAI's tokenizer). For Anthropic models, token counts are approximate (~10-15% estimation error). This is acceptable for checkpoint threshold decisions where exact counts are not critical.
CheckpointManager ¶
CheckpointManager(store: KeyValueStore, token_threshold: int = 50000, recent_window_size: int = 5, encoding_name: str = 'cl100k_base', ttl_seconds: int = 86400)
Manages orchestrator state compression.
Workflow:
- After each worker result, estimate_tokens() checks context size
- If threshold exceeded, create_checkpoint() asks a summarizer to compress the current state
- The orchestrator restarts with: system_prompt + checkpoint + recent_window
Source code in src/heddle/orchestrator/checkpoint.py
estimate_tokens ¶
should_checkpoint ¶
Check if context has grown enough to trigger compression.
Source code in src/heddle/orchestrator/checkpoint.py
create_checkpoint
async
¶
create_checkpoint(goal_id: str, original_instruction: str, completed_tasks: list[dict[str, Any]], pending_tasks: list[dict[str, Any]], open_issues: list[str], decisions_made: list[str], checkpoint_number: int) -> CheckpointState
Build a checkpoint.
The orchestrator or a dedicated summarizer compresses current state into this structure.
Source code in src/heddle/orchestrator/checkpoint.py
load_latest
async
¶
Load the most recent checkpoint for a goal.
Source code in src/heddle/orchestrator/checkpoint.py
format_for_injection ¶
Format checkpoint as context to inject into a fresh orchestrator session.
This is what the orchestrator sees when it "wakes up" after a checkpoint.
Source code in src/heddle/orchestrator/checkpoint.py
Store¶
store ¶
Backward-compatibility shim.
This module originally defined CheckpointStore and
InMemoryCheckpointStore. The store abstraction is now general-purpose
and lives in :mod:heddle.core.kvstore. The old names continue to work as
aliases for the new ones.
Migration: new code should import from heddle.core.kvstore directly.
Existing imports from this module are kept working through the v0.x series
and will be removed in v1.0.
InMemoryCheckpointStore ¶
Bases: KeyValueStore
In-memory key-value store for tests and local development.
Values are stored in a dict with optional expiry timestamps.
Expiry is checked lazily on get() — no background cleanup.
Source code in src/heddle/core/kvstore.py
set
async
¶
Store a value with optional TTL.
get
async
¶
Retrieve a value, or None if missing/expired.
Source code in src/heddle/core/kvstore.py
set_if_not_exists
async
¶
Atomic set-if-absent. Lazily expires the existing entry first.
Single-event-loop atomicity is sufficient for the test/dev use
cases this store targets; multi-process coordination requires
:class:RedisKeyValueStore.
Source code in src/heddle/core/kvstore.py
CheckpointStore ¶
Bases: ABC
Abstract TTL-aware key-value store.
Implementations must handle:
- String key-value storage.
- TTL-based expiration (best-effort; lazy expiry is acceptable).
- Returning
Nonefor missing or expired keys.
set
abstractmethod
async
¶
get
abstractmethod
async
¶
set_if_not_exists
abstractmethod
async
¶
Atomically set key to value with TTL only if absent.
Returns True if the value was stored (caller "won the
race"), False if the key already existed (caller lost).
TTL is mandatory — the SETNX-without-TTL footgun (orphaned
leases on crash) is explicitly disallowed.
Used by :func:heddle.contrib.events.lease.finalization_lease
and any other coordination primitive that needs a single-writer
guarantee with bounded recovery.
Source code in src/heddle/core/kvstore.py
aclose
async
¶
Release any I/O resources held by this store.
Subclasses that hold open client connections override this to close them. Idempotent — safe to call more than once. Default is a no-op.
Source code in src/heddle/core/kvstore.py
scope ¶
Return a view that transparently prepends prefix to all keys.
The view implements the same KeyValueStore interface, so it nests
cleanly — a scoped view of a scoped view concatenates the prefixes.
aclose() on a scoped view is a no-op; the underlying store owns
the connection.
Source code in src/heddle/core/kvstore.py
Result Stream¶
stream ¶
Streaming result collection for orchestrators.
Provides ResultStream, an async iterator that yields TaskResult
objects as they arrive from the message bus — rather than blocking until
all results are collected.
Lifecycle (publish-before-subscribe race avoidance)::
stream = ResultStream(bus, subject, expected_ids, timeout)
async with stream: # subscribes
await dispatch_subtasks(...) # safe to publish now
results = await stream.collect_all()
Subscribing BEFORE the caller publishes any task whose result we expect
is mandatory — NATS is at-most-once. If a fast worker publishes its
result onto heddle.results.{goal_id} before we have an active
subscription, that result is lost and the goal will time out. The
async with block makes the ordering explicit at every call site.
Two consumption modes:
1. **Batch** (backward compatible with pre-Strategy-A code)::
async with ResultStream(bus, subject, expected_ids, timeout) as stream:
await dispatch(...)
results = await stream.collect_all()
2. **Incremental** — enables progress callbacks and early exit::
async with ResultStream(bus, subject, ids, timeout,
on_result=my_progress_callback) as stream:
await dispatch(...)
async for result in stream:
# process each result as it arrives
...
The on_result callback is invoked for every arriving result with the
signature (result, collected_count, expected_count) -> bool | None.
Returning True signals early exit — the stream stops collecting and
the caller gets whatever has arrived so far.
This module is used by:
OrchestratorActor._collect_results()— dynamic orchestrator- Potentially by
MCPBridgefor richer progress reporting (future)
Design decisions:
- Subscribe-before-publish enforced: callers must use
async with(or explicitstart()). Iterating without entering the context raises a :class:RuntimeErrorrather than silently lazy-subscribing — the lazy form was the original race and is now treated as a bug. - Single-use: a
ResultStreamcan only be iterated once (it owns the bus subscription lifecycle). - Callback errors are non-fatal: if
on_resultraises, the error is logged and collection continues. - Duplicate filtering: results for the same
task_idare silently skipped (at-least-once delivery tolerance). - Unknown task_ids are ignored: only results matching
expected_task_idsare collected.
ResultCallback ¶
Bases: Protocol
Callback invoked when a result arrives during streaming collection.
Parameters¶
result : TaskResult The just-arrived result. collected : int How many results have been collected so far (including this one). expected : int Total number of expected results.
Returns:¶
bool | None
Return True to signal early exit (stop collecting).
Return None or False to continue.
ResultStream ¶
ResultStream(bus: MessageBus, subject: str, expected_task_ids: set[str], timeout: float, *, on_result: ResultCallback | None = None)
Async iterator that yields TaskResult objects as they arrive.
Wraps a bus subscription for a specific result subject, filtering
incoming messages to only those matching expected_task_ids.
The stream terminates when:
- All expected results have arrived, OR
- The timeout expires, OR
- The
on_resultcallback returnsTrue(early exit), OR - The subscription is closed.
After iteration, inspect :attr:collected, :attr:timed_out, and
:attr:early_exited for post-mortem state.
Parameters¶
bus : MessageBus
The message bus to subscribe on.
subject : str
NATS subject to subscribe to (e.g. heddle.results.{goal_id}).
expected_task_ids : set[str]
Set of task_ids we expect results for.
timeout : float
Maximum seconds to wait for all results.
on_result : ResultCallback | None
Optional callback invoked as each result arrives.
Example:¶
::
stream = ResultStream(
bus=nats_bus,
subject=f"heddle.results.{goal_id}",
expected_task_ids={"task-1", "task-2", "task-3"},
timeout=60.0,
on_result=my_progress_handler,
)
# Batch mode (drop-in replacement for old collect):
results = await stream.collect_all()
# Or streaming mode:
async for result in stream:
print(f"Got {result.worker_type}: {result.status}")
Source code in src/heddle/orchestrator/stream.py
collected
property
¶
Map of task_id → TaskResult for all collected results.
early_exited
property
¶
True if collection ended due to on_result callback signaling stop.
start
async
¶
Subscribe to the bus subject.
MUST be called before the caller publishes any task whose result
is expected on this subject — NATS is at-most-once. Prefer
async with stream: (which calls start on __aenter__)
to make the ordering explicit at the call site.
Idempotent — calling twice is an error. Returns self to
allow stream = await ResultStream(...).start() if the caller
prefers that style.
Source code in src/heddle/orchestrator/stream.py
aclose
async
¶
Release the subscription. Idempotent.
Safe to call from a finally block; the second call is a
no-op.
Source code in src/heddle/orchestrator/stream.py
__aenter__
async
¶
__aexit__
async
¶
__aexit__(exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None
Release the subscription regardless of how the block exits.
collect_all
async
¶
Consume the stream fully, returning all collected results as a list.
Must be called from inside an async with block (or after an
explicit start()).
Source code in src/heddle/orchestrator/stream.py
__aiter__ ¶
Return the async iterator (self — delegates to _stream).