phronomy 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -0
  3. data/README.md +24 -2
  4. data/SECURITY.md +1 -1
  5. data/docs/architecture/agent-approval-recovery.md +320 -0
  6. data/docs/architecture/agent-child-approval-recovery.md +387 -0
  7. data/docs/architecture/agent-child-execution-recovery.md +425 -0
  8. data/docs/architecture/agent-dispatch-recovery.md +308 -0
  9. data/docs/architecture/agent-terminal-persistence-evidence.md +360 -0
  10. data/docs/architecture/agent-terminal-recovery.md +298 -0
  11. data/docs/architecture/agent-terminal-submission-recovery.md +275 -0
  12. data/docs/architecture/agent-tool-child-lifetime.md +29 -0
  13. data/docs/architecture/agent-transition-ownership.md +24 -0
  14. data/docs/architecture/backend-groups.md +6 -0
  15. data/docs/architecture/detached-outcome-proof-projection.md +576 -0
  16. data/docs/architecture/execution-abstraction-review.md +5 -0
  17. data/docs/architecture/handoff-dispatch-recovery.md +205 -0
  18. data/docs/architecture/handoff-initial-terminal-application.md +321 -0
  19. data/docs/architecture/initial-preparation-recovery.md +308 -0
  20. data/docs/architecture/multi-agent-handoff.md +17 -0
  21. data/docs/architecture/native-outcome-preparation.md +715 -0
  22. data/docs/architecture/native-parent-dispatch-recovery.md +460 -0
  23. data/docs/architecture/native-parent-outcome-recovery.md +644 -0
  24. data/docs/architecture/parent-child-terminal-acknowledgement.md +297 -0
  25. data/docs/architecture/r8-unit12.md +6 -3
  26. data/docs/architecture/r8-unit4.md +11 -2
  27. data/docs/architecture/recovery-physical-attempt.md +88 -0
  28. data/docs/architecture/recovery-submission-custody.md +247 -0
  29. data/docs/architecture/retained-attempts.md +229 -0
  30. data/docs/architecture/retained-outcome-materialization.md +636 -0
  31. data/docs/architecture/retained-outcome-publication.md +506 -0
  32. data/docs/architecture/storage-execution-boundaries.md +1 -1
  33. data/docs/architecture/structured-output-and-scope.md +15 -0
  34. data/docs/architecture/synchronous-participant-application.md +397 -0
  35. data/docs/architecture/synchronous-participant-contract.md +195 -0
  36. data/docs/architecture/team-admission-rejection.md +91 -0
  37. data/docs/architecture/team-cancellation-delivery.md +245 -0
  38. data/docs/architecture/team-child-retirement.md +104 -0
  39. data/docs/architecture/tracing.md +26 -0
  40. data/docs/architecture/workflow-terminal-ownership-design.md +25 -9
  41. data/docs/architecture/workflow-terminal-reconciliation.md +221 -0
  42. data/docs/architecture.md +16 -9
  43. data/docs/decisions/025-process-local-agent-ownership-and-runtime-admission.md +8 -0
  44. data/docs/features.md +3 -3
  45. data/docs/mcp-client.md +138 -5
  46. data/docs/migrations/orchestrator-subagent-dispatch.md +89 -0
  47. data/docs/migrations/vector-async-clients.md +18 -3
  48. data/docs/persistence-backends.md +30 -4
  49. data/docs/runtime-and-concurrency.md +235 -11
  50. data/lib/phronomy/agent/admission.rb +37 -17
  51. data/lib/phronomy/agent/api/agent.rb +25 -0
  52. data/lib/phronomy/agent/approval_recovery.rb +30 -0
  53. data/lib/phronomy/agent/approval_recovery_api.rb +61 -0
  54. data/lib/phronomy/agent/approval_recovery_error.rb +39 -0
  55. data/lib/phronomy/agent/approval_recovery_result.rb +94 -0
  56. data/lib/phronomy/agent/async_event_api.rb +22 -5
  57. data/lib/phronomy/agent/base.rb +76 -48
  58. data/lib/phronomy/agent/context_preparation.rb +10 -8
  59. data/lib/phronomy/agent/dispatch_recovery.rb +29 -0
  60. data/lib/phronomy/agent/dispatch_recovery_api.rb +84 -0
  61. data/lib/phronomy/agent/dispatch_recovery_error.rb +36 -0
  62. data/lib/phronomy/agent/dispatch_recovery_result.rb +93 -0
  63. data/lib/phronomy/agent/execution/agent_invocation.rb +11 -3
  64. data/lib/phronomy/agent/execution/approval_continuation_plan.rb +131 -0
  65. data/lib/phronomy/agent/execution/approval_parent_evidence.rb +116 -0
  66. data/lib/phronomy/agent/execution/approval_persistence_evidence.rb +111 -0
  67. data/lib/phronomy/agent/execution/approval_recovery_operation.rb +496 -0
  68. data/lib/phronomy/agent/execution/approval_resume_commit.rb +174 -10
  69. data/lib/phronomy/agent/execution/dispatch_continuation_delivery.rb +96 -0
  70. data/lib/phronomy/agent/execution/dispatch_persistence_evidence.rb +147 -0
  71. data/lib/phronomy/agent/execution/dispatch_preparation.rb +63 -7
  72. data/lib/phronomy/agent/execution/dispatch_recovery_operation.rb +495 -0
  73. data/lib/phronomy/agent/execution/execution_coordinator.rb +724 -158
  74. data/lib/phronomy/agent/execution/execution_outcome_committer.rb +312 -39
  75. data/lib/phronomy/agent/execution/execution_registry.rb +508 -13
  76. data/lib/phronomy/agent/execution/initial_persistence_evidence.rb +269 -0
  77. data/lib/phronomy/agent/execution/initial_preparation.rb +132 -40
  78. data/lib/phronomy/agent/execution/initial_preparation_recovery_operation.rb +513 -0
  79. data/lib/phronomy/agent/execution/invocation_transitions.rb +3 -0
  80. data/lib/phronomy/agent/execution/outcome_planning.rb +108 -0
  81. data/lib/phronomy/agent/execution/outcome_preparation.rb +81 -0
  82. data/lib/phronomy/agent/execution/outcome_recovery_operation.rb +609 -0
  83. data/lib/phronomy/agent/execution/outcome_text_projection.rb +73 -0
  84. data/lib/phronomy/agent/execution/outcome_write_plan.rb +48 -0
  85. data/lib/phronomy/agent/execution/runtime_record_encoder.rb +7 -4
  86. data/lib/phronomy/agent/execution/terminal_persistence_evidence.rb +280 -0
  87. data/lib/phronomy/agent/execution/terminal_recovery_operation.rb +38 -0
  88. data/lib/phronomy/agent/execution_change.rb +138 -26
  89. data/lib/phronomy/agent/execution_environment.rb +29 -0
  90. data/lib/phronomy/agent/execution_rejected_error.rb +34 -0
  91. data/lib/phronomy/agent/initial_preparation_recovery.rb +32 -0
  92. data/lib/phronomy/agent/initial_preparation_recovery_api.rb +85 -0
  93. data/lib/phronomy/agent/initial_preparation_recovery_error.rb +41 -0
  94. data/lib/phronomy/agent/initial_preparation_recovery_result.rb +115 -0
  95. data/lib/phronomy/agent/lifecycle/hosted_approval_context.rb +86 -0
  96. data/lib/phronomy/agent/lifecycle/hosted_invocation.rb +42 -10
  97. data/lib/phronomy/agent/lifecycle/identity_write.rb +101 -0
  98. data/lib/phronomy/agent/lifecycle/lifetime_api.rb +28 -0
  99. data/lib/phronomy/agent/lifecycle/ownership_registry.rb +136 -70
  100. data/lib/phronomy/agent/lifecycle/scope.rb +3 -3
  101. data/lib/phronomy/agent/outcome_recovery.rb +47 -0
  102. data/lib/phronomy/agent/outcome_recovery_api.rb +114 -0
  103. data/lib/phronomy/agent/outcome_recovery_error.rb +36 -0
  104. data/lib/phronomy/agent/outcome_recovery_result.rb +92 -0
  105. data/lib/phronomy/agent/output_contract.rb +16 -6
  106. data/lib/phronomy/agent/persistence/identity_receipt_repository.rb +61 -0
  107. data/lib/phronomy/agent/persistence/records.rb +2 -0
  108. data/lib/phronomy/agent/persistence/storage_schema.rb +2 -0
  109. data/lib/phronomy/agent/recovery/invocation_restorer.rb +8 -5
  110. data/lib/phronomy/agent/recovery/recovery_coordinator/continuation.rb +6 -4
  111. data/lib/phronomy/agent/recovery/recovery_coordinator/installation.rb +21 -43
  112. data/lib/phronomy/agent/recovery/recovery_coordinator.rb +19 -6
  113. data/lib/phronomy/agent/runtime_binding/engine_environment.rb +12 -0
  114. data/lib/phronomy/agent/state_writer.rb +4 -3
  115. data/lib/phronomy/agent/store.rb +7 -1
  116. data/lib/phronomy/agent/terminal_recovery.rb +41 -0
  117. data/lib/phronomy/agent/terminal_recovery_api.rb +101 -0
  118. data/lib/phronomy/agent/terminal_recovery_error.rb +36 -0
  119. data/lib/phronomy/agent/terminal_recovery_result.rb +67 -0
  120. data/lib/phronomy/agent/tool_execution/tool_approval_request.rb +25 -1
  121. data/lib/phronomy/common/values/serializable.rb +37 -4
  122. data/lib/phronomy/engine/concurrency/offload_pool.rb +32 -4
  123. data/lib/phronomy/engine/concurrency/pool_registry.rb +6 -0
  124. data/lib/phronomy/engine/event_loop.rb +161 -11
  125. data/lib/phronomy/engine/execution_binding.rb +4 -2
  126. data/lib/phronomy/engine/execution_receiver_binding.rb +5 -0
  127. data/lib/phronomy/engine/runtime/shutdown_result.rb +21 -0
  128. data/lib/phronomy/engine/runtime/timer_queue.rb +7 -2
  129. data/lib/phronomy/engine/runtime.rb +119 -15
  130. data/lib/phronomy/execution/attempt_completion.rb +91 -0
  131. data/lib/phronomy/execution/concurrency/cancellation_token.rb +7 -2
  132. data/lib/phronomy/execution/concurrency/physical_completion_task.rb +7 -2
  133. data/lib/phronomy/execution/execution.rb +17 -2
  134. data/lib/phronomy/execution/execution_receiver.rb +27 -0
  135. data/lib/phronomy/execution/execution_retirement.rb +30 -0
  136. data/lib/phronomy/execution/invocation_controls.rb +2 -2
  137. data/lib/phronomy/execution/retained_attempts.rb +179 -0
  138. data/lib/phronomy/execution/stopped_terminal_custody.rb +99 -0
  139. data/lib/phronomy/llm_adapter/response.rb +7 -1
  140. data/lib/phronomy/multi_agent/admission_registry.rb +6 -0
  141. data/lib/phronomy/multi_agent/durable_subagent_coordinator.rb +175 -39
  142. data/lib/phronomy/multi_agent/handoff_dispatch_evidence.rb +176 -0
  143. data/lib/phronomy/multi_agent/handoff_finalization_error.rb +33 -0
  144. data/lib/phronomy/multi_agent/handoff_history_release.rb +80 -0
  145. data/lib/phronomy/multi_agent/handoff_participant.rb +31 -6
  146. data/lib/phronomy/multi_agent/handoff_runner.rb +195 -21
  147. data/lib/phronomy/multi_agent/handoff_terminal_finalization.rb +176 -0
  148. data/lib/phronomy/multi_agent/native_approval_evidence.rb +26 -0
  149. data/lib/phronomy/multi_agent/native_child_authority.rb +135 -0
  150. data/lib/phronomy/multi_agent/native_dispatch_evidence.rb +43 -0
  151. data/lib/phronomy/multi_agent/native_outcome_evidence.rb +46 -0
  152. data/lib/phronomy/multi_agent/native_persistence_plan.rb +93 -0
  153. data/lib/phronomy/multi_agent/orchestrator.rb +28 -52
  154. data/lib/phronomy/multi_agent/reserved_child_admission.rb +90 -1
  155. data/lib/phronomy/multi_agent/store.rb +5 -34
  156. data/lib/phronomy/multi_agent/subagent_history_release.rb +88 -0
  157. data/lib/phronomy/multi_agent/team_cancellation_delivery_error.rb +21 -0
  158. data/lib/phronomy/multi_agent/team_cancellation_request.rb +134 -0
  159. data/lib/phronomy/multi_agent/team_coordinator.rb +174 -27
  160. data/lib/phronomy/persistence_composition/stores.rb +10 -3
  161. data/lib/phronomy/runtime_composition/execution_defaults.rb +18 -0
  162. data/lib/phronomy/storage/backends/in_memory.rb +3 -1
  163. data/lib/phronomy/storage/resource.rb +10 -1
  164. data/lib/phronomy/tools/agent.rb +7 -1
  165. data/lib/phronomy/tools/mcp.rb +210 -91
  166. data/lib/phronomy/tools/mcp_http_close_response.rb +23 -0
  167. data/lib/phronomy/tools/mcp_transport_registry.rb +210 -0
  168. data/lib/phronomy/tools/vector_search.rb +28 -5
  169. data/lib/phronomy/tracing/automatic.rb +8 -1
  170. data/lib/phronomy/version.rb +1 -1
  171. data/lib/phronomy/workflow/execution/workflow.rb +34 -0
  172. data/lib/phronomy/workflow/execution/workflow_execution_environment.rb +1 -0
  173. data/lib/phronomy/workflow/execution/workflow_execution_registry.rb +106 -7
  174. data/lib/phronomy/workflow/execution/workflow_runner.rb +53 -108
  175. data/lib/phronomy/workflow/execution/workflow_terminal_operation.rb +489 -0
  176. data/lib/phronomy/workflow/execution/workflow_terminal_persistence.rb +81 -0
  177. data/lib/phronomy/workflow/execution/workflow_terminal_recovery.rb +38 -0
  178. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_error.rb +34 -0
  179. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_result.rb +56 -0
  180. data/lib/phronomy/workflow/runtime_binding/workflow_engine_environment.rb +10 -1
  181. data/lib/phronomy/workflow/runtime_binding/workflow_task_session.rb +3 -1
  182. data/lib/phronomy/workflow/runtime_binding/workflow_terminal_policy.rb +2 -1
  183. data/scripts/api_snapshot.rb +46 -1
  184. data/sig/_private/phronomy/multi_agent/team_cancellation_request.rbs +19 -0
  185. data/sig/phronomy/agent/approval_recovery.rbs +54 -0
  186. data/sig/phronomy/agent/dispatch_recovery.rbs +49 -0
  187. data/sig/phronomy/agent/execution_contract.rbs +4 -1
  188. data/sig/phronomy/agent/execution_environment.rbs +2 -0
  189. data/sig/phronomy/agent/initial_preparation_recovery.rbs +48 -0
  190. data/sig/phronomy/agent/outcome_recovery.rbs +51 -0
  191. data/sig/phronomy/agent/store.rbs +1 -0
  192. data/sig/phronomy/agent/terminal_persistence_evidence.rbs +111 -0
  193. data/sig/phronomy/agent/terminal_recovery.rbs +46 -0
  194. data/sig/phronomy/agent.rbs +36 -0
  195. data/sig/phronomy/engine/concurrency/timer_bindings.rbs +2 -0
  196. data/sig/phronomy/engine/execution_binding.rbs +2 -1
  197. data/sig/phronomy/engine/execution_receiver.rbs +4 -0
  198. data/sig/phronomy/engine/observability.rbs +22 -1
  199. data/sig/phronomy/execution/execution.rbs +16 -1
  200. data/sig/phronomy/execution/execution_receiver.rbs +12 -0
  201. data/sig/phronomy/execution/execution_retirement.rbs +18 -0
  202. data/sig/phronomy/execution/stopped_terminal_custody.rbs +19 -0
  203. data/sig/phronomy/handoff.rbs +1 -0
  204. data/sig/phronomy/multi_agent/handoff_finalization_error.rbs +18 -0
  205. data/sig/phronomy/multi_agent/store.rbs +1 -1
  206. data/sig/phronomy/multi_agent/team_cancellation_delivery_error.rbs +9 -0
  207. data/sig/phronomy/persistence_composition.rbs +2 -1
  208. data/sig/phronomy/storage/contracts.rbs +2 -1
  209. data/sig/phronomy/tools/mcp.rbs +27 -0
  210. data/sig/phronomy/workflow.rbs +42 -0
  211. metadata +104 -2
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "weakref"
4
+
5
+ module Phronomy
6
+ module Agent
7
+ # Captures the original hosted parent's authority before a child decision
8
+ # is submitted. Saved evidence is immutable; later handles use only the same
9
+ # live owners and never reconstruct authority from diagnostic identities.
10
+ # @api private
11
+ class HostedApprovalContext
12
+ attr_reader :parent_evidence
13
+
14
+ def initialize(parent:, child:, parent_wait:, parent_evidence:, reader:)
15
+ @parent_reference = WeakRef.new(parent)
16
+ @child_reference = WeakRef.new(child)
17
+ @parent_wait_reference = WeakRef.new(parent_wait)
18
+ @parent_agent_id = parent.agent_id.to_s.dup.freeze
19
+ @parent_execution_id = parent_wait.execution_id.to_s.dup.freeze
20
+ @parent_revision = parent_wait.revision
21
+ @child_agent_id = child.agent_id.to_s.dup.freeze
22
+ @parent_evidence = parent_evidence
23
+ @wait = parent_evidence.wait
24
+ @reader = reader
25
+ @mutex = Mutex.new
26
+ @released = false
27
+ end
28
+
29
+ # Only the canonical continuation's physical end (or restored pre-state)
30
+ # retires this authority. A failed original observer cannot release it.
31
+ def release!
32
+ @mutex.synchronize do
33
+ @released = true
34
+ @reader = @parent_evidence = nil
35
+ @parent_reference = @child_reference = @parent_wait_reference = nil
36
+ end
37
+ end
38
+
39
+ # EventLoop application checks only local ownership. Guarded Store reads
40
+ # are performed separately by the approval persistence worker.
41
+ def validate_live!
42
+ parent, child, parent_wait, = live_owners
43
+ environment = parent.__execution_environment
44
+ owner = environment.registry.agent_execution_owner(@wait.execution_id)
45
+ unless parent_wait.current? && parent_wait.execution_id == @parent_execution_id &&
46
+ parent.agent_id == @parent_agent_id && child.agent_id == @child_agent_id &&
47
+ child.__execution_environment.registry.equal?(environment.registry) &&
48
+ owner&.agent.equal?(child)
49
+ raise Phronomy::AgentBusyError, "Original hosted approval authority is no longer current"
50
+ end
51
+ true
52
+ rescue WeakRef::RefError
53
+ raise Phronomy::AgentBusyError, "Original hosted approval owner is no longer available"
54
+ end
55
+
56
+ # The observation may close independently. Only the exact canonical task
57
+ # carries the decision's right to detach a later approval wait.
58
+ def build_invocation(observation:, detach_task:)
59
+ parent_reference = @mutex.synchronize { @parent_reference unless @released }
60
+ return unless parent_reference
61
+ parent = parent_reference.__getobj__
62
+ HostedInvocation.new(parent, @parent_execution_id, observation,
63
+ resumed_from: @wait, detach_task: detach_task) do |execution_id, approval_id|
64
+ validate_live!
65
+ _, child, _, reader = live_owners
66
+ reader.call(@parent_agent_id, @parent_execution_id, execution_id, approval_id,
67
+ parent_revision: @parent_revision, live_child: child)
68
+ end
69
+ rescue WeakRef::RefError
70
+ # A historical recovery receipt still observes execution after its host
71
+ # has disappeared. It cannot issue a replacement detach capability.
72
+ nil
73
+ end
74
+
75
+ private
76
+
77
+ def live_owners
78
+ @mutex.synchronize do
79
+ raise Phronomy::AgentBusyError, "Hosted approval authority has finished" if @released
80
+ [@parent_reference.__getobj__, @child_reference.__getobj__,
81
+ @parent_wait_reference.__getobj__, @reader]
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -5,11 +5,16 @@ module Phronomy
5
5
  # An opt-in host handle. wait_result yields the ordinary terminal result or
