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
@@ -36,6 +36,7 @@ module Phronomy
36
36
  @session_receivers = {}
37
37
  @dispatching_delivery = nil
38
38
  @receiver_shutdown_error = nil
39
+ @unaccepted_retirements = {}
39
40
  @fsms = {}
40
41
  @waiting = {}
41
42
  @admitted_fsm_session_ids = Set.new
@@ -46,6 +47,7 @@ module Phronomy
46
47
  @state = :running
47
48
  @outstanding_sessions = 0
48
49
  @shutdown_status = nil
50
+ @abort_error = nil
49
51
 
50
52
  @lag_mutex = Mutex.new
51
53
  @last_lag_ns = 0
@@ -163,7 +165,42 @@ module Phronomy
163
165
 
164
166
  # @api private
165
167
  def __receiver_cleanup_complete?
166
- @receiver_shutdown_error.nil?
168
+ @lifecycle_mutex.synchronize do
169
+ @receiver_shutdown_error.nil? && @unaccepted_retirements.empty?
170
+ end
171
+ end
172
+
173
+ # A joined original dispatcher cannot deliver more commands. Pool shutdown
174
+ # and domain-specific attempt completion are independent requirements.
175
+ # @api private
176
+ def __stopped_workers_quiescent?
177
+ !thread_alive? && @lifecycle_mutex.synchronize { @receivers_stopped == true } &&
178
+ @runtime.__stopped_workers_quiescent?
179
+ end
180
+
181
+ # Dispose only the stopped session retained for this exact receiver and
182
+ # operation. Its owner accepts the independent durable disposition before
183
+ # the dispatcher drops its matching record. The block performs no I/O.
184
+ # @api private
185
+ def __transfer_stopped_session(receiver, session_id, operation)
186
+ @lifecycle_mutex.synchronize do
187
+ entry = @stopped_session_owners&.fetch(session_id, nil)
188
+ if entry && (!entry.first.equal?(receiver) || !entry.last.equal?(operation))
189
+ raise Phronomy::Error, "stopped session belongs to another terminal operation"
190
+ end
191
+ yield !entry.nil?
192
+ @stopped_session_owners.delete(session_id) if entry
193
+ end
194
+ end
195
+
196
+ # Receivers affirm their stopped custody under this same lifecycle lock.
197
+ # @api private
198
+ def __stopped_cleanup_verified?
199
+ @lifecycle_mutex.synchronize do
200
+ !thread_alive? && @receivers_stopped && @receiver_shutdown_error.nil? && !@abandoned_transport &&
201
+ !@stopped_session_owners&.any? && runtime_idle_locked? &&
202
+ @execution_receivers.values.all?(&:stopped_cleanup_ready_locked?)
203
+ end
167
204
  end
168
205
 
169
206
  def register(fsm_session, completion: nil, receiver: nil)
@@ -183,7 +220,8 @@ module Phronomy
183
220
 
184
221
  @lifecycle_mutex.synchronize do
185
222
  ensure_accepting_registrations!
186
- if @admitted_fsm_session_ids.include?(fsm_session.id)
223
+ if @admitted_fsm_session_ids.include?(fsm_session.id) ||
224
+ @session_receivers.key?(fsm_session.id) || @unaccepted_retirements.key?(fsm_session.id)
187
225
  raise Phronomy::Error,
188
226
  "FSMSession #{fsm_session.id.inspect} is already registered"
189
227
  end
@@ -334,7 +372,15 @@ module Phronomy
334
372
  join_until(deadline)
335
373
 
336
374
  @shutdown_status = if thread_alive?
337
- @lifecycle_mutex.synchronize { @state = :failed }
375
+ @lifecycle_mutex.synchronize do
376
+ @state = :failed
377
+ @abort_error = Phronomy::RuntimeShutdownError.new(
378
+ "EventLoop drain deadline expired; retained work requires recovery"
379
+ )
380
+ # Cooperative stop: an executing callback is never interrupted.
381
+ # Once it returns, the owner retires queued/live transport work.
382
+ @queue.push(STOP)
383
+ end
338
384
  :cancel_timeout
339
385
  elsif state == :failed
340
386
  :failed
@@ -375,6 +421,8 @@ module Phronomy
375
421
 
376
422
  def run_loop
