-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternal_action_coordinator.py
More file actions
1546 lines (1478 loc) · 56.6 KB
/
Copy pathexternal_action_coordinator.py
File metadata and controls
1546 lines (1478 loc) · 56.6 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
from __future__ import annotations
import json
from collections.abc import Callable, Mapping
from typing import Any, ClassVar, NoReturn
from pydantic import ValidationError
from agent.contracts import RuntimeExecutionContext, RuntimeExecutionError
from .canonical import canonical_json, decode_tool_result, stable_hash
from .evidence import EvidenceProjector
from .external_actions import (
DefinitiveExternalActionError,
ExternalActionDispatcher,
ExternalActionProvider,
ExternalActionProviderResult,
ExternalActionReconciliationPendingError,
ExternalActionRequest,
)
from .planner import ToolObservation
from .sandbox import ToolRetryMode, ToolSpec
from .workflow_store import (
ClaimOutcome,
ExternalActionDispatchOutcome,
ExternalActionPrepareOutcome,
ExternalActionRecord,
ExternalActionStatus,
ToolCallRecord,
ToolCallStatus,
WorkflowStore,
)
class ExternalActionCoordinator:
"""Coordinates the durable external-action state machine.
The coordinator owns no per-call state. Every transition is fenced by the
durable Workflow Store so retries and restart recovery preserve the same
action identity and provider-dispatch semantics.
"""
# Every message the coordinator can surface, so a host that supplies a
# narrower table cannot turn a post-dispatch failure path into a KeyError.
DEFAULT_FAILURE_MESSAGES: ClassVar[Mapping[str, str]] = {
"external_action_failed": "External action failed definitively.",
"external_action_outcome_unknown": (
"External action outcome is unknown and was not retried again."
),
"external_action_evidence_incomplete": (
"External action completed, but durable run evidence is incomplete."
),
"run_cancel_requested": (
"Run cancellation was requested before external action dispatch."
),
}
# Reconciliation prefers the least-proven known outcome, because a record
# that cannot prove a provider result must not be masked by a terminal
# sibling. Any unknown status, or a corrupt PREPARED row that claims a
# dispatch already occurred, blocks selection entirely and keeps the Run
# reconciliation-pending.
_RECONCILE_PRIORITY: ClassVar[Mapping[ExternalActionStatus, int]] = {
ExternalActionStatus.DISPATCHING: 0,
ExternalActionStatus.OUTCOME_UNKNOWN: 1,
ExternalActionStatus.SUCCEEDED: 2,
ExternalActionStatus.FAILED: 3,
ExternalActionStatus.PREPARED: 4,
}
def __init__(
self,
*,
workflow_store: WorkflowStore,
dispatcher: ExternalActionDispatcher | None,
workflow_type: str,
evidence_projector: EvidenceProjector,
fail: Callable[[str, str, str], NoReturn],
failure_messages: Mapping[str, str] | Callable[[], Mapping[str, str]],
max_dispatches: int | Callable[[], int] = 2,
) -> None:
self.workflow_store = workflow_store
self.dispatcher = dispatcher
self.workflow_type = workflow_type
self.evidence_projector = evidence_projector
self.fail = fail
self._failure_messages = failure_messages
self._max_dispatches = max_dispatches
@property
def failure_messages(self) -> Mapping[str, str]:
if callable(self._failure_messages):
return self._failure_messages()
return self._failure_messages
def failure_message(self, code: str) -> str:
"""Resolve a safe message, falling back before a failure path can raise.
These lookups happen only while terminalizing a run whose provider call
may already have been applied, so a host table missing a code must not
replace the outcome with a KeyError.
"""
message = self.failure_messages.get(code)
if message is None:
return self.DEFAULT_FAILURE_MESSAGES.get(code, "External action failed.")
return message
@property
def max_dispatches(self) -> int:
if callable(self._max_dispatches):
return self._max_dispatches()
return self._max_dispatches
def provider_for(self, spec: ToolSpec) -> ExternalActionProvider | None:
"""Resolve the server-owned provider used by policy preflight."""
if self.dispatcher is None or spec.provider_name is None:
return None
return self.dispatcher.registry.resolve(spec.provider_name)
def dispatched_action(
self,
run_id: str,
step_id: str,
) -> ExternalActionRecord | None:
action = self.workflow_store.get_external_action(run_id, step_id)
if action is None or action.dispatch_count < 1:
return None
return action
def reconcile_dispatched_action(
self,
*,
context: RuntimeExecutionContext,
action: ExternalActionRecord | None = None,
include_terminal: bool = True,
) -> None:
"""Fail safely when preflight/identity drift blocks ledger recovery.
Once dispatch_count is non-zero, current registry, permission, provider,
input-schema, or thread-state drift must never downgrade the run to an
ordinary validation/configuration failure. The provider may already
have applied the write.
"""
if action is None:
dispatched_actions = [
candidate
for candidate in self.workflow_store.list_external_actions(context.run_id)
if candidate.dispatch_count > 0
]
if not dispatched_actions:
return
reconciliation_pending = any(
candidate.status not in self._RECONCILE_PRIORITY
or candidate.status == ExternalActionStatus.PREPARED
for candidate in dispatched_actions
)
if not reconciliation_pending:
actions = [
candidate
for candidate in dispatched_actions
if include_terminal or not candidate.status.is_terminal
]
if not actions:
return
action = min(
actions,
key=lambda candidate: self._RECONCILE_PRIORITY[candidate.status],
)
else:
reconciliation_pending = (
action.status not in self._RECONCILE_PRIORITY
or action.status == ExternalActionStatus.PREPARED
)
if (
not reconciliation_pending
and action.status.is_terminal
and not include_terminal
):
return
try:
self._mirror_evidence(context.run_id)
except Exception:
pass
if reconciliation_pending or action is None:
raise ExternalActionReconciliationPendingError()
if action.status == ExternalActionStatus.DISPATCHING:
step = self.workflow_store.get_step(context.run_id, action.step_id)
if step is None:
raise ExternalActionReconciliationPendingError()
self._fail_external_dispatch_binding(
context=context,
step=step,
action=action,
)
elif action.status == ExternalActionStatus.OUTCOME_UNKNOWN:
code = "external_action_outcome_unknown"
elif action.status == ExternalActionStatus.SUCCEEDED:
code = "external_action_evidence_incomplete"
elif action.status == ExternalActionStatus.FAILED:
code = "external_action_failed"
else:
# PREPARED with dispatch_count > 0 is corrupt and cannot prove that
# a provider call did not happen. It also cannot be fenced into a
# terminal outcome, so keep the Run recoverable for reconciliation.
raise ExternalActionReconciliationPendingError()
try:
self._fail(
context.run_id,
code,
"Dispatched external action could not be reconciled.",
)
except RuntimeExecutionError as exc:
if exc.code == code:
raise
except Exception:
pass
raise RuntimeExecutionError(code, self.failure_message(code))
def execute(
self,
*,
context: RuntimeExecutionContext,
tool_name: str,
spec: ToolSpec,
step_id: str,
normalized_arguments: dict[str, Any],
) -> ToolObservation:
provider_name = spec.provider_name
if provider_name is None or self.dispatcher is None:
# Authorization performs this check before a step is claimed. Keep
# the execution boundary fail-closed if a caller invokes it
# independently or mutates server configuration between phases.
self._fail(
context.run_id,
"external_action_not_configured",
"External action provider is not configured.",
)
provider = self.dispatcher.registry.resolve(provider_name)
if provider is None:
self._fail(
context.run_id,
"external_action_not_configured",
"External action provider is not configured.",
)
provider_identity = provider.provider_identity
input_hash = self._stable_hash(normalized_arguments)
arguments_json = self.canonical_json(normalized_arguments)
idempotency_key = self.idempotency_key(
context=context,
step_id=step_id,
tool_name=tool_name,
input_hash=input_hash,
)
existing = self.workflow_store.get_step(context.run_id, step_id)
if existing is not None and existing.status == ToolCallStatus.COMPLETED:
return self.restore_success(
context=context,
step=existing,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
if existing is not None and existing.status == ToolCallStatus.FAILED:
self.restore_failure(
context=context,
step=existing,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
if existing is not None and existing.status == ToolCallStatus.RUNNING:
if not context.recovered_after_restart:
self._fail(
context.run_id,
"tool_execution_failed",
"External action is already running without a recovery boundary.",
)
if existing.attempt_token is None:
raise ExternalActionReconciliationPendingError()
step = existing
attempt_token = existing.attempt_token
recovered_dispatch = True
else:
claim = self.workflow_store.claim_step(
context.run_id,
step_id,
tool_name,
input_hash,
max_attempts=1,
)
if claim.outcome == ClaimOutcome.CACHED:
assert claim.step is not None
return self.restore_success(
context=context,
step=claim.step,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
if claim.outcome in {
ClaimOutcome.INPUT_MISMATCH,
ClaimOutcome.DEFINITION_MISMATCH,
}:
self._fail(
context.run_id,
"invalid_planner_decision",
"Persisted external action identity does not match the decision.",
)
if claim.outcome in {
ClaimOutcome.ALREADY_RUNNING,
ClaimOutcome.ATTEMPTS_EXHAUSTED,
}:
self._fail(
context.run_id,
"tool_execution_failed",
f"External action step could not be claimed: {claim.outcome.value}.",
)
assert claim.outcome == ClaimOutcome.CLAIMED
assert claim.step is not None and claim.attempt_token is not None
step = claim.step
attempt_token = claim.attempt_token
recovered_dispatch = False
try:
prepared = self.workflow_store.prepare_external_action(
run_id=context.run_id,
step_id=step_id,
tool_attempt_token=attempt_token,
tenant_id=context.authority.tenant_id,
subject_id=context.authority.subject_id,
workflow_type=self.workflow_type,
tool_name=tool_name,
provider_name=provider_name,
provider_identity=provider_identity,
input_hash=input_hash,
arguments_json=arguments_json,
retry_mode=spec.retry_mode.value,
idempotency_key=idempotency_key,
)
except Exception:
if recovered_dispatch:
# The existing RUNNING step may already own a DISPATCHING
# action. If its ledger row cannot be read or validated, keep
# both Workflow and Run non-terminal for startup recovery.
raise ExternalActionReconciliationPendingError() from None
self._fail(
context.run_id,
"invalid_planner_decision",
"External action preparation failed before dispatch.",
)
self._mirror_evidence(context.run_id)
if prepared.outcome in {
ExternalActionPrepareOutcome.IDENTITY_MISMATCH,
ExternalActionPrepareOutcome.TOOL_ATTEMPT_MISMATCH,
}:
mismatched_action = prepared.action
if mismatched_action is None:
try:
mismatched_action = self.workflow_store.get_external_action(
context.run_id,
step_id,
)
except Exception:
mismatched_action = None
if (
mismatched_action is not None
and mismatched_action.status == ExternalActionStatus.DISPATCHING
):
self._fail_external_dispatch_binding(
context=context,
step=step,
action=mismatched_action,
)
self._fail(
context.run_id,
"invalid_planner_decision",
"Persisted external action binding does not match this execution.",
)
assert prepared.action is not None
action = prepared.action
self._validate_external_action_binding(
context=context,
step=step,
action=action,
spec=spec,
provider_identity=provider_identity,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
try:
self._external_action_request(action)
except (json.JSONDecodeError, RuntimeExecutionError, ValidationError):
if action.status == ExternalActionStatus.DISPATCHING:
self._fail_external_dispatch_binding(
context=context,
step=step,
action=action,
)
self._fail(
context.run_id,
"invalid_planner_decision",
"Prepared external action cannot form a provider request.",
)
if action.status == ExternalActionStatus.PREPARED:
dispatch = self.workflow_store.begin_external_action_dispatch(
context.run_id,
step_id,
tool_attempt_token=attempt_token,
)
self._mirror_evidence(context.run_id)
if dispatch.outcome == ExternalActionDispatchOutcome.RUN_CANCELLED:
raise RuntimeExecutionError(
"run_cancel_requested",
self.failure_message("run_cancel_requested"),
)
if dispatch.outcome == ExternalActionDispatchOutcome.TERMINAL:
return self._handle_external_terminal(
context=context,
step=step,
action=dispatch.action,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
if dispatch.outcome != ExternalActionDispatchOutcome.CLAIMED:
self._fail(
context.run_id,
"tool_execution_failed",
f"External action dispatch could not be claimed: {dispatch.outcome.value}.",
)
action = dispatch.action
dispatch_token = dispatch.dispatch_token
elif action.status == ExternalActionStatus.DISPATCHING:
if not recovered_dispatch:
self._fail(
context.run_id,
"tool_execution_failed",
"External action dispatch is already in progress.",
)
return self._recover_external_dispatch(
context=context,
step=step,
action=action,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
attempt_token=attempt_token,
)
else:
return self._handle_external_terminal(
context=context,
step=step,
action=action,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
if dispatch_token is None:
self._fail(
context.run_id,
"invalid_planner_decision",
"Claimed external action dispatch has no token.",
)
return self._dispatch_external_action(
context=context,
step=step,
action=action,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
attempt_token=attempt_token,
dispatch_token=dispatch_token,
)
def _recover_external_dispatch(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
action: ExternalActionRecord,
spec: ToolSpec,
normalized_arguments: dict[str, Any],
input_hash: str,
idempotency_key: str,
attempt_token: str,
) -> ToolObservation:
dispatch_token = action.dispatch_token
if dispatch_token is None:
raise ExternalActionReconciliationPendingError()
if spec.retry_mode == ToolRetryMode.UNSAFE:
self._raise_external_outcome_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
finalizer=lambda: self.workflow_store.finalize_unsafe_interrupted_action(
context.run_id,
step.step_id,
dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
),
)
if action.dispatch_count >= self.max_dispatches:
self._finalize_external_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
)
retry = self.workflow_store.retry_external_action_dispatch(
context.run_id,
step.step_id,
previous_dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
)
self._mirror_evidence(context.run_id)
if retry.outcome == ExternalActionDispatchOutcome.TERMINAL:
return self._handle_external_terminal(
context=context,
step=step,
action=retry.action,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
)
if (
retry.outcome != ExternalActionDispatchOutcome.RETRY_CLAIMED
or retry.dispatch_token is None
):
self._fail(
context.run_id,
"invalid_planner_decision",
f"Persisted external action could not be safely recovered: {retry.outcome.value}.",
)
return self._dispatch_external_action(
context=context,
step=step,
action=retry.action,
spec=spec,
normalized_arguments=normalized_arguments,
input_hash=input_hash,
idempotency_key=idempotency_key,
attempt_token=attempt_token,
dispatch_token=retry.dispatch_token,
)
def _dispatch_external_action(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
action: ExternalActionRecord,
spec: ToolSpec,
normalized_arguments: dict[str, Any],
input_hash: str,
idempotency_key: str,
attempt_token: str,
dispatch_token: str,
) -> ToolObservation:
assert spec.provider_name is not None
assert self.dispatcher is not None
while True:
provider = self.dispatcher.registry.resolve(spec.provider_name)
if provider is None or provider.provider_identity != action.provider_identity:
# The dispatch claim already won its durable race. If routing
# changes after preparation, do not send the key to a different
# provider/account ledger; conservatively close as unknown.
self._finalize_external_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
)
request = self._external_action_request(action)
try:
provider_result: ExternalActionProviderResult = self.dispatcher.dispatch(
provider_name=spec.provider_name,
retry_mode=spec.retry_mode,
request=request,
)
except DefinitiveExternalActionError:
try:
self.workflow_store.finalize_external_action_failed(
context.run_id,
step.step_id,
dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
error_code="external_action_failed",
)
except Exception:
if not self._external_failure_was_committed(
context=context,
step=step,
expected_action=action,
dispatch_token=dispatch_token,
):
self._raise_external_outcome_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
finalizer=lambda: (
self.workflow_store.finalize_external_action_outcome_unknown(
context.run_id,
step.step_id,
dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
error_code="external_action_outcome_unknown",
)
),
)
self._raise_external_terminal_failure(
context=context,
step=step,
error_code="external_action_failed",
)
except Exception:
retry = self._retry_after_ambiguous_result(
context=context,
step=step,
action=action,
spec=spec,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
)
if retry is None:
self._finalize_external_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
)
action, dispatch_token = retry
continue
trusted_result = {
**provider_result.result,
"provider_reference": provider_result.provider_reference,
}
assert spec.output_model is not None # ToolRegistry invariant
try:
if self._contains_sensitive_text(
trusted_result,
idempotency_key,
):
raise ValueError("Provider output contains a runtime idempotency key")
trusted_result = spec.output_model.model_validate(
trusted_result,
context={"arguments": normalized_arguments},
).model_dump(mode="json")
if self._contains_sensitive_text(
trusted_result,
idempotency_key,
):
raise ValueError(
"Normalized provider output contains a runtime idempotency key"
)
result_json = self.canonical_json(trusted_result)
except (TypeError, ValueError, ValidationError):
retry = self._retry_after_ambiguous_result(
context=context,
step=step,
action=action,
spec=spec,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
)
if retry is None:
self._finalize_external_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
)
action, dispatch_token = retry
continue
try:
self.workflow_store.finalize_external_action_succeeded(
context.run_id,
step.step_id,
dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
result_json=result_json,
provider_reference=provider_result.provider_reference,
)
except Exception:
if not self._external_success_was_committed(
context=context,
step=step,
expected_action=action,
dispatch_token=dispatch_token,
result_json=result_json,
provider_reference=provider_result.provider_reference,
):
self._raise_external_outcome_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
finalizer=lambda: (
self.workflow_store.finalize_external_action_outcome_unknown(
context.run_id,
step.step_id,
dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
error_code="external_action_outcome_unknown",
)
),
)
self._record_external_success_evidence(
context=context,
step=step,
result=trusted_result,
)
return ToolObservation(
step_id=step.step_id,
tool_name=step.tool_name,
arguments=normalized_arguments,
result=trusted_result,
)
def _retry_after_ambiguous_result(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
action: ExternalActionRecord,
spec: ToolSpec,
dispatch_token: str,
attempt_token: str,
) -> tuple[ExternalActionRecord, str] | None:
if spec.retry_mode == ToolRetryMode.UNSAFE or action.dispatch_count >= self.max_dispatches:
return None
retry = self.workflow_store.retry_external_action_dispatch(
context.run_id,
step.step_id,
previous_dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
)
self._mirror_evidence(context.run_id)
if (
retry.outcome == ExternalActionDispatchOutcome.RETRY_CLAIMED
and retry.dispatch_token is not None
):
return retry.action, retry.dispatch_token
if retry.outcome == ExternalActionDispatchOutcome.TERMINAL:
# A concurrent terminal write cannot be returned from this helper
# without revalidating its tool/result binding. Treat it as a
# durable integrity failure rather than dispatching again.
self._fail(
context.run_id,
"invalid_planner_decision",
"External action became terminal during an ambiguous retry.",
)
if retry.outcome == ExternalActionDispatchOutcome.RETRY_UNSAFE:
return None
self._fail(
context.run_id,
"invalid_planner_decision",
f"External action retry state is invalid: {retry.outcome.value}.",
)
def _finalize_external_unknown(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
dispatch_token: str,
attempt_token: str,
) -> NoReturn:
self._raise_external_outcome_unknown(
context=context,
step=step,
dispatch_token=dispatch_token,
attempt_token=attempt_token,
finalizer=lambda: self.workflow_store.finalize_external_action_outcome_unknown(
context.run_id,
step.step_id,
dispatch_token=dispatch_token,
tool_attempt_token=attempt_token,
error_code="external_action_outcome_unknown",
),
)
def _external_success_was_committed(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
expected_action: ExternalActionRecord,
dispatch_token: str,
result_json: str,
provider_reference: str,
) -> bool:
"""Resolve an exception thrown after the terminal transaction boundary.
A wrapper, connection cleanup, or injected crash can raise after SQLite
committed. Re-reading exact action/tool identity prevents downgrading a
durable success to unknown while still refusing to trust a different
terminal record.
"""
try:
action = self.workflow_store.get_external_action(
context.run_id,
step.step_id,
)
current_step = self.workflow_store.get_step(
context.run_id,
step.step_id,
)
except Exception:
return False
if action is None or current_step is None:
return False
identity = (
action.action_id,
action.run_id,
action.step_id,
action.tenant_id,
action.subject_id,
action.workflow_type,
action.tool_name,
action.provider_name,
action.provider_identity,
action.input_hash,
action.arguments_json,
action.retry_mode,
action.idempotency_key,
)
expected_identity = (
expected_action.action_id,
expected_action.run_id,
expected_action.step_id,
expected_action.tenant_id,
expected_action.subject_id,
expected_action.workflow_type,
expected_action.tool_name,
expected_action.provider_name,
expected_action.provider_identity,
expected_action.input_hash,
expected_action.arguments_json,
expected_action.retry_mode,
expected_action.idempotency_key,
)
return bool(
identity == expected_identity
and action.status == ExternalActionStatus.SUCCEEDED
and action.dispatch_token == dispatch_token
and action.provider_reference == provider_reference
and action.result_json == result_json
and action.error_code is None
and current_step.status == ToolCallStatus.COMPLETED
and current_step.attempt_token == step.attempt_token
and current_step.result_json == result_json
and current_step.error_code is None
)
def _external_failure_was_committed(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
expected_action: ExternalActionRecord,
dispatch_token: str,
) -> bool:
"""Resolve an exception raised after a definitive terminal commit."""
try:
action = self.workflow_store.get_external_action(
context.run_id,
step.step_id,
)
current_step = self.workflow_store.get_step(
context.run_id,
step.step_id,
)
except Exception:
return False
if action is None or current_step is None:
return False
identity = (
action.action_id,
action.run_id,
action.step_id,
action.tenant_id,
action.subject_id,
action.workflow_type,
action.tool_name,
action.provider_name,
action.provider_identity,
action.input_hash,
action.arguments_json,
action.retry_mode,
action.idempotency_key,
)
expected_identity = (
expected_action.action_id,
expected_action.run_id,
expected_action.step_id,
expected_action.tenant_id,
expected_action.subject_id,
expected_action.workflow_type,
expected_action.tool_name,
expected_action.provider_name,
expected_action.provider_identity,
expected_action.input_hash,
expected_action.arguments_json,
expected_action.retry_mode,
expected_action.idempotency_key,
)
return bool(
identity == expected_identity
and action.status == ExternalActionStatus.FAILED
and action.dispatch_token == dispatch_token
and action.provider_reference is None
and action.result_json is None
and action.error_code == "external_action_failed"
and current_step.status == ToolCallStatus.FAILED
and current_step.attempt_token == step.attempt_token
and current_step.result_json is None
and current_step.error_code == "external_action_failed"
)
def _record_external_success_evidence(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
result: dict[str, Any],
) -> None:
# A mirror can fail after its workflow event committed. One complete
# retry repairs either side of that gap without invoking the provider.
for _ in range(2):
try:
self._mirror_evidence(context.run_id)
self._record_tool_success(
context.run_id,
step.step_id,
step.tool_name,
result,
)
return
except Exception:
continue
raise RuntimeExecutionError(
"external_action_evidence_incomplete",
self.failure_message("external_action_evidence_incomplete"),
)
def _raise_external_terminal_failure(
self,
*,
context: RuntimeExecutionContext,
step: ToolCallRecord,
error_code: str,
) -> NoReturn:
"""Preserve a proven terminal failure across run-evidence outages."""
for _ in range(2):
try:
self._mirror_evidence(context.run_id)
self._record_tool_failure(
context.run_id,
step.step_id,
step.tool_name,
error_code,
)
break
except Exception:
continue
try:
self._fail(
context.run_id,
error_code,
"Persisted external action failed.",
)
except RuntimeExecutionError as exc:
if exc.code == error_code:
raise