-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiled.py
More file actions
2339 lines (2158 loc) · 107 KB
/
Copy pathcompiled.py
File metadata and controls
2339 lines (2158 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
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
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Compiled graph + execute loop.
Execution begins at the entry node; each step runs a node, merges
its partial update via per-field reducers, then evaluates the
outgoing edge against the post-update state to choose the next node
(or END to halt).
Node, edge, reducer, and routing errors carry recoverable state;
state validation errors do not.
Each node attempt produces a started/completed event PAIR. The
engine dispatches the started event before invoking the wrapped node
function and the completed event after the reducer merge succeeds
(with ``post_state`` populated) or after the node, reducer, or state
validation fails (with ``error`` populated). Routing errors do NOT
produce their own event pair; they land on the preceding node's
``completed`` event with ``error`` populated.
``CompiledGraph[StateT]`` and ``_merge_partial[StateT]`` carry the
concrete state subclass through to ``invoke()``'s return type, so
consumers don't need ``cast(MyState, ...)`` at the call site.
"""
from __future__ import annotations
import asyncio
import time
import uuid
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from dataclasses import replace as dataclass_replace
from typing import TYPE_CHECKING, Any, Literal, cast
if TYPE_CHECKING:
# ``FanOutNode`` lives in ``.fan_out`` which has a TYPE_CHECKING
# back-reference to ``CompiledGraph`` here. Importing at module
# top would create a textual cycle CodeQL's
# ``py/cyclic-import`` rule flags (no runtime issue —
# ``fan_out``'s ``compiled`` import is itself TYPE_CHECKING-gated
# — but the static analyzer doesn't see that). Type annotations
# use the string form via ``from __future__ import annotations``;
# runtime use (the ``isinstance`` check in ``_invoke``) imports
# lazily inside the function.
from .fan_out import FanOutNode
from pydantic import ValidationError
from openarmature.checkpoint.errors import (
CheckpointError,
CheckpointNotFound,
CheckpointRecordInvalid,
CheckpointSaveFailed,
CheckpointStateMigrationFailed,
CheckpointStateMigrationMissing,
)
from openarmature.checkpoint.migration import MigrationRegistry, StateMigration
from openarmature.checkpoint.protocol import (
Checkpointer,
CheckpointRecord,
FanOutInstanceProgress,
FanOutProgress,
NodePosition,
)
from openarmature.observability.correlation import (
_reset_active_dispatch,
_reset_active_observers,
_reset_correlation_id,
_reset_fan_out_index,
_reset_invocation_id,
_reset_namespace_prefix,
_set_active_dispatch,
_set_active_observer_span,
_set_active_observers,
_set_correlation_id,
_set_fan_out_index,
_set_invocation_id,
_set_namespace_prefix,
current_active_observer_span,
current_attempt_index,
validate_invocation_id,
)
from openarmature.observability.metadata import (
_reset_invocation_metadata,
_set_invocation_metadata,
current_invocation_metadata,
validate_invocation_metadata,
)
from .edges import END, ConditionalEdge, EndSentinel, StaticEdge
from .errors import (
EdgeException,
NodeException,
ReducerError,
RoutingError,
RuntimeGraphError,
StateValidationError,
)
from .events import (
FanOutEventConfig,
InvocationCompletedEvent,
InvocationStartedEvent,
NodeEvent,
)
from .middleware import ChainCall, Middleware, compose_chain
from .nodes import Node
from .observer import (
_DRAIN_SENTINEL,
DrainSummary,
Observer,
RemoveHandle,
SubscribedObserver,
_coerce_subscribed,
_dispatch,
_FanOutExecutionState,
_FanOutInstanceState,
_InvocationContext,
_QueuedItem,
deliver_loop,
)
from .reducers import Reducer
from .state import State
from .subgraph import SubgraphNode
# Try-import OpenTelemetry attach primitives so the engine can splice an
# observer-published span into the OTel context for the duration of a
# node body. The engine treats the span value opaquely (writes by an
# observer's ``prepare_sync``, reads via ``current_active_observer_span``)
# and only touches OTel when both: (a) the extras are installed, and
# (b) an observer actually published a span. Installs without ``[otel]``
# get a no-op attach/detach pair; the observer ContextVar stays
# ``None`` and nothing changes.
#
# The names are bound to ``None`` in the except branch so pyright
# narrows correctly at call sites (``if _otel_attach is None: ...``)
# rather than flagging "possibly unbound."
try:
from opentelemetry.context import attach as _otel_attach
from opentelemetry.context import detach as _otel_detach
from opentelemetry.trace.propagation import set_span_in_context as _otel_set_span_in_context
except ImportError: # pragma: no cover — exercised only in non-otel installs
_otel_attach = None # type: ignore[assignment]
_otel_detach = None # type: ignore[assignment]
_otel_set_span_in_context = None # type: ignore[assignment]
def _attach_active_observer_span() -> object | None:
"""Read ``current_active_observer_span``; if an observer published
one and OTel is installed, attach the span into the OTel context
so that any logs emitted from the next user-code scope (a node
body) pick up the right ``trace_id``/``span_id`` via OTel's
``LoggingHandler``.
Returns the OTel context token to hand back to
:func:`_detach_active_observer_span` in ``finally``, or ``None``
if no attach happened (no observer, no OTel, or both).
"""
if _otel_attach is None or _otel_set_span_in_context is None:
return None
span = current_active_observer_span()
if span is None:
return None
return _otel_attach(_otel_set_span_in_context(cast("Any", span)))
def _detach_active_observer_span(token: object | None) -> None:
"""Pair to :func:`_attach_active_observer_span`. No-op when no
attach was performed (token is ``None``)."""
if token is None or _otel_detach is None:
return
_otel_detach(cast("Any", token))
def _merge_partial[StateT: State](
prior: StateT,
partial: Mapping[str, Any],
reducers: Mapping[str, Reducer],
producing_node: str,
) -> StateT:
"""Apply per-field reducers to merge a node's partial update into prior state.
Re-validates the resulting state against the schema (validation
happens at node boundaries). Wraps reducer failures as
``ReducerError`` and schema failures as ``StateValidationError``.
"""
# Lazy import to avoid a textual cycle (parallel_branches has a
# TYPE_CHECKING back-reference to this module). _MultiContribution
# is the sentinel ParallelBranchesNode uses when multiple branches
# write the same parent field — each value flows through the
# parent's reducer in branch insertion order per spec §11.4 +
# §11.8.
from .parallel_branches import _MultiContribution # noqa: PLC0415
new_values = prior.model_dump()
for field_name, partial_value in partial.items():
reducer = reducers.get(field_name)
if reducer is None:
# Unknown field — surface as a schema validation failure below.
new_values[field_name] = partial_value
continue
try:
if isinstance(partial_value, _MultiContribution):
# Per pipeline-utilities §11.4: multi-branch
# contributions to one parent field apply in branch
# insertion order via the parent's reducer. Fold
# each value in sequence.
acc = new_values[field_name]
for v in partial_value.values:
acc = reducer(acc, v)
new_values[field_name] = acc
else:
new_values[field_name] = reducer(new_values[field_name], partial_value)
except Exception as e:
raise ReducerError(
field_name=field_name,
reducer_name=reducer.name,
producing_node=producing_node,
cause=e,
recoverable_state=prior,
) from e
try:
# type(prior) narrows to `type[StateT]`; model_validate returns StateT.
return type(prior).model_validate(new_values)
except ValidationError as e:
offending = sorted({str(err["loc"][0]) for err in e.errors() if err["loc"]})
raise StateValidationError(
f"state validation failed after node {producing_node!r}: {e}",
fields=offending,
cause=e,
) from e
@dataclass(frozen=True)
class _StepResult[StateT: State]:
"""Return shape of the per-step dispatchers
(``_step_function_node`` / ``_step_subgraph_node`` /
``_step_fan_out_node``) under the proposal-0012 v0.9.0 swap.
Spec graph-engine §3 step 3 (revised) requires the
``completed`` event for the just-completed node to fire AFTER
edge evaluation completes — so that edge-resolution failures
(``routing_error``, ``edge_exception``) land on the preceding
node's completed event with ``error`` populated, sharing the
started/completed pair rather than producing a separate event
pair (§6 revised).
The step dispatchers can't call ``_dispatch_completed`` for
the success path themselves anymore, because the outcome
isn't knowable until edge eval (which lives in ``_invoke``)
runs. Failure-path dispatches (``node_exception`` /
``reducer_error`` / ``state_validation_error``) still fire
inline inside ``innermost`` — those errors short-circuit
before edge eval can run, and the step function raises out.
For the success path, the step dispatcher returns the
finalized state plus a closure ``finalize_completed`` that
``_invoke`` calls AFTER edge eval, passing either ``None``
(edge eval succeeded → dispatch completed with
``post_state``) or the edge error (dispatch completed with
``error`` populated).
For ``_step_subgraph_node``, the wrapper is transparent per
fixture 013 (no started/completed pair); ``finalize_completed``
is a no-op closure so edge errors after a subgraph wrapper
propagate silently per proposal 0012's "preceding unit's
pair" framing applied to a unit that never had one. Same for
middleware that short-circuits without invoking ``next``.
"""
state: StateT
finalize_completed: Callable[[RuntimeGraphError | None], None]
def _no_op_finalize(_edge_error: RuntimeGraphError | None) -> None:
"""Default ``finalize_completed`` for cases where the step
didn't dispatch a started/completed pair — subgraph wrappers
(transparent per fixture 013) and middleware that short-
circuits without invoking ``next``. Edge errors propagate
silently per proposal 0012 + fixture 013."""
# Helpers for the proposal 0009 per-instance fan-out resume contract.
# The shared mutable ``fan_out_progress_state`` dict on
# _InvocationContext is keyed by ``(namespace, fan_out_node_name)``;
# these helpers locate / project / mutate it consistently.
def _find_innermost_fan_out_instance_state(
context: _InvocationContext,
) -> _FanOutInstanceState | None:
"""Locate the per-instance state for the innermost active fan-out
relative to ``context``.
A node running inside fan-out instance ``i`` of fan-out ``F``
sees ``context.namespace_prefix`` ending with ``F``'s own name
and ``context.fan_out_index == i``. Walk the namespace prefix
back to find the longest matching key in ``fan_out_progress_state``
so nested fan-outs route to the right level.
Returns ``None`` when no match is found — defensive against an
inner node firing outside any registered fan-out (shouldn't
happen if ``FanOutNode.run_with_context`` correctly registers
each fan-out before descending). Callers that expect a hit
surface the missing-state case as a no-op rather than a crash.
"""
if context.fan_out_index is None:
return None
prefix = context.namespace_prefix
state_dict = context.fan_out_progress_state
# Walk the prefix from longest to shortest. The innermost
# fan-out's full key is (namespace_before_fan_out, fan_out_name)
# where namespace_before_fan_out + (fan_out_name,) == prefix.
for split in range(len(prefix), 0, -1):
key = (prefix[: split - 1], prefix[split - 1])
if key in state_dict:
exec_state = state_dict[key]
idx = context.fan_out_index
if 0 <= idx < len(exec_state.instances):
return exec_state.instances[idx]
return None
def _project_fan_out_progress(
state_dict: Mapping[tuple[tuple[str, ...], str], _FanOutExecutionState],
) -> tuple[FanOutProgress, ...]:
"""Project the engine-internal mutable per-fan-out state into the
frozen :class:`FanOutProgress` shape on a saved record.
Per §10.11's snapshot semantics, a save fires with ALL concurrent
fan-out instances' states captured at the moment of the save —
not just the one whose ``completed`` event triggered the save.
This projection enumerates the whole dict; the engine save site
calls it once per save regardless of which fan-out's inner node
fired the event.
Deterministic ordering: sort by (namespace, fan_out_node_name).
Two saves carrying the same logical state then serialize
byte-identically, which matters for backends that hash records.
"""
out: list[FanOutProgress] = []
for (namespace, name), exec_state in sorted(state_dict.items()):
instances = tuple(
FanOutInstanceProgress(
state=inst.state,
result=inst.result,
result_is_error=inst.result_is_error,
completed_inner_positions=tuple(inst.completed_inner_positions),
)
for inst in exec_state.instances
)
out.append(
FanOutProgress(
fan_out_node_name=name,
namespace=namespace,
instance_count=exec_state.instance_count,
instances=instances,
)
)
return tuple(out)
def _restore_fan_out_progress_state(
saved: Sequence[FanOutProgress],
) -> dict[tuple[tuple[str, ...], str], _FanOutExecutionState]:
"""Inverse projection of :func:`_project_fan_out_progress`. On resume
the loaded record's frozen ``fan_out_progress`` tuple gets unpacked
into the mutable per-fan-out tracking dict that ``FanOutNode``
consults to decide which instances to skip vs re-run.
Extra-output state isn't preserved across resume — the spec models
``result`` as a single accumulator entry and is silent on
``extra_outputs``. Reconstructing them would require either
serializing them on the record (a spec change) or recomputing them
(defeating the point of skip-on-resume). Fixtures don't exercise
``extra_outputs`` on the resume path; if a future workload needs
them, surface as a follow-on.
``result_is_error`` is read verbatim from the saved record's
explicit field per spec §10.11 (proposal 0027). The pre-0027
structural-pattern heuristic is gone — the spec mandates the
explicit field as the authoritative discriminator because the
user's state schema can legitimately contain values that match
the engine's canonical error-record shape, and a heuristic would
misclassify them.
"""
out: dict[tuple[tuple[str, ...], str], _FanOutExecutionState] = {}
for fp in saved:
instances: list[_FanOutInstanceState] = []
for inst in fp.instances:
instances.append(
_FanOutInstanceState(
state=inst.state,
result=inst.result,
result_is_error=inst.result_is_error,
extra_outputs={},
completed_inner_positions=list(inst.completed_inner_positions),
)
)
key = (fp.namespace, fp.fan_out_node_name)
out[key] = _FanOutExecutionState(
fan_out_node_name=fp.fan_out_node_name,
namespace=fp.namespace,
instance_count=fp.instance_count,
instances=instances,
)
return out
async def _save_fan_out_internal(
checkpointer: Any,
invocation_id: str,
record: CheckpointRecord,
) -> None:
"""Route a fan-out-internal save through the checkpointer's
optional batching seam.
Per spec §10.11.4, Checkpointer backends MAY support batching
scoped to fan-out internal saves. When the backend exposes a
``save_fan_out_internal`` coroutine, route there so it can buffer
or flush per its configuration. Otherwise, fall back to the
standard ``save`` — non-batching backends see no behavioral change.
"""
saver = getattr(checkpointer, "save_fan_out_internal", None)
if saver is None:
await checkpointer.save(invocation_id, record)
return
await saver(invocation_id, record)
async def _save_fan_out_in_flight_failure( # pyright: ignore[reportUnusedFunction]
checkpointer: Any,
invocation_id: str,
record: CheckpointRecord,
) -> None:
"""Route an "instance failed mid-execution" save through the
checkpointer's failure-save seam (§10.11.4 + the in_flight
observability gap §10.11).
Backends that expose ``save_fan_out_in_flight_failure`` get the
save directly; under batching, the typical implementation
buffers without triggering the flush count (preserving the
"buffered saves lost on crash" model). Backends that don't
expose the hook fall back to ``save`` so non-batching backends
keep the failure save durable.
"""
saver = getattr(checkpointer, "save_fan_out_in_flight_failure", None)
if saver is None:
await checkpointer.save(invocation_id, record)
return
await saver(invocation_id, record)
@dataclass(frozen=True)
class _MigrationSummary:
"""Per-resume migration-chain metadata threaded out of
``_migrate_record`` so the engine can dispatch an
``openarmature.checkpoint.migrate`` observer event after the
invocation context is built (per spec §6 cross-ref in proposal
0014). Carried on the synthetic ``NodeEvent.pre_state``
payload for ``phase="checkpoint_migrated"``; the OTel observer
reads it to emit the span.
"""
from_version: str
to_version: str
chain_length: int
def _apply_migration_step(
migration: StateMigration,
value: Any,
label: str,
) -> Any:
"""Apply one migration step to one value (outer state or one
parent-state entry). Wraps the user-supplied migration function's
raise as ``CheckpointStateMigrationFailed`` per spec §10.12.2.
The original exception rides ``__cause__``.
"""
try:
return migration.migrate(value)
except CheckpointError:
# Preserve canonical category — if a migration raises a
# CheckpointError subclass itself (rare; migrations are
# spec-mandated pure per §10.12.2), propagate the original
# category rather than wrapping it as
# CheckpointStateMigrationFailed.
raise
except Exception as exc:
# Concise wrap-message intentionally. ``raise ... from exc``
# preserves the original exception on ``__cause__``;
# Python's traceback formatter surfaces it, so embedding the
# underlying ``type/str`` in this message would just
# duplicate information (and confuse the output when the
# underlying ``__str__`` is multi-line).
raise CheckpointStateMigrationFailed(
f"migration {migration.from_version!r}→{migration.to_version!r} raised while migrating {label}",
from_version=migration.from_version,
to_version=migration.to_version,
) from exc
@dataclass(frozen=True)
class CompiledGraph[StateT: State]:
"""An immutable, executable graph produced by `GraphBuilder.compile()`.
The compile-time topology (state class, entry, nodes, edges, reducers) is
immutable. Two mutable lists ride alongside for observer plumbing
(`_attached_observers` and `_active_workers`), neither of which affect the
compiled topology and both of which are scoped to the same instance.
"""
state_cls: type[StateT]
entry: str
nodes: Mapping[str, Node[StateT]]
edges: Mapping[str, StaticEdge | ConditionalEdge[StateT]]
reducers: Mapping[str, Reducer]
# Per-graph middleware in registration order (outer-to-inner). Composes
# OUTSIDE per-node middleware at runtime per pipeline-utilities §3.
middleware: tuple[Middleware, ...] = ()
# Observer plumbing — see attach_observer/drain. Mutable on a frozen
# dataclass: the list reference is fixed but its contents change.
# Parameterized factories so pyright infers the element types.
_attached_observers: list[SubscribedObserver] = field(default_factory=list[SubscribedObserver])
# Per-task `add_done_callback` auto-removes completed workers — long-
# running services that never call drain() don't accumulate completed
# Task references indefinitely. Values are the per-invocation
# `_InvocationContext` so `drain()` can read each worker's
# `drain_counters` to compute the undelivered-event count at timeout.
_active_workers: dict[asyncio.Task[None], _InvocationContext] = field(
default_factory=dict[asyncio.Task[None], _InvocationContext]
)
# Single-element list so the frozen-dataclass binding is stable but
# the user can swap the registered Checkpointer via
# ``attach_checkpointer``. ``None`` when no backend is registered.
_checkpointer_slot: list[Checkpointer | None] = field(default_factory=lambda: [None])
# State-migration registry (pipeline-utilities §10.12 / proposal
# 0014). Populated by ``GraphBuilder.with_state_migration(s)``;
# consulted on resume when the loaded record's ``schema_version``
# does not match the current state class's ``schema_version``.
migration_registry: MigrationRegistry = field(default_factory=MigrationRegistry)
# ------------------------------------------------------------------
# Observer registration (spec v0.6.0 §6)
# ------------------------------------------------------------------
def attach_observer(
self,
observer: Observer,
*,
phases: Iterable[str] | None = None,
) -> RemoveHandle:
"""Register a graph-attached observer.
Graph-attached observers fire on every invocation of this
graph until removed; including when this graph runs as a
subgraph inside a parent. Returns a ``RemoveHandle`` whose
``.remove()`` method detaches the observer; idempotent.
``phases`` selects the phase strings (``"started"``,
``"completed"``) the observer subscribes to; default is both.
An empty ``phases`` set raises ``ValueError`` at registration
time.
Changes to the registered set during a graph run do NOT take
effect until the next invocation. The set of observers
delivering events for an in-flight invocation is fixed at
the point the invocation begins.
"""
subscribed = _coerce_subscribed(observer, phases=phases)
self._attached_observers.append(subscribed)
return RemoveHandle(_observers=self._attached_observers, _observer=subscribed)
# ------------------------------------------------------------------
# Checkpointer registration
# ------------------------------------------------------------------
def attach_checkpointer(self, checkpointer: Checkpointer | None) -> None:
"""Register a Checkpointer for this graph.
Pass ``None`` to clear a previously-registered backend.
Without a registered Checkpointer the engine never calls
``save()`` and ``invoke(resume_invocation=...)`` raises
``checkpoint_not_found``.
At most one Checkpointer per graph. Calling
``attach_checkpointer`` again replaces the previously-
registered one; multi-backend fan-out is the user's
responsibility (wrap two underlying Checkpointers behind a
custom protocol-conforming implementation if needed).
"""
self._checkpointer_slot[0] = checkpointer
@property
def checkpointer(self) -> Checkpointer | None:
"""Currently-registered Checkpointer, or ``None``."""
return self._checkpointer_slot[0]
# ------------------------------------------------------------------
# State migration (pipeline-utilities §10.12 / proposal 0014)
# ------------------------------------------------------------------
async def _migrate_record(
self,
record: CheckpointRecord,
checkpointer: Checkpointer,
invocation_id: str,
current_schema_version: str,
) -> tuple[CheckpointRecord, _MigrationSummary]:
"""Resolve a migration chain for ``record`` and apply it.
Returns ``(migrated_record, summary)``. ``migrated_record``
has ``state`` + ``parent_states`` mapped through the chain.
``summary`` carries the chain's metadata so the caller can
dispatch a ``checkpoint_migrated`` observer event after the
invocation context exists (per the spec §6 cross-ref in
proposal 0014).
Caller is responsible for the post-migration deserialization
step (§10.12.4): if the migrated state cannot deserialize
against the current state class, the resulting failure
surfaces as ``CheckpointRecordInvalid``.
Spec §10.12.2 says "parent states MUST be treated as carrying
the same ``schema_version`` as the outer record." We apply
the same chain to every entry in ``parent_states`` lockstep
with the outer state. Future per-parent versioning would
need a spec follow-on.
"""
# Eligibility check first per §10.12.1: backends that hold
# typed in-memory state or class-bound serialization cannot
# expose the class-independent intermediate the registry
# consumes. Mismatch + no eligibility → CheckpointRecordInvalid.
if not getattr(checkpointer, "supports_state_migration", False):
raise CheckpointRecordInvalid(
invocation_id,
f"persisted schema_version={record.schema_version!r} does not "
f"match current {current_schema_version!r}, and the active "
f"checkpointer ({type(checkpointer).__name__}) does not "
f"support state migration",
)
# resolve_chain raises CheckpointStateMigrationChainAmbiguous
# directly on multi-shortest-path detection per spec §10.10
# / §10.12.2 (proposal 0018, spec v0.16.0). No except-wrap
# needed here — the canonical category propagates straight
# through and the registry's exception contract is one type
# regardless of when ambiguity surfaces (register vs resolve).
chain = self.migration_registry.resolve_chain(
record.schema_version,
current_schema_version,
)
if chain is None:
raise CheckpointStateMigrationMissing(
f"no migration chain from {record.schema_version!r} to {current_schema_version!r}",
from_version=record.schema_version,
to_version=current_schema_version,
registered_migrations_count=len(self.migration_registry),
registry_description=self.migration_registry.describe(),
)
migrated_state: Any = record.state
migrated_parents: list[Any] = list(record.parent_states)
for migration in chain:
migrated_state = _apply_migration_step(migration, migrated_state, "state")
for i, parent in enumerate(migrated_parents):
migrated_parents[i] = _apply_migration_step(migration, parent, f"parent_states[{i}]")
# Per spec §6 cross-ref, the caller dispatches a synthetic
# ``checkpoint_migrated`` observer event using the summary
# below as soon as the invocation context exists. We can't
# dispatch from here because the context isn't built yet.
summary = _MigrationSummary(
from_version=record.schema_version,
to_version=current_schema_version,
chain_length=len(chain),
)
migrated = dataclass_replace(
record,
state=migrated_state,
parent_states=tuple(migrated_parents),
)
return migrated, summary
async def drain(self, timeout: float | None = None) -> DrainSummary:
"""Await delivery of every observer event produced by prior
invocations of this graph, optionally bounded by ``timeout``.
Callers running in short-lived processes (scripts, serverless
functions, CLIs) MUST use drain to avoid losing observer events
that were dispatched but not yet delivered.
Only events dispatched before this call are awaited; events
from invocations started concurrently with drain may or may
not be included. Subgraph events from active invocations are
part of the parent invocation's worker and are covered
automatically.
``timeout`` is a non-negative duration in seconds. If omitted
or ``None``, drain waits indefinitely — a slow, hung, or
misbehaving observer can therefore hold drain (and the calling
process) indefinitely. If supplied, drain returns no later
than ``timeout`` seconds after the call begins; any observer
events still queued or in-flight at that point are considered
undelivered. Workers are cancelled via ``Task.cancel()`` so
the compiled graph remains usable for subsequent invocations
— partial delivery state from one drain does NOT leak into
the next invocation.
Returns a :class:`DrainSummary` with ``undelivered_count`` and
``timeout_reached`` fields. The shape is the same whether or
not a timeout was supplied; on the no-timeout / timeout-not-
fired path both fields are zero / false.
Observers SHOULD be written to be cancellation-safe
(idempotent writes, try/finally cleanup) so that interruption
by drain timeout does not leave partial side effects in an
inconsistent state.
Raises ``ValueError`` if ``timeout`` is negative or NaN.
Non-numeric input raises ``TypeError`` from the comparison.
"""
# ``not (timeout >= 0)`` is the right check: catches negative
# values, catches NaN (all comparisons with NaN return False),
# and lets non-numeric input raise ``TypeError`` from the
# comparison operator itself. Silently treating a negative
# timeout as "immediate cancel" would be a user-hostile failure
# mode — the spec contract is non-negative seconds.
if timeout is not None and not (timeout >= 0):
raise ValueError(f"drain timeout must be non-negative, got {timeout!r}")
if not self._active_workers:
return DrainSummary(undelivered_count=0, timeout_reached=False)
# Snapshot the dict: each worker's done-callback removes its
# entry from `_active_workers`, so iterating directly while
# `asyncio.wait` awaits would mutate during iteration.
snapshot = dict(self._active_workers)
workers = list(snapshot.keys())
_done, pending = await asyncio.wait(
workers,
timeout=timeout,
return_when=asyncio.ALL_COMPLETED,
)
if pending:
undelivered = sum(
snapshot[w].drain_counters.dispatched - snapshot[w].drain_counters.delivered for w in pending
)
timeout_reached = True
for w in pending:
w.cancel()
else:
undelivered = 0
timeout_reached = False
# Gather ALL workers (done + pending) so any exception that
# escaped a delivery worker surfaces here instead of leaking
# as a "Task exception was never retrieved" warning. The
# ``return_exceptions=True`` absorbs both the synthetic
# ``CancelledError`` from cancelled workers and any genuine
# bug-escape from a ``deliver_loop`` that ever raised past
# its inner ``warnings.warn`` isolation. Also load-bearing
# for the cross-invocation cleanliness contract — done-
# callbacks fire on cancellation, so ``_active_workers`` is
# empty by the time we return.
await asyncio.gather(*workers, return_exceptions=True)
return DrainSummary(undelivered_count=undelivered, timeout_reached=timeout_reached)
# ------------------------------------------------------------------
# Public invocation
# ------------------------------------------------------------------
async def invoke(
self,
initial_state: StateT,
observers: Iterable[Observer | SubscribedObserver] | None = None,
*,
correlation_id: str | None = None,
invocation_id: str | None = None,
resume_invocation: str | None = None,
metadata: Mapping[str, Any] | None = None,
) -> StateT:
"""Run the graph from ``initial_state`` to END and return the
final state.
Optional ``observers`` are invocation-scoped; they fire only
for this run, after all graph-attached observers (including
subgraph-attached ones for events originating in subgraphs).
Each entry in ``observers`` may be either a bare ``Observer``
callable (subscribes to both phases) or a ``SubscribedObserver``
wrapping an observer with an explicit ``phases`` set.
This method returns as soon as the graph execution loop
completes, regardless of whether the observer delivery queue
has finished processing every dispatched event. Use
``await compiled.drain()`` if you need delivery-completion
guarantees.
**Checkpointing.**
- ``correlation_id`` is the per-invocation cross-backend join
key. Caller-supplied or auto-generated UUIDv4 when absent.
Preserved unchanged across ``resume_invocation``.
- ``invocation_id`` (proposal 0039) is the per-attempt id.
Caller-supplied or auto-generated UUIDv4 when absent; a
caller value MAY be any non-empty URL-safe string. Applies
to the fresh-invocation path only — a ``resume_invocation``
mints a fresh id regardless (each attempt is its own
invocation).
- ``resume_invocation`` names a prior ``invocation_id`` to
resume from. Requires a registered Checkpointer; raises
``CheckpointNotFound`` when the backend has no record for
the supplied id, ``CheckpointRecordInvalid`` when the
loaded record's schema is incompatible. Resume mints a NEW
``invocation_id``; each attempt is its own invocation in
the observability sense; the ``correlation_id`` is the
cross-attempt join key.
- **Save-failure policy.** This implementation raises
``CheckpointSaveFailed`` to the caller of ``invoke()``
immediately when ``Checkpointer.save`` raises; saves are
NOT retried by the engine. Wrap the Checkpointer in your
own retry logic if transient backend failures should be
reattempted.
**Caller-supplied invocation metadata (proposal 0034).**
- ``metadata`` is an optional mapping of arbitrary
``key → value`` entries the framework propagates to every
observability backend. Values MUST be OTel-attribute-
compatible scalars (``str`` / ``int`` / ``float`` / ``bool``)
or homogeneous arrays of those types. Keys MUST NOT use
the ``openarmature.*`` or ``gen_ai.*`` reserved namespaces.
Validation runs synchronously at the API boundary; rule
violations raise ``ValueError`` BEFORE any work begins.
- Per spec §5.6 the OTel observer emits each entry as an
``openarmature.user.<key>`` cross-cutting span attribute on
every span and OTel log record. The Langfuse observer
merges each entry into ``trace.metadata`` AND every
``observation.metadata`` (top level, sibling to
``correlation_id``).
- Mid-invocation augmentation via
:func:`openarmature.observability.set_invocation_metadata`
merges into the same ContextVar with the same validation
rules; affects spans emitted AFTER the call returns.
Raises one of the runtime error categories on failure.
"""
# Validate caller-supplied metadata at the API boundary so any
# rule violation surfaces synchronously before the worker task
# is created or any node body runs.
validated_metadata = validate_invocation_metadata(metadata)
invocation_scoped = tuple(_coerce_subscribed(o) for o in (observers or ()))
queue: asyncio.Queue[_QueuedItem | None] = asyncio.Queue()
# Resolve the resume path BEFORE building the context so we can
# restore the correlation_id from the saved record (per §10.4
# step 3) and pre-populate the skip-set + completed_positions.
starting_state: StateT = initial_state
resolved_correlation_id = correlation_id or str(uuid.uuid4())
# Caller-supplied invocation_id (proposal 0039) applies to the
# fresh-invocation path only; a resume mints a fresh id
# regardless (each attempt is its own invocation, §5.1).
if invocation_id is not None and resume_invocation is None:
invocation_id = validate_invocation_id(invocation_id)
else:
invocation_id = str(uuid.uuid4())
resume_skip_set: frozenset[tuple[str, ...]] = frozenset()
completed_positions: list[NodePosition] = []
pending_resume_states: dict[int, Any] = {}
# Populated by ``_migrate_record`` during a version-mismatched
# resume; left ``None`` for the no-resume + versions-match
# paths. Dispatched as a synthetic ``checkpoint_migrated``
# observer event after the invocation context is built so
# the OTel observer can emit an
# ``openarmature.checkpoint.migrate`` span per spec §6.
migration_summary: _MigrationSummary | None = None
if resume_invocation is not None:
checkpointer = self._checkpointer_slot[0]
if checkpointer is None:
# §10.1.1: resume against an unregistered backend
# surfaces as ``checkpoint_not_found`` — the user has
# misconfigured the run.
raise CheckpointNotFound(resume_invocation)
record = await checkpointer.load(resume_invocation)
if record is None:
raise CheckpointNotFound(resume_invocation)
# Per spec §10.12 (proposal 0014): version-mismatch resume.
# Routing precedence (per §10.10 + §10.12.1):
# 1. unsupported backend → CheckpointRecordInvalid.
# Backends that hold typed in-memory state or
# class-bound serialization can't expose the
# class-independent intermediate the migration
# registry needs.
# 2. no chain in the registry → CheckpointStateMigrationMissing.
# Actionable: register a migration.
# 3. chain found but a migration raises →
# CheckpointStateMigrationFailed.
# 4. post-migration state fails to deserialize →
# CheckpointRecordInvalid (the §10.12.4 boundary).
# Order matters — do NOT swap eligibility and registry-lookup.
current_schema_version = self.state_cls.schema_version
if record.schema_version != current_schema_version:
record, migration_summary = await self._migrate_record(
record,
checkpointer,
resume_invocation,
current_schema_version,
)
# The saved record's ``state`` is post-merge state at the
# saving node's level (depth = len(parent_states)). For
# outer-level saves, parent_states is empty and ``state``
# IS the outermost state. For inner-node saves
# (parent_states populated), the OUTERMOST state lives in
# ``parent_states[0]`` and the deeper levels are
# parent_states[1:] + (state,) at depths 1..N. The descent
# path consumes the depth-keyed map to skip projection
# when re-entering an in-flight subgraph.
parent_states_chain: tuple[Any, ...] = record.parent_states
if parent_states_chain:
outer_raw = parent_states_chain[0]
# Inner depths 1..N: parent_states[1:] then state at depth N.
deeper_states = list(parent_states_chain[1:]) + [record.state]
for depth, st in enumerate(deeper_states, start=1):
pending_resume_states[depth] = st
else:
outer_raw = record.state
# State coercion: if the record carries a Pydantic instance
# (in-memory backend), use it directly; if it's a dict (JSON-
# mode SQLite), re-validate against the declared state class.
# A validation failure means the persisted record is
# incompatible with the current graph (state-shape mismatch
# or missing required fields), which §10.10 names as
# ``checkpoint_record_invalid`` — wrap the ValidationError
# so callers see the canonical category, not the raw
# pydantic exception.
if isinstance(outer_raw, dict):
try:
starting_state = self.state_cls.model_validate(outer_raw)
except ValidationError as exc:
raise CheckpointRecordInvalid(
resume_invocation,
f"saved outer state does not validate against {self.state_cls.__name__}: {exc}",
) from exc
else:
starting_state = cast("StateT", outer_raw)
# §10.4 step 3: keep the original correlation_id verbatim.
# Per spec resume MUST preserve the cross-backend join key.
resolved_correlation_id = record.correlation_id
completed_positions = list(record.completed_positions)
# Skip-set keys are the FULL identity tuple of a node:
# NodePosition.namespace + (NodePosition.node_name,). This
# matches what the engine looks up at run time
# (``context.namespace_prefix + (current,)``).
resume_skip_set = frozenset(p.namespace + (p.node_name,) for p in completed_positions)
# Per spec §10.7 / §10.11: restore per-fan-out per-instance
# state from the loaded record. ``FanOutNode.run_with_context``
# consults this on re-dispatch — completed instances skip,
# in_flight / not_started instances re-execute. Empty tuple
# when no fan-outs were in flight at save time.
fan_out_progress_state = _restore_fan_out_progress_state(record.fan_out_progress)
else:
fan_out_progress_state = {}
context = _InvocationContext(
queue=queue,
graph_attached=tuple(self._attached_observers),
invocation_scoped=invocation_scoped,
invocation_id=invocation_id,
correlation_id=resolved_correlation_id,
checkpointer=self._checkpointer_slot[0],
completed_positions=completed_positions,
resume_skip_set=resume_skip_set,
pending_resume_states=pending_resume_states,
resume_invocation=resume_invocation,
fan_out_progress_state=fan_out_progress_state,
# Per spec §10.2 (proposal 0028): the canonical source for
# ``schema_version`` on every save during this invocation.
# Threaded unchanged through every descent.
state_cls=self.state_cls,
)
# Spec observability §3.1: the correlation_id MUST be readable
# from anywhere within the invocation's async call tree via the
# language's idiomatic context primitive. Set the ContextVar
# BEFORE creating the delivery worker so the worker's captured
# context sees the correlation_id (asyncio.create_task snapshots
# the current Context at creation time). Reset on return so
# subsequent invocations get a fresh slate. Nested ``invoke()``
# calls (subgraph-as-node uses ``_invoke`` directly, not the
# public ``invoke``, so they don't re-set; see §3.1's
# "per-invocation is OUTERMOST invoke" wording).
correlation_token = _set_correlation_id(resolved_correlation_id)
invocation_token = _set_invocation_id(invocation_id)
metadata_token = _set_invocation_metadata(validated_metadata)
worker = asyncio.create_task(deliver_loop(queue, context.drain_counters))
self._active_workers[worker] = context
# Auto-prune: when the worker completes (after the sentinel is