377
423
  loop do
424
+ break if @abort_error
425
+
378
426
  fire_due_timers
379
427
  timeout = @runtime.__timer_queue.seconds_until_next
380
428
  item = dequeue(timeout: timeout)
@@ -391,7 +439,11 @@ module Phronomy
391
439
  dispatch(event)
392
440
  check_dispatch_time(dispatch_start_ns, event)
393
441
  end
394
- fire_due_timers
442
+ if @abort_error
443
+ cleanup_abandoned_work(@abort_error)
444
+ else
445
+ fire_due_timers
446
+ end
395
447
  rescue => error
396
448
  notify_unexpected_dispatcher_failure(error)
397
449
  raise
@@ -424,6 +476,9 @@ module Phronomy
424
476
  case event.type
425
477
  when :finished, :halted, :error
426
478
  fsm_session_id = event.payload.fetch(:fsm_session_id)
479
+ # A late terminal message cannot bypass a refused custody transfer.
480
+ return if @unaccepted_retirements.key?(fsm_session_id)
481
+
427
482
  session = @fsms.delete(fsm_session_id)
428
483
  waiter = @waiting.delete(fsm_session_id)
429
484
  decrement_outstanding if session
@@ -438,11 +493,71 @@ module Phronomy
438
493
  when :execution_control
439
494
  dispatch_execution(event.payload)
440
495
  when :recovery_required
441
- fsm_session_id = event.payload.fetch(:fsm_session_id)
442
- session = @fsms.delete(fsm_session_id)
496
+ retire_execution(event.payload)
497
+ end
498
+ end
499
+
500
+ def retire_execution(payload)
501
+ fsm_session_id = payload.fetch(:fsm_session_id)
502
+ pending = @unaccepted_retirements[fsm_session_id]
503
+ session = @fsms.delete(fsm_session_id)
504
+ return unless session || pending
505
+
506
+ receiver = pending ? pending.fetch(:receiver) :
507
+ @lifecycle_mutex.synchronize { @session_receivers[fsm_session_id] }
508
+ unless receiver
443
509
  decrement_outstanding if session
444
- receiver = @lifecycle_mutex.synchronize { @session_receivers.delete(fsm_session_id) }
445
- receiver&.session_retired(fsm_session_id, reason: :recovery_required)
510
+ return
511
+ end
512
+
513
+ retirement = pending ? pending.fetch(:retirement) : ExecutionRetirement.new(
514
+ fsm_session_id: fsm_session_id, reason: :recovery_required, error: payload[:error]
515
+ )
516
+ # Retain the source and recipient before calling the recipient. Neither a
517
+ # throw nor an untyped return may silently discharge completion custody.
518
+ # Moving the session count to retained custody is one idle-accounting step.
519
+ @lifecycle_mutex.synchronize do
520
+ @outstanding_sessions -= 1 if session && @outstanding_sessions.positive?
521
+ @session_receivers.delete(fsm_session_id)
522
+ @unaccepted_retirements[fsm_session_id] = {
523
+ retirement: retirement, receiver: receiver, error: nil
524
+ }.freeze
525
+ end
526
+ acceptance = begin
527
+ value = receiver.adopt_retirement(retirement)
528
+ if value.equal?(ExecutionRetirement::UNSUPPORTED)
529
+ receiver.session_retired(fsm_session_id, reason: :recovery_required)
530
+ end
531
+ value
532
+ rescue => error
533
+ retain_retirement(retirement, receiver, error)
534
+ return
535
+ end
536
+ if acceptance.equal?(ExecutionRetirement::UNSUPPORTED)
537
+ release_retirement_custody(fsm_session_id)
538
+ elsif retirement.accepted_by?(acceptance)
539
+ waiter = @waiting.delete(fsm_session_id)
540
+ release_retirement_custody(fsm_session_id)
541
+ complete_waiter(waiter, retirement)
542
+ else
543
+ retain_retirement(retirement, receiver, Phronomy::Error.new(
544
+ "Execution receiver did not accept retirement custody for #{fsm_session_id.inspect}"
545
+ ))
546
+ end
547
+ end
548
+
549
+ def retain_retirement(retirement, receiver, error = nil)
550
+ @lifecycle_mutex.synchronize do
551
+ @unaccepted_retirements[retirement.fsm_session_id] = {
552
+ retirement: retirement, receiver: receiver, error: error
553
+ }.freeze
554
+ end
555
+ end
556
+
557
+ def release_retirement_custody(fsm_session_id)
558
+ @lifecycle_mutex.synchronize do
559
+ @unaccepted_retirements.delete(fsm_session_id)
560
+ @idle_cond.broadcast if runtime_idle_locked?
446
561
  end