6
6
  # an ApprovalWait when the hosted operation itself is detached.
7
7
  class HostedInvocation
8
- def initialize(agent, execution_id, task, resumed_from: nil, &child_approval_wait)
8
+ def initialize(agent, execution_id, task, resumed_from: nil, detach_task: task, &child_approval_wait)
9
9
  @agent, @execution_id, @task = agent, execution_id, task
10
+ @detach_task = detach_task
10
11
  @environment = agent.__execution_environment
11
12
  @resumed_from = resumed_from
12
13
  @child_approval_wait = child_approval_wait
14
+ @authority_mutex = Mutex.new
15
+ if resumed_from && detach_task.respond_to?(:on_physical_complete)
16
+ observe_detach_completion(detach_task)
17
+ end
13
18
  end
14
19
 
15
20
  def wait_result(timeout: nil) = @task.wait_result(timeout: timeout)
@@ -24,33 +29,60 @@ module Phronomy
24
29
  if Phronomy::WaitPolicy.blocking_forbidden?
25
30
  raise Phronomy::EventLoopReentrancyError, "detach! requires a host thread"
26
31
  end
32
+ agent, environment, detach_task, reader = detach_authority
27
33
  child = execution_id != @execution_id
28
34
  wait = if @resumed_from
29
35
  if execution_id == @resumed_from.execution_id && approval_request_id != @resumed_from.approval_request_id