447
562
  end
448
563
 
@@ -464,8 +579,37 @@ module Phronomy
464
579
  end
465
580
  end
466
581
 
582
+ def confirm_retained_retirements
583
+ @unaccepted_retirements.dup.each do |id, pending|
584
+ retirement = pending.fetch(:retirement)
585
+ receiver = pending.fetch(:receiver)
586
+ waiter = @waiting[id]
587
+ next unless waiter.is_a?(Phronomy::TaskResult) && !waiter.done?
588
+ next unless retirement.accepted_by?(receiver.acknowledge_retained_retirement(retirement))
589
+
590
+ complete_waiter(waiter, retirement)
591
+ @waiting.delete(id)
592
+ release_retirement_custody(id)
593
+ rescue => error
594
+ retain_retirement(retirement, receiver, error)
595
+ end
596
+ end
597
+
467
598
  def cleanup_abandoned_work(error)
468
- drain_queued_items.each do |item|
599
+ confirm_retained_retirements
600
+ queued = drain_queued_items
601
+ @lifecycle_mutex.synchronize do
602
+ @stopped_session_owners = {}
603
+ @fsms.each_key do |id|
604
+ next unless @waiting.key?(id)
605
+ receiver = @session_receivers[id]
606
+ operation = receiver&.stopped_terminal_owner_locked(id)
607
+ @stopped_session_owners[id] = [receiver, operation].freeze if operation
608
+ end
609
+ @abandoned_transport ||= @outstanding_sessions != @stopped_session_owners.size || !@execution_deliveries.empty? ||
610
+ !@unaccepted_retirements.empty? || queued.any? { |item| !item.equal?(STOP) && !item.equal?(WAKE) }
611
+ end
612
+ queued.each do |item|
469
613
  next if item.equal?(STOP) || item.equal?(WAKE)
470
614
 
471
615
  event, = item
@@ -474,8 +618,12 @@ module Phronomy
474
618
  complete_waiter(event.payload[:completion], error)
475
619
  end
476
620
 
477
- @waiting.values.each { |waiter| complete_waiter(waiter, error) }
478
- @waiting.clear
621
+ @waiting.delete_if do |fsm_session_id, waiter|
622
+ next false if @unaccepted_retirements.key?(fsm_session_id)
623
+
624
+ complete_waiter(waiter, error)
625
+ true
626
+ end
479
627
  @fsms.clear
480
628
  deliveries = @lifecycle_mutex.synchronize do
481
629
  pending = @execution_deliveries.values
@@ -536,6 +684,7 @@ module Phronomy
536
684
 
537
685
  def runtime_idle_locked?
538
686
  @outstanding_sessions.zero? && @execution_deliveries.empty? &&
687
+ @unaccepted_retirements.empty? &&
539
688
  @execution_receivers.values.all?(&:idle?)
540
689
  end
541
690
 
@@ -565,6 +714,7 @@ module Phronomy
565
714
  rescue => caught
566
715
  @receiver_shutdown_error ||= caught
567
716
  end
717
+ @lifecycle_mutex.synchronize { @receivers_stopped = @receiver_shutdown_error.nil? }
568
718
  @runtime.__event_loop_failed(@receiver_shutdown_error) if @receiver_shutdown_error
569
719
  end
570
720
 
@@ -5,13 +5,15 @@ module Phronomy
5
5
  # binding does not acquire any resources; default Runtime is resolved on use.
6
6
  # @api private
7
7
  module ExecutionBinding
8
+ def self.supports_submission_rejection? = true
9
+
8
10
  def self.submit(pool: nil, runtime: nil, pool_name: nil, size: 10,
9
- queue_size: 100, **options, &operation)
11
+ queue_size: 100, on_rejected: nil, **options, &operation)
10
12
  unless pool
11
13
  runtime ||= Runtime.instance
12
14
  pool = pool_name ? runtime.pool(pool_name, size: size, queue_size: queue_size) : runtime.offload
13
15
  end
14
- pool.submit(**options, &operation)
16
+ Execution.submit_with_rejection_evidence(pool, on_rejected: on_rejected, **options, &operation)
15
17
  end
16
18
 
17
19
  def self.after(seconds, &callback)
@@ -19,8 +19,13 @@ module Phronomy
19
19
  end
20
20
 
21
21
  def bound_to?(owner) = @event_loop.equal?(owner)
22
+ def stopped_workers_quiescent? = @event_loop.__stopped_workers_quiescent?
22
23
  def current? = @event_loop.current?
23
24
 
25
+ def transfer_stopped_session(receiver, session_id, operation, &block)
26
+ @event_loop.__transfer_stopped_session(receiver, session_id, operation, &block)
27
+ end
28
+
24
29
  def synchronize(&block)
25
30
  @event_loop.__synchronize_execution_state(&block)
26
31
  end
@@ -2,6 +2,27 @@
2
2
 
3
3
  module Phronomy
4
4
  class Runtime
5
+ # One management observation of an original Runtime after shutdown. The
6
+ # first shutdown result stays available even after deferred cleanup succeeds.
7
+ # @api public
8
+ class ShutdownManagementResult
9
+ attr_reader :original_shutdown, :blockers, :participant_states, :read_errors, :participant_error
10
+
11
+ def initialize(original_shutdown, blockers, participant_states, read_errors, participant_error)
12
+ @original_shutdown = original_shutdown
13
+ @blockers = blockers.freeze
14
+ @participant_states = participant_states.freeze
15
+ @read_errors = read_errors.freeze
16
+ @participant_error = participant_error
17
+ freeze
18
+ end
19
+
20
+ # Returns true after the original cleanup or verified deferred finalization.
21
+ def cleanup_complete?
22
+ blockers.empty?
23
+ end
24
+ end
25
+
5
26
  # Immutable result returned by {Runtime#shutdown}.
6
27
  #
7
28
  # +runtime_outcome+ records whether execution remained healthy. It is
@@ -88,8 +88,13 @@ module Phronomy
88
88
  callbacks.each do |callback|
89
89
  callback.call
90
90
  rescue => error
91
- Phronomy::RuntimeSettings.current.logger&.error do
92
- "[TimerQueue] callback raised #{error.class}: #{error.message}"
91
+ begin
92
+ Phronomy::RuntimeSettings.current.logger&.error do
93
+ "[TimerQueue] callback raised #{error.class}: #{error.message}"
94
+ end
95
+ rescue
96
+ # Reporting must not interrupt delivery to the remaining timers.
97
+ nil
93
98
  end
94
99
  ensure
95
100
  @mutex.synchronize do
@@ -44,7 +44,7 @@ module Phronomy
44
44
  return ShutdownResult.not_started unless runtime
45
45
 
46
46
  result = runtime.shutdown(timeout: timeout)
47
- unless result.cleanup_complete?
47
+ unless result.cleanup_complete? || runtime.__deferred_cleanup_finalized?
48
48
  raise Phronomy::RuntimeShutdownError,
49
49
  "Runtime cleanup is incomplete; default Runtime was retained"
50
50
  end
@@ -99,6 +99,11 @@ module Phronomy
99
99
  end
100
100
 
101
101
  # Lookup only; retained pools remain observable during and after shutdown.
102
+ # @api private
103
+ def __stopped_workers_quiescent?
104
+ @lifecycle_mutex.synchronize { !@shutdown_result.nil? } && @pool_registry.terminated?
105
+ end
106
+
102
107
  # @api private
103
108
  def __offload_if_initialized
104
109
  @pool_registry.default_pool_if_initialized
@@ -221,18 +226,23 @@ module Phronomy
221
226
  event_loop_status, pools_stopped, timers_idle, subsystem_error =
222
227
  shutdown_resources(loop_instance, deadline: stop_deadline)
223
228
  participant_error = @lifecycle_mutex.synchronize { @shutdown_participant_error }
224
- cleanup_complete = participants_idle && participant_error.nil? &&
225
- loop_idle &&
229
+ loop_cleanup_complete = loop_idle &&
226
230
  (!loop_instance || !loop_instance.thread_alive?) &&
227
231
  event_loop_status != :cancel_timeout &&
228
- (!loop_instance || loop_instance.__receiver_cleanup_complete?) &&
229
- pools_stopped &&
230
- timers_idle &&
231
- subsystem_error.nil?
232
+ (!loop_instance || loop_instance.__receiver_cleanup_complete?)
233
+ @shutdown_barriers = []
234
+ @shutdown_barriers << :event_loop_incomplete unless loop_cleanup_complete
235
+ @shutdown_barriers << :timer_delivery_incomplete unless timers_idle
236
+ @shutdown_barriers << :subsystem_error if subsystem_error
237
+ cleanup_complete = participants_idle && participant_error.nil? &&
238
+ pools_stopped && @shutdown_barriers.empty?
232
239
 
233
- cleanup_complete = finalize_participants(participants) if cleanup_complete
240
+ if cleanup_complete
241
+ cleanup_complete = close_stopped_admissions && finalize_participants(participants)
242
+ end
234
243
  failure = @lifecycle_mutex.synchronize { @failure } || subsystem_error
235
244
  runtime_outcome = if failure || event_loop_status == :failed
245
+ @shutdown_barriers << :runtime_failure
236
246
  :failed
237
247
  else
238
248
  :terminated
@@ -254,6 +264,67 @@ module Phronomy
254
264
  end
255
265
  end
256
266
 
267
+ # Explicit default reset may use a finalization already confirmed by
268
+ # management. This read cannot initiate cleanup or call participants.
269
+ # @api private
270
+ def __deferred_cleanup_finalized?
271
+ @shutdown_mutex.synchronize { @participant_finalization_complete == true }
272
+ end
273
+
274
+ # Recheck this stopped Runtime on an external management thread. An original
275
+ # participant opts in with a nonblocking, read-only shutdown_cleanup_ready?
276
+ # that affirms its closed admission and permanent resolution of prior work.
277
+ # After positive physical and owner evidence, run deferred finalizers once.
278
+ # @return [ShutdownManagementResult] a new report for this observation
279
+ # @api public
280
+ def reconcile_shutdown
281
+ if event_loop_current?
282
+ raise Phronomy::RuntimeShutdownReentrancyError, "shutdown reconciliation requires an external management thread"
283
+ end
284
+
285
+ @shutdown_mutex.synchronize do
286
+ raise Phronomy::RuntimeShutdownError, "shutdown has not finished" unless @shutdown_result
287
+
288
+ if @shutdown_result.cleanup_complete? || @participant_finalization_complete
289
+ states = @shutdown_participants.transform_values { :finalized }
290
+ return ShutdownManagementResult.new(@shutdown_result, [], states, {}, nil)
291
+ end
292
+
293
+ barriers = @shutdown_barriers.dup
294
+ barriers << :workers_active unless @pool_registry.terminated?
295
+ if @event_loop
296
+ if @event_loop.__stopped_cleanup_verified?
297
+ barriers.delete(:event_loop_incomplete)
298
+ else
299
+ barriers << :receiver_custody_unverified
300
+ end
301
+ end
302
+ errors = {}
303
+ participants = {}
304
+ @shutdown_participants.each do |key, participant|
305
+ participants[key] = if participant.respond_to?(:shutdown_cleanup_ready?)
306
+ (participant.shutdown_cleanup_ready? == true) ? :ready : :pending
307
+ else
308
+ :unsupported
309
+ end
310
+ rescue => error
311
+ errors[key] = error
312
+ participants[key] = :error
313
+ end
314
+ barriers << :participants_pending unless participants.values.all?(:ready)
315
+ barriers << :participant_failure if @shutdown_participant_error
316
+
317
+ if barriers.empty?
318
+ if !close_stopped_admissions(participants)
319
+ barriers << :participants_pending
320
+ elsif !finalize_participants(@shutdown_participants.values)
321
+ barriers << :participant_failure
322
+ end
323
+ end
324
+ ShutdownManagementResult.new(@shutdown_result, barriers, participants, errors, @shutdown_participant_error)
325
+ end
326
+ end
327
+
257
328
  private
258
329
 
259
330
  # Called with the lifecycle lock held; participants only close their gates.
@@ -276,16 +347,49 @@ module Phronomy
276
347
  end.all?
277
348
  end
278
349
 
279
- # Finalize every participant even if one fails. Earlier releases are not
280
- # rolled back, and a failure prevents replacement of the default Runtime.
281
- def finalize_participants(participants)
282
- participants.map do |participant|
283
- participant.after_runtime_shutdown if participant.respond_to?(:after_runtime_shutdown)
284
- true
350
+ # Close diagnostic admission only as part of an otherwise eligible final
351
+ # release. The participant rechecks its leases under the admission lock;
352
+ # an intervening reader keeps its owner and a later observation can retry.
353
+ def close_stopped_admissions(states = nil)
354
+ @shutdown_participants.all? do |key, participant|
355
+ next true unless participant.respond_to?(:close_stopped_admission)
356
+ next true if participant.close_stopped_admission(deferred: !states.nil?) == true
357
+ states[key] = :pending if states
358
+ false
285
359
  rescue => error
286
360
  @lifecycle_mutex.synchronize { record_participant_failure(error) }
287
361
  false
288
- end.all?
362
+ end
363
+ end
364
+
365
+ # Finalize every participant even if one fails. Earlier releases are not
366
+ # rolled back, and a failure prevents replacement of the default Runtime.
367
+ def finalize_participants(participants)
368
+ return @participant_finalization_complete unless @participant_finalization_complete.nil?
369
+
370
+ # Both shutdown and later management hold the same shutdown mutex. Publish
371
+ # the one-shot result before delivering an asynchronous interrupt to the
372
+ # caller. A hook may already have released resources when it unwinds.
373
+ Thread.handle_interrupt(Object => :never) do
374
+ @participant_finalization_complete = Thread.handle_interrupt(Object => :immediate) do
375
+ participants.map do |participant|
376
+ participant.after_runtime_shutdown if participant.respond_to?(:after_runtime_shutdown)
377
+ true
378
+ rescue => error
379
+ @lifecycle_mutex.synchronize { record_participant_failure(error) }
380
+ false
381
+ end.all?
382
+ end
383
+ rescue Exception => error # rubocop:disable Lint/RescueException
384
+ interrupted = error
385
+ raise
386
+ ensure
387
+ if @participant_finalization_complete.nil?
388
+ @participant_finalization_complete = false
389
+ failure = interrupted || Phronomy::RuntimeShutdownError.new("Runtime finalization exited without confirmation")
390
+ @lifecycle_mutex.synchronize { record_participant_failure(failure) }
391
+ end
392
+ end
289
393
  end
290
394
 
291
395
  # Called with the lifecycle lock held. Failed hooks make cleanup uncertain.
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ # Records one worker's facts independently of its logical task observation.
5
+ # Readers and *_locked methods require the supplied owner's mutex. This lets
6
+ # owners combine physical facts with their own custody decisions atomically.
7
+ # Task methods and notifications always run outside that mutex.
8
+ # @api private
9
+ class AttemptCompletion
10
+ attr_reader :task
11
+
12
+ def initialize(mutex:)
13
+ @mutex = mutex
14
+ @task = @result = @error = @watch_error = nil
15
+ @physical = @logical = @worker_recorded = @physical_watch = false
16
+ end
17
+
18
+ def attach_locked(task)
19
+ @task = task
20
+ end
21
+
22
+ def record_worker_locked(result, error)
23
+ @result, @error, @worker_recorded = result, error, true
24
+ end
25
+
26
+ # The owner supplies its admission conclusion; this record cannot infer it.
27
+ def submission_failed_locked(error, physical:)
28
+ @logical, @physical, @error = true, physical, error
29
+ end
30
+
31
+ def snapshot_locked
32
+ {physical: @physical, logical: @logical, result: @result, error: @error,
33
+ watch_error: @watch_error, physical_watch: @physical_watch}.freeze
34
+ end
35
+
36
+ def release_task_locked
37
+ @task = nil
38
+ end
39
+
40
+ # Release heavy references after the owner has finished its delivery.
41
+ def release_references_locked
42
+ @task = @result = @error = @watch_error = nil
43
+ end
44
+
45
+ # The handle was attached before submission returned. Registering callbacks
46
+ # must not attach it again or acquire the owner mutex around task methods.
47
+ def watch(task)
48
+ physical = task.respond_to?(:on_physical_complete)
49
+ if physical
50
+ task.on_physical_complete do
51
+ @mutex.synchronize { @physical = true }
52
+ yield :physical
53
+ end
54
+ @mutex.synchronize { @physical_watch = true }
55
+ end
56
+ task.on_complete do |result, error|
57
+ @mutex.synchronize { record_observation_locked(result, error, physical: !physical) }
58
+ yield :logical
59
+ end
60
+ rescue => error
61
+ @mutex.synchronize { @watch_error = error }
62
+ raise
63
+ end
64
+
65
+ # The caller captures this record and its handle under one owner lock.
66
+ # Read the task outside that lock, then merge with the latest worker facts.
67
+ def refresh(task)
68
+ return false unless task
69
+ status, value, error = task.__snapshot
70
+ physical = if task.respond_to?(:physical_complete?)
71
+ task.physical_complete?
72
+ else
73
+ !task.respond_to?(:on_physical_complete) && status != :pending
74
+ end
75
+ @mutex.synchronize do
76
+ return false unless @task.equal?(task)
77
+ @physical ||= physical
78
+ record_observation_locked(value, error, physical: false) unless status == :pending
79
+ end
80
+ true
81
+ end
82
+
83
+ private
84
+
85
+ def record_observation_locked(result, error, physical:)
86
+ @logical = true
87
+ @physical ||= physical
88
+ @result, @error = result, error unless @worker_recorded
89
+ end
90
+ end
91
+ end
@@ -98,8 +98,13 @@ module Phronomy
98
98
  def deliver_cancel_callback(callback)
99
99
  callback.call
100
100
  rescue => error
101
- Phronomy::RuntimeSettings.current.logger&.error do
102
- "[CancellationToken] on_cancel callback raised #{error.class}: #{error.message}"
101
+ begin
102
+ Phronomy::RuntimeSettings.current.logger&.error do
103
+ "[CancellationToken] on_cancel callback raised #{error.class}: #{error.message}"
104
+ end
105
+ rescue
106
+ # Reporting must not interrupt delivery to the remaining observers.
107
+ nil
103
108
  end
104
109
  end
105
110
 
@@ -68,8 +68,13 @@ module Phronomy
68
68
  def deliver_physical_callback(callback)
69
69
  callback.call
70
70
  rescue => error
71
- Phronomy::RuntimeSettings.current.logger&.error do
72
- "[PhysicalCompletionTask] callback raised #{error.class}: #{error.message}"
71
+ begin
72
+ Phronomy::RuntimeSettings.current.logger&.error do
73
+ "[PhysicalCompletionTask] callback raised #{error.class}: #{error.message}"
74
+ end
75
+ rescue
76
+ # Reporting must not interrupt delivery to the remaining observers.
77
+ nil
73
78
  end
74
79
  end
75
80
  end
@@ -10,9 +10,24 @@ module Phronomy
10
10
  class << self
11
11
  attr_writer :backend_provider
12
12
 
13
- def submit(**options, &operation)
13
+ def submit(on_rejected: nil, **options, &operation)
14
14
  raise ArgumentError, "Execution.submit requires a block" unless operation
15
- backend.submit(**options, &operation)
15
+ submit_with_rejection_evidence(backend, on_rejected: on_rejected, **options, &operation)
16
+ end
17
+
18
+ # Optional evidence must not change a legacy submitter's call contract.
19
+ # The capability only permits sending the callback; only the callback's
20
+ # actual invocation supplies evidence. Never retry a failed submission.
21
+ # @api private
22
+ def submit_with_rejection_evidence(submitter, on_rejected: nil, **options, &operation)
23
+ if on_rejected && submitter.respond_to?(:supports_submission_rejection?) &&
24
+ submitter.supports_submission_rejection? == true &&
25
+ submitter.method(:submit).parameters.any? { |kind, name|
26
+ kind == :keyrest || ([:key, :keyreq].include?(kind) && name == :on_rejected)
27
+ }
28
+ options[:on_rejected] = on_rejected
29
+ end
30
+ submitter.submit(**options, &operation)
16
31
  end
17
32
 
18
33
  def after(seconds, &callback)