30
- @child_approval_wait.call(execution_id, approval_request_id)
36
+ reader.call(execution_id, approval_request_id)
31
37
  end
32
38
  elsif child
33
- matching_child_wait(execution_id, approval_request_id)
39
+ matching_child_wait(execution_id, approval_request_id, reader: reader)
34
40
  else
35
- @agent.persistence.standalone_approval_wait(agent_id: @agent.agent_id, execution_id: @execution_id)
41
+ agent.persistence.standalone_approval_wait(agent_id: agent.agent_id, execution_id: @execution_id)
36
42
  end
37
43
  unless wait && wait.approval_request_id == approval_request_id
38
44
  raise Phronomy::AgentBusyError, "No matching hosted approval wait"
39
45
  end
40
- owner = @environment.registry.agent_execution_owner(execution_id)
41
- unless owner && (child ? owner.agent.persistence.equal?(@agent.persistence) : owner.agent.equal?(@agent))
46
+ owner = environment.registry.agent_execution_owner(execution_id)
47
+ unless owner && (child ? owner.agent.persistence.equal?(agent.persistence) : owner.agent.equal?(agent))
42
48
  raise Phronomy::AgentBusyError, "Hosted execution has no matching local owner"
43
49
  end
44
50
  completion = owner.coordinator.request_hosted_detach(wait,
45
- task: (child && !@resumed_from) ? nil : @task, parent: child ? @agent : nil)
51
+ task: (child && !@resumed_from) ? nil : detach_task, parent: child ? agent : nil)
46
52
  completion.wait_result
47
53
  end
48
54
 
49
55
  private
50
56
 
51
- def matching_child_wait(execution_id, approval_request_id)
57
+ def observe_detach_completion(task)
58
+ task.on_physical_complete do
59
+ continuation = task.respond_to?(:hosted_detach_task, true) ? task.send(:hosted_detach_task) : task
60
+ if continuation.equal?(task)
61
+ retire_detach_authority
62
+ else
63
+ # A still-open ordinary handle follows its exact lease handoff.
64
+ # This affects cleanup only; EventLoop rechecks detach authority.
65
+ observe_detach_completion(continuation)
66
+ end
67
+ end
68
+ end
69
+
70
+ def retire_detach_authority
71
+ @authority_mutex.synchronize do
72
+ @agent = @environment = @detach_task = @child_approval_wait = nil
73
+ end
74
+ end
75
+
76
+ def detach_authority
77
+ @authority_mutex.synchronize do
78
+ raise Phronomy::AgentBusyError, "Hosted continuation has physically finished" unless @agent
79
+ [@agent, @environment, @detach_task, @child_approval_wait]
80
+ end
81
+ end
82
+
83
+ def matching_child_wait(execution_id, approval_request_id, reader:)
52
84
  settled = @task.done?
53
- wait = @child_approval_wait&.call(execution_id, approval_request_id)
85
+ wait = reader&.call(execution_id, approval_request_id)
54
86
  return unless wait
55
87
 
56
88
  # The child's event can precede the parent's committed coordination
@@ -60,7 +92,7 @@ module Phronomy
60
92
  @task.wait_result # Propagate a parent failure other than a committed wait.
61
93
  raise Phronomy::AgentBusyError, "Hosted parent did not reach its coordination wait"
62
94
  end
63
- wait if settled || @child_approval_wait.call(execution_id, approval_request_id) == wait
95
+ wait if settled || reader.call(execution_id, approval_request_id) == wait
64
96
  end
65
97
  end
66
98
  end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Phronomy
6
+ module Agent
7
+ # Evidence from the exact synchronous Store transaction changing an Agent ID.
8
+ # The caller retains the local reservation while this transaction settles.
9
+ # @api private
10
+ class IdentityWrite
11
+ def self.supported?(store)
12
+ store.respond_to?(:identity_receipts?) && store.identity_receipts?
13
+ end
14
+
15
+ def initialize(agent_id:, kind:, agent_class:, generation: nil)
16
+ @agent_id, @kind, @agent_class = agent_id, kind, agent_class
17
+ @generation = generation
18
+ end
19
+
20
+ def perform(persistence)
21
+ @store = persistence
22
+ receipts = self.class.supported?(persistence)
23
+ persistence.transaction do |records, scope|
24
+ @scope = scope
25
+ prepare_receipt(records) if receipts && scope
26
+ @value = yield records
27
+ record_receipt(records) if @after_receipt
28
+ @prepared = true
29
+ @value
30
+ end
31
+ rescue
32
+ @disposition = observe if !committed? && reconcilable?
33
+ raise unless committed?
34
+ @value
35
+ end
36
+
37
+ def prepared? = @prepared
38
+
39
+ def committed? = @disposition == :committed || (prepared? && @scope&.outermost? && @scope.committed?)
40
+ def rolled_back? = @disposition == :not_committed
41
+ def reconcilable? = prepared? && @scope&.outermost? && !@after_receipt.nil?
42
+ def generation = @after_receipt&.operation_id
43
+
44
+ def matches?(store, expected_class)
45
+ @store.equal?(store) && @agent_class == expected_class
46
+ end
47
+
48
+ def retain_observation
49
+ return unless reconcilable?
50
+ @scope = @value = nil
51
+ self
52
+ end
53
+
54
+ def observe
55
+ observed = nil
56
+ proof = Phronomy::Persistence::SaveOutcome.compare(before: @before, after: @after) do
57
+ observed = @store.transaction do |records, scope|
58
+ unless scope.outermost?
59
+ raise Phronomy::Persistence::TransactionError, "Agent identity evidence requires a fresh outer Store transaction"
60
+ end
61
+ receipts = records.identity_receipts
62
+ receipts.guard!(@agent_id)
63
+ [receipts.read(@agent_id), read_root(records)]
64
+ end
65
+ end
66
+ return :superseded if proof.disposition == :unknown && observed && superseded?(observed)
67
+ proof.disposition
68
+ end
69
+
70
+ private
71
+
72
+ def superseded?(observed)
73
+ receipt, root = observed
74
+ receipt && receipt.revision >= @after_receipt.revision &&
75
+ receipt.operation_id != @after_receipt.operation_id && (receipt.kind == :create) == !root.nil?
76
+ end
77
+
78
+ def prepare_receipt(records)
79
+ receipts = records.identity_receipts
80
+ receipts.guard!(@agent_id)
81
+ before = receipts.read(@agent_id)
82
+ if @kind == :purge && before&.operation_id != @generation
83
+ raise Phronomy::Persistence::ConflictError, "Agent identity changed before purge"
84
+ end
85
+ @before = [before, ((@kind == :purge) ? read_root(records) : nil)].freeze
86
+ @after_receipt = receipts.next_receipt(before: before, operation_id: SecureRandom.uuid.freeze, kind: @kind)
87
+ end
88
+
89
+ def record_receipt(records)
90
+ @after = [@after_receipt, ((@kind == :create) ? @value.root.to_h : nil)].freeze
91
+ records.identity_receipts.write(@agent_id, before: @before.first, after: @after_receipt)
92
+ end
93
+
94
+ def read_root(records)
95
+ records.agents.load(@agent_id).to_h
96
+ rescue Phronomy::Persistence::NotFoundError
97
+ nil
98
+ end
99
+ end
100
+ end
101
+ end
@@ -29,6 +29,34 @@ module Phronomy
29
29
 
30
30
  private
31
31
 
32
+ # Observes recorded local mutation custody after earlier serial delivery.
33
+ # False proves neither durable completion nor global physical quiescence.
34
+ # Call only outside persistence transactions and domain/lifecycle locks.
35
+ # @api private
36
+ def __execution_custody_pending?(execution_id)
37
+ unless execution_id.is_a?(String) && !execution_id.empty?
38
+ raise ArgumentError, "execution_id must be a nonempty String"
39
+ end
40
+ if Phronomy::WaitPolicy.blocking_forbidden?
41
+ raise Phronomy::EventLoopReentrancyError, "Agent custody observation cannot block EventLoop"
42
+ end
43
+ __assert_live_agent!
44
+ unless @_phronomy_runtime_owner_state == :live
45
+ raise Phronomy::RuntimeShutdownError, "Agent custody observation requires its live incarnation"
46
+ end
47
+ environment = __execution_environment
48
+ environment.assert_custody_query_available!
49
+ __with_operation do
50
+ environment.assert_custody_query_available!
51
+ registry = environment.existing_registry
52
+ pending = registry ? registry.observe_execution_custody(
53
+ agent_id: agent_id, execution_id: execution_id, environment: environment
54
+ ).wait_result : false
55
+ environment.assert_custody_query_available!
56
+ pending
57
+ end
58
+ end
59
+
32
60
  # The participant proves which durable retentions are finished history;
33
61
  # Agent controls admission, idleness and release of the local owners.
34
62
  def __unload_with_peer_execution!(execution_id, reserved_by:)
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "identity_write"
4
+
3
5
  module Phronomy
4
6
  module Agent
5
7
  # Process-local authoritative owner registry for mutable Agent instances.
@@ -32,38 +34,39 @@ module Phronomy
32
34
 
33
35
  def create(agent_id, expected_class:, scope_owner: nil)
34
36
  key = normalize_agent_id(agent_id)
35
- token = reserve_create!(key, scope_owner: scope_owner)
36
-
37
- begin
38
- agent = yield(@environment)
39
- rescue Phronomy::AgentAlreadyExistsError,
40
- Phronomy::Persistence::ConflictError,
41
- Phronomy::Persistence::NotFoundError,
42
- Phronomy::Persistence::SerializationError,
43
- ArgumentError,
44
- Phronomy::ConfigurationError
45
- release_construction!(key, token)
46
- raise
47
- rescue
48
- # A generic backend/transport failure can be an indeterminate commit.
49
- # Do not make the same identity creatable again until recovery proves
50
- # which durable lineage exists.
51
- fail_construction_closed!(key, token)
52
- raise
37
+ Thread.handle_interrupt(Object => :never) do
38
+ token = reserve_create!(key, scope_owner: scope_owner)
39
+ write = IdentityWrite.new(agent_id: key, kind: :create, agent_class: expected_class)
40
+ begin
41
+ agent = Thread.handle_interrupt(Object => :immediate) { yield(@environment, write) }
42
+ rescue Phronomy::AgentAlreadyExistsError,
43
+ Phronomy::Persistence::ConflictError,
44
+ Phronomy::Persistence::NotFoundError,
45
+ Phronomy::Persistence::SerializationError,
46
+ ArgumentError,
47
+ Phronomy::ConfigurationError
48
+ release_construction!(key, token) unless write.prepared?
49
+ raise
50
+ else
51
+ published = publish_constructed!(key, token, agent, expected_class)
52
+ ensure
53
+ unless published
54
+ # An interrupted constructor cannot publish its incomplete receiver.
55
+ # A confirmed root can be hydrated later through ordinary load.
56
+ if write.committed? || write.rolled_back?
57
+ release_construction!(key, token)
58
+ else
59
+ fail_construction_closed!(key, token, agent: agent, write: write)
60
+ end
61
+ end
62
+ end
53
63
  end
54
-
55
- publish_constructed!(
56
- key,
57
- token,
58
- agent,
59
- expected_class,
60
- fail_closed: true
61
- )
62
64
  end
63
65
 
64
66
  def load(agent_id, expected_class:, scope_owner: nil)
65
67
  key = normalize_agent_id(agent_id)
66
68
  token = nil
69
+ installing = nil
67
70
 
68
71
  loop do
69
72
  existing = @mutex.synchronize do
@@ -80,7 +83,7 @@ module Phronomy
80
83
  when :constructing, :purging
81
84
  @condition.wait(@mutex)
82
85
  :retry
83
- when :recovery_required
86
+ when :recovery_required, :reconciling_identity
84
87
  raise ownership_recovery_error(key)
85
88
  when nil
86
89
  token = Object.new.freeze
@@ -100,20 +103,19 @@ module Phronomy
100
103
  break
101
104
  end
102
105
 
103
- begin
104
- agent = yield(@environment)
105
- publish_constructed!(
106
- key,
107
- token,
108
- agent,
109
- expected_class,
110
- fail_closed: false
111
- )
112
- rescue
113
- # Hydration is read-only. A failed load does not establish a new
114
- # durable Agent lineage, so the reservation can safely be released.
115
- release_construction!(key, token)
116
- raise
106
+ agent = yield(@environment, ->(owner) { installing = owner })
107
+ published = Thread.handle_interrupt(Object => :never) { publish_constructed!(key, token, agent, expected_class) }
108
+ ensure
109
+ if token && !published
110
+ Thread.handle_interrupt(Object => :never) do
111
+ # Pure hydration has no pending command. Once recovery may have
112
+ # reached the dispatcher, only its exact incarnation owns that work.
113
+ if installing
114
+ fail_construction_closed!(key, token, agent: installing)
115
+ else
116
+ release_construction!(key, token)
117
+ end
118
+ end
117
119
  end
118
120
  end
119
121
 
@@ -124,7 +126,7 @@ module Phronomy
124
126
  case entry&.state
125
127
  when :live
126
128
  entry.agent
127
- when :recovery_required
129
+ when :recovery_required, :reconciling_identity
128
130
  raise ownership_recovery_error(key)
129
131
  # :nocov:
130
132
  when :purging, :unloading
@@ -137,12 +139,33 @@ module Phronomy
137
139
  validate_expected_class!(agent, expected_class, key)
138
140
  end
139
141
 
142
+ def reconcile_identity(agent_id, expected_class:, persistence:)
143
+ key = normalize_agent_id(agent_id)
144
+ Thread.handle_interrupt(Object => :never) do
145
+ entry = @mutex.synchronize do
146
+ ensure_running!
147
+ current = @entries[key]
148
+ raise ownership_recovery_error(key) if current&.state == :reconciling_identity
149
+ return unless current&.state == :recovery_required && current.token
150
+ unless current.token.matches?(persistence, expected_class)
151
+ raise ArgumentError, "Agent identity reconciliation requires the original class and Store"
152
+ end
153
+ @entries[key] = current.with(state: :reconciling_identity)
154
+ end
155
+ begin
156
+ result = Thread.handle_interrupt(Object => :immediate) { entry.token.observe }
157
+ ensure
158
+ finish_identity_reconciliation(key, entry, result)
159
+ end
160
+ end
161
+ end
162
+
140
163
  # Admission and lifetime transitions share this mutex. No Runtime or Store
141
164
  # operation is called while it is held.
142
165
  def acquire_operation(agent, read_only: false, wait_on_shutdown: true)
143
166
  token = Object.new.freeze
144
167
  @mutex.synchronize do
145
- ensure_running! unless read_only && @state == :draining
168
+ ensure_running! unless read_only && @state == :draining && !@stopped_admission_closed
146
169
  entry = @entries[agent.agent_id]
147
170
  if entry&.agent&.equal?(agent) && entry.state == :unloading
148
171
  raise Phronomy::AgentBusyError, "Agent #{agent.agent_id.inspect} is unloading"
@@ -150,7 +173,7 @@ module Phronomy
150
173
  unless entry&.state == :live && entry.agent.equal?(agent)
151
174
  raise Phronomy::RuntimeShutdownError, "Agent is no longer the live Runtime owner"
152
175
  end
153
- (@operations[agent] ||= {})[token] = wait_on_shutdown
176
+ (@operations[agent] ||= {})[token] = wait_on_shutdown || read_only
154
177
  end
155
178
  OperationLease.new(self, agent, token)
156
179
  end
@@ -249,16 +272,24 @@ module Phronomy
249
272
  # is then stable until the caller's durable checks commit or roll back.
250
273
  def unload_idle_pair(parent, peer_id)
251
274
  raise Phronomy::AgentBusyError, "Expected distinct Agent identities" if parent.agent_id == peer_id
275
+ with_idle_owners(parent, [parent.agent_id, peer_id], unload: true) do |owners|
276
+ yield owners[peer_id]
277
+ true
278
+ end
279
+ end
280
+
281
+ # Reserve every identity across the durable operation, including unloaded
282
+ # identities. The mutex protects only reservation and restoration.
283
+ def with_idle_owners(anchor, ids, unload: false)
252
284
  transition = Object.new.freeze
253
- # A host thread may exit during verification. Keep the short two-owner
254
- # registry changes indivisible even in the presence of an async interrupt.
255
285
  Thread.handle_interrupt(Object => :never) do
256
- owners = reserve_idle_pair!(parent, peer_id, transition)
286
+ owners = reserve_idle_owners!(anchor, ids, transition)
257
287
  begin
258
- Thread.handle_interrupt(Object => :immediate) { yield owners[peer_id] }
288
+ result = Thread.handle_interrupt(Object => :immediate) { yield owners }
259
289
  success = true
290
+ result
260
291
  ensure
261
- finish_unload_entries(owners, transition, success: success)
292
+ finish_unload_entries(owners, transition, success: unload && success)
262
293
  end
263
294
  end
264
295
  end
@@ -327,7 +358,7 @@ module Phronomy
327
358
  # Unknown durable outcome is fail-closed, but it must not leave load/shutdown
328
359
  # waiters blocked forever. Convert the transition into an explicit stable
329
360
  # recovery-required state and wake all waiters.
330
- def leave_purge_uncertain(agent, token)
361
+ def leave_purge_uncertain(agent, token, write: nil)
331
362
  key = normalize_agent_id(agent.agent_id)
332
363
  @mutex.synchronize do
333
364
  validate_purge_entry!(@entries[key], agent, token, key)
@@ -335,7 +366,7 @@ module Phronomy
335
366
  @entries[key] = Entry.new(
336
367
  state: :recovery_required,
337
368
  agent: agent,
338
- token: nil
369
+ token: write&.retain_observation
339
370
  )
340
371
  @condition.broadcast
341
372
  end
@@ -359,7 +390,7 @@ module Phronomy
359
390
  def wait_until_idle(deadline)
360
391
  @mutex.synchronize do
361
392
  while @operations.values.any? { |operations| operations.value?(true) } || @entries.values.any? { |entry|
362
- %i[constructing purging unloading].include?(entry.state) ||
393
+ %i[constructing purging unloading reconciling_identity].include?(entry.state) ||
363
394
  (entry.state == :live && entry.token == :pending_unload)
364
395
  }
365
396
  remaining = deadline - monotonic_now
@@ -372,6 +403,28 @@ module Phronomy
372
403
  end
373
404
  end
374
405
 
406
+ # Reads admitted during drain may finish. No new read may slip between a
407
+ # positive stopped observation and a deferred finalizer detaching owners.
408
+ def close_stopped_admission(deferred:)
409
+ @mutex.synchronize do
410
+ return false unless @state == :draining
411
+ # Normal drain already verified the execution receiver, pools and
412
+ # timers. A passive observer of a durable wait carries no local write.
413
+ busy = deferred ? !@operations.empty? : @operations.values.any? { |leases| leases.value?(true) }
414
+ return false if busy
415
+ @stopped_admission_closed = true
416
+ end
417
+ end
418
+
419
+ # Independent stopped observation. A retained construction or live scope
420
+ # needs its own resolution; ordinary quiescent Agent objects may detach.
421
+ def shutdown_cleanup_ready?
422
+ @mutex.synchronize do
423
+ @state == :draining && @operations.empty? && @scope_owners.empty? &&
424
+ @entries.values.all? { |entry| entry.state == :live && entry.token.nil? }
425
+ end
426
+ end
427
+
375
428
  def after_runtime_shutdown
376
429
  agents = @mutex.synchronize do
377
430
  @state = :terminated
@@ -388,16 +441,38 @@ module Phronomy
388
441
 
389
442
  private
390
443
 
391
- def reserve_idle_pair!(parent, peer_id, transition)
444
+ def finish_identity_reconciliation(key, entry, result)
445
+ @mutex.synchronize do
446
+ case result
447
+ when :committed, :superseded
448
+ entry.agent&.send(:__mark_purged!, @environment)
449
+ @entries.delete(key)
450
+ @scope_owners.delete(key)
451
+ when :not_committed
452
+ if entry.agent
453
+ entry.agent.send(:__restore_live_after_purge_abort!, @environment)
454
+ @entries[key] = entry.with(state: :live, token: nil)
455
+ else
456
+ @entries.delete(key)
457
+ @scope_owners.delete(key)
458
+ end
459
+ else
460
+ @entries[key] = entry.with(state: :recovery_required)
461
+ end
462
+ @condition.broadcast
463
+ end
464
+ end
465
+
466
+ def reserve_idle_owners!(anchor, ids, transition)
392
467
  @mutex.synchronize do
393
468
  ensure_running!
394
- owners = {parent.agent_id => parent, peer_id => @entries[peer_id]&.agent}
469
+ owners = ids.to_h { |id| [id, (anchor && id == anchor.agent_id) ? anchor : @entries[id]&.agent] }
395
470
  owners.each do |id, agent|
396
471
  entry = @entries[id]
397
472
  raise Phronomy::AgentBusyError, "Agent belongs to a scope" if @scope_owners[id]
398
473
  next if entry.nil? && agent.nil?
399
- unless entry&.state == :live && entry.agent.equal?(agent)
400
- raise Phronomy::AgentBusyError, "Local Agent owner changed"
474
+ unless entry&.state == :live && entry.agent.equal?(agent) && entry.token.nil?
475
+ raise Phronomy::AgentBusyError, "Local Agent owner changed or has a pending release"
401
476
  end
402
477
  assert_no_operations!(agent)
403
478
  end
@@ -433,7 +508,7 @@ module Phronomy
433
508
  @mutex.synchronize do
434
509
  ensure_running!
435
510
  if (entry = @entries[key])
436
- raise ownership_recovery_error(key) if entry.state == :recovery_required
511
+ raise ownership_recovery_error(key) if %i[recovery_required reconciling_identity].include?(entry.state)
437
512
 
438
513
  if scope_owner
439
514
  raise Phronomy::AgentBusyError, "Agent #{key.inspect} already has a Runtime owner"
@@ -448,7 +523,7 @@ module Phronomy
448
523
  token
449
524
  end
450
525
 
451
- def publish_constructed!(key, token, agent, expected_class, fail_closed:)
526
+ def publish_constructed!(key, token, agent, expected_class)
452
527
  validate_expected_class!(agent, expected_class, key)
453
528
  unless agent.agent_id.to_s == key
454
529
  raise Phronomy::Error,
@@ -466,16 +541,6 @@ module Phronomy
466
541
  @condition.broadcast
467
542
  end
468
543
  agent
469
- rescue
470
- # :nocov:
471
- if fail_closed
472
- fail_construction_closed!(key, token, agent: agent)
473
- agent&.send(:__mark_ownership_recovery_required!, @environment)
474
- else
475
- release_construction!(key, token)
476
- end
477
- # :cover:
478
- raise
479
544
  end
480
545
 
481
546
  def release_construction!(key, token)
@@ -491,7 +556,7 @@ module Phronomy
491
556
  end
492
557
  end
493
558
 
494
- def fail_construction_closed!(key, token, agent: nil)
559
+ def fail_construction_closed!(key, token, agent: nil, write: nil)
495
560
  @mutex.synchronize do
496
561
  entry = @entries[key]
497
562
  # :nocov:
@@ -501,9 +566,10 @@ module Phronomy
501
566
  @entries[key] = Entry.new(
502
567
  state: :recovery_required,
503
568
  agent: agent,
504
- token: nil
569
+ token: write&.retain_observation
505
570
  )
506
571
  @condition.broadcast
572
+ agent&.send(:__mark_ownership_recovery_required!, @environment)
507
573
  end
508
574
  end
509
575