shikibu 0.3.0 → 0.4.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 (137) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +82 -0
  3. data/lib/shikibu/activity.rb +84 -48
  4. data/lib/shikibu/actors.rb +129 -0
  5. data/lib/shikibu/app.rb +33 -19
  6. data/lib/shikibu/blobs.rb +42 -0
  7. data/lib/shikibu/channels.rb +240 -64
  8. data/lib/shikibu/constants.rb +8 -0
  9. data/lib/shikibu/context.rb +184 -14
  10. data/lib/shikibu/errors.rb +56 -0
  11. data/lib/shikibu/fs.rb +93 -0
  12. data/lib/shikibu/integrations/sidekiq.rb +9 -13
  13. data/lib/shikibu/middleware/rack_app.rb +17 -1
  14. data/lib/shikibu/replay.rb +242 -107
  15. data/lib/shikibu/storage/actor_ops.rb +331 -0
  16. data/lib/shikibu/storage/channel_ops.rb +421 -0
  17. data/lib/shikibu/storage/cursor_ops.rb +37 -0
  18. data/lib/shikibu/storage/sequel_storage.rb +400 -324
  19. data/lib/shikibu/storage/sqlite_ops.rb +58 -0
  20. data/lib/shikibu/supervisor.rb +279 -0
  21. data/lib/shikibu/tasks.rb +193 -0
  22. data/lib/shikibu/version.rb +1 -1
  23. data/lib/shikibu/worker.rb +155 -73
  24. data/lib/shikibu/workflow.rb +106 -48
  25. data/lib/shikibu.rb +4 -0
  26. data/schema/SEMANTICS.md +351 -0
  27. data/schema/db/migrations/mysql/20261123000000_outbox_claimed_at.sql +5 -0
  28. data/schema/db/migrations/mysql/20261201000000_actor_registry.sql +24 -0
  29. data/schema/db/migrations/mysql/20261202000000_actor_capabilities.sql +15 -0
  30. data/schema/db/migrations/mysql/20261203000000_payload_blobs.sql +11 -0
  31. data/schema/db/migrations/mysql/20261204000000_actor_fs.sql +13 -0
  32. data/schema/db/migrations/mysql/20261205000000_actor_tasks.sql +15 -0
  33. data/schema/db/migrations/mysql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  34. data/schema/db/migrations/mysql/20261207000000_add_sandboxed.sql +5 -0
  35. data/schema/db/migrations/mysql/20261208000000_widen_actor_owner_columns.sql +15 -0
  36. data/schema/db/migrations/postgresql/20261123000000_outbox_claimed_at.sql +5 -0
  37. data/schema/db/migrations/postgresql/20261201000000_actor_registry.sql +23 -0
  38. data/schema/db/migrations/postgresql/20261202000000_actor_capabilities.sql +15 -0
  39. data/schema/db/migrations/postgresql/20261203000000_payload_blobs.sql +11 -0
  40. data/schema/db/migrations/postgresql/20261204000000_actor_fs.sql +13 -0
  41. data/schema/db/migrations/postgresql/20261205000000_actor_tasks.sql +15 -0
  42. data/schema/db/migrations/postgresql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  43. data/schema/db/migrations/postgresql/20261207000000_add_sandboxed.sql +5 -0
  44. data/schema/db/migrations/postgresql/20261208000000_widen_actor_owner_columns.sql +7 -0
  45. data/schema/db/migrations/sqlite/20261123000000_outbox_claimed_at.sql +5 -0
  46. data/schema/db/migrations/sqlite/20261201000000_actor_registry.sql +23 -0
  47. data/schema/db/migrations/sqlite/20261202000000_actor_capabilities.sql +15 -0
  48. data/schema/db/migrations/sqlite/20261203000000_payload_blobs.sql +11 -0
  49. data/schema/db/migrations/sqlite/20261204000000_actor_fs.sql +13 -0
  50. data/schema/db/migrations/sqlite/20261205000000_actor_tasks.sql +15 -0
  51. data/schema/db/migrations/sqlite/20261206000000_actor_tasks_claimed_at.sql +7 -0
  52. data/schema/db/migrations/sqlite/20261207000000_add_sandboxed.sql +5 -0
  53. data/schema/db/migrations/sqlite/20261208000000_widen_actor_owner_columns.sql +7 -0
  54. data/schema/docs/column-values.md +10 -0
  55. data/schema/spec/ActorFS.tla +117 -0
  56. data/schema/spec/ActorFS_lww_monotonic.cfg +7 -0
  57. data/schema/spec/ActorFS_new.cfg +8 -0
  58. data/schema/spec/ActorFS_old.cfg +7 -0
  59. data/schema/spec/CompetingMessageClaim.tla +127 -0
  60. data/schema/spec/CompetingMessageClaimSplit.tla +132 -0
  61. data/schema/spec/CompetingMessageClaimSplit_atomic_lost.cfg +7 -0
  62. data/schema/spec/CompetingMessageClaimSplit_atomic_once.cfg +7 -0
  63. data/schema/spec/CompetingMessageClaimSplit_fixed.cfg +7 -0
  64. data/schema/spec/CompetingMessageClaimSplit_split_lost.cfg +7 -0
  65. data/schema/spec/CompetingMessageClaimSplit_split_once.cfg +7 -0
  66. data/schema/spec/CompetingMessageClaimSplit_waitonly_lost.cfg +7 -0
  67. data/schema/spec/CompetingMessageClaimSplit_waitonly_once.cfg +7 -0
  68. data/schema/spec/CompetingMessageClaim_new.cfg +10 -0
  69. data/schema/spec/CompetingMessageClaim_old.cfg +11 -0
  70. data/schema/spec/EpochFencing.tla +87 -0
  71. data/schema/spec/EpochFencingRuns.tla +107 -0
  72. data/schema/spec/EpochFencingRuns_epoch.cfg +6 -0
  73. data/schema/spec/EpochFencingRuns_none.cfg +6 -0
  74. data/schema/spec/EpochFencingRuns_witness.cfg +6 -0
  75. data/schema/spec/EpochFencingRuns_worker.cfg +6 -0
  76. data/schema/spec/EpochFencingRuns_worker1.cfg +6 -0
  77. data/schema/spec/EpochFencing_new.cfg +8 -0
  78. data/schema/spec/EpochFencing_old.cfg +9 -0
  79. data/schema/spec/InstanceClaim.tla +196 -0
  80. data/schema/spec/InstanceClaimVerdict.tla +116 -0
  81. data/schema/spec/InstanceClaimVerdict_changedrows.cfg +6 -0
  82. data/schema/spec/InstanceClaimVerdict_changedrows_live.cfg +6 -0
  83. data/schema/spec/InstanceClaimVerdict_foundrows.cfg +6 -0
  84. data/schema/spec/InstanceClaimVerdict_foundrows_live.cfg +6 -0
  85. data/schema/spec/InstanceClaim_atomic_unfenced.cfg +9 -0
  86. data/schema/spec/InstanceClaim_live.cfg +9 -0
  87. data/schema/spec/InstanceClaim_new.cfg +9 -0
  88. data/schema/spec/InstanceClaim_old.cfg +11 -0
  89. data/schema/spec/InstanceClaim_racy_fenced.cfg +9 -0
  90. data/schema/spec/README.md +97 -0
  91. data/schema/spec/SupervisorRestart.tla +108 -0
  92. data/schema/spec/SupervisorRestartCAS.tla +84 -0
  93. data/schema/spec/SupervisorRestartCAS_nonsticky.cfg +6 -0
  94. data/schema/spec/SupervisorRestartCAS_snapshot.cfg +6 -0
  95. data/schema/spec/SupervisorRestartCAS_sticky.cfg +6 -0
  96. data/schema/spec/SupervisorRestart_racy.cfg +7 -0
  97. data/schema/spec/SupervisorRestart_strict.cfg +7 -0
  98. data/schema/spec/TaskClaim.tla +92 -0
  99. data/schema/spec/TaskClaimReadBack.tla +84 -0
  100. data/schema/spec/TaskClaimReadBack_byid.cfg +6 -0
  101. data/schema/spec/TaskClaimReadBack_order.cfg +6 -0
  102. data/schema/spec/TaskClaim_new.cfg +8 -0
  103. data/schema/spec/TaskClaim_old.cfg +9 -0
  104. data/schema/spec/TaskReclaim.tla +110 -0
  105. data/schema/spec/TaskReclaimAttempts.tla +73 -0
  106. data/schema/spec/TaskReclaimAttempts_attempt.cfg +6 -0
  107. data/schema/spec/TaskReclaimAttempts_claimant.cfg +6 -0
  108. data/schema/spec/TaskReclaim_new.cfg +8 -0
  109. data/schema/spec/TaskReclaim_old.cfg +8 -0
  110. data/schema/spec/WaitRegistration.tla +170 -0
  111. data/schema/spec/WaitRegistrationSub.tla +133 -0
  112. data/schema/spec/WaitRegistrationSub_fixed.cfg +6 -0
  113. data/schema/spec/WaitRegistrationSub_fixed_guarded.cfg +6 -0
  114. data/schema/spec/WaitRegistrationSub_guardonly_reg.cfg +6 -0
  115. data/schema/spec/WaitRegistrationSub_guardonly_res.cfg +6 -0
  116. data/schema/spec/WaitRegistrationSub_head_reg.cfg +6 -0
  117. data/schema/spec/WaitRegistrationSub_head_res.cfg +6 -0
  118. data/schema/spec/WaitRegistrationSub_noclear_reg.cfg +6 -0
  119. data/schema/spec/WaitRegistrationSub_noclear_res.cfg +6 -0
  120. data/schema/spec/WaitRegistrationSub_unfencedreg_reg.cfg +6 -0
  121. data/schema/spec/WaitRegistrationSub_unfencedreg_res.cfg +6 -0
  122. data/schema/spec/WaitRegistration_new.cfg +10 -0
  123. data/schema/spec/WaitRegistration_old.cfg +11 -0
  124. data/schema/spec/WaitRegistration_residual.cfg +11 -0
  125. data/schema/spec/WaitRegistration_sweep.cfg +11 -0
  126. data/schema/spec/actorfs_check_test.go +165 -0
  127. data/schema/spec/claim_check_test.go +387 -0
  128. data/schema/spec/competing_claim_test.go +194 -0
  129. data/schema/spec/epoch_check_test.go +128 -0
  130. data/schema/spec/go.mod +3 -0
  131. data/schema/spec/supervisorrestart_check_test.go +131 -0
  132. data/schema/spec/taskclaim_check_test.go +135 -0
  133. data/schema/spec/taskreclaim_check_test.go +125 -0
  134. data/schema/spec/tlc-check.sh +45 -0
  135. data/schema/spec/tlc-matrix.txt +68 -0
  136. data/schema/spec/wait_check_test.go +256 -0
  137. metadata +121 -2
@@ -3,12 +3,13 @@
3
3
  module Shikibu
4
4
  # Orchestrates workflow execution with deterministic replay
5
5
  class ReplayEngine
6
- attr_reader :storage, :worker_id, :hooks
6
+ attr_reader :storage, :worker_id, :hooks, :capability_key
7
7
 
8
- def initialize(storage:, worker_id:, hooks: nil)
8
+ def initialize(storage:, worker_id:, hooks: nil, capability_key: nil)
9
9
  @storage = storage
10
10
  @worker_id = worker_id
11
11
  @hooks = hooks
12
+ @capability_key = capability_key
12
13
  end
13
14
 
14
15
  # Start a new workflow instance
@@ -16,7 +17,7 @@ module Shikibu
16
17
  # @param instance_id [String] Instance ID
17
18
  # @param input [Hash, Object] Input parameters (Hash for untyped, typed object for typed workflows)
18
19
  # @return [Object, nil] Workflow result or nil if suspended
19
- def start_workflow(workflow_class, instance_id:, **input)
20
+ def start_workflow(workflow_class, instance_id:, sandboxed: false, parent_instance_id: nil, **input)
20
21
  # Serialize input for storage (handles typed inputs)
21
22
  serialized_input = workflow_class.serialize_input(input)
22
23
 
@@ -34,7 +35,9 @@ module Shikibu
34
35
  source_hash: workflow_class.source_hash,
35
36
  owner_service: 'default',
36
37
  input_data: serialized_input,
37
- status: Status::RUNNING
38
+ status: Status::RUNNING,
39
+ sandboxed: sandboxed,
40
+ parent_instance_id: parent_instance_id
38
41
  )
39
42
 
40
43
  # Execute the workflow
@@ -43,13 +46,18 @@ module Shikibu
43
46
 
44
47
  # Resume a workflow from its current state
45
48
  # @param instance_id [String] Instance ID
49
+ # @param lock_id [String, nil] Lock identity the caller already holds
50
+ # (batch claim); the run continues that lock epoch instead of
51
+ # acquiring a new one (cf. romancy ResumeWorkflowWithLockID)
46
52
  # @return [Object, nil] Workflow result or nil if suspended
47
- def resume_workflow(instance_id)
53
+ def resume_workflow(instance_id, lock_id: nil)
48
54
  instance = storage.get_instance(instance_id)
49
55
  raise WorkflowNotFoundError, instance_id unless instance
56
+ # Terminal statuses are absorbing: resuming a terminated instance is a no-op
57
+ return nil if Status::TERMINAL.include?(instance[:status])
50
58
 
51
59
  # Handle crash recovery for compensating workflows (Romancy/Edda compatible)
52
- return resume_compensating_workflow(instance_id) if instance[:status] == Status::COMPENSATING
60
+ return resume_compensating_workflow(instance_id, lock_id: lock_id) if instance[:status] == Status::COMPENSATING
53
61
 
54
62
  workflow_class = Shikibu.get_workflow(instance[:workflow_name])
55
63
  raise WorkflowNotRegisteredError, instance[:workflow_name] unless workflow_class
@@ -63,7 +71,8 @@ module Shikibu
63
71
  workflow_class,
64
72
  instance[:input_data],
65
73
  replaying: true,
66
- history_cache: history_cache
74
+ history_cache: history_cache,
75
+ lock_id: lock_id
67
76
  )
68
77
  end
69
78
 
@@ -71,28 +80,31 @@ module Shikibu
71
80
  # This executes remaining compensations from DB using the global registry
72
81
  # @param instance_id [String] Instance ID
73
82
  # @return [nil]
74
- def resume_compensating_workflow(instance_id)
75
- # Acquire lock
76
- raise LockNotAcquiredError, instance_id unless storage.try_acquire_lock(instance_id, worker_id, timeout: 300)
83
+ def resume_compensating_workflow(instance_id, lock_id: nil)
84
+ # Acquire lock (or continue the caller's claimed epoch)
85
+ lock_id = run_lock(instance_id, lock_id, 300)
77
86
 
78
87
  begin
79
- execute_compensations_from_db(instance_id)
88
+ execute_compensations_from_db(instance_id, lock_id)
80
89
 
81
90
  # Clear compensations and update status
82
91
  storage.clear_compensations(instance_id)
83
- storage.update_instance_status(instance_id, Status::FAILED)
92
+ storage.update_instance_status(instance_id, Status::FAILED, lock_id: lock_id)
84
93
 
85
94
  nil
86
95
  ensure
87
- storage.release_lock(instance_id, worker_id)
96
+ storage.release_lock(instance_id, lock_id)
88
97
  end
89
98
  end
90
99
 
91
100
  # Execute compensations from DB (for crash recovery)
92
101
  # Uses global registry to find compensation functions
93
102
  # @param instance_id [String] Instance ID
94
- def execute_compensations_from_db(instance_id)
103
+ def execute_compensations_from_db(instance_id, lock_id = nil)
95
104
  compensations = storage.get_compensations(instance_id)
105
+ instance = storage.get_instance(instance_id)
106
+ ctx = WorkflowContext.new(instance_id: instance_id, workflow_name: instance&.dig(:workflow_name),
107
+ worker_id: worker_id, lock_id: lock_id, storage: storage, hooks: hooks)
96
108
 
97
109
  # Get already executed compensation IDs from history (idempotency)
98
110
  history = storage.get_history(instance_id)
@@ -106,29 +118,39 @@ module Shikibu
106
118
  compensations.each do |comp|
107
119
  next if executed_ids.include?(comp[:id])
108
120
 
109
- execute_compensation_from_registry(instance_id, comp)
121
+ # The instance context identifies children spawned by the
122
+ # compensation (sandbox inheritance).
123
+ with_current_workflow_context(ctx) { execute_compensation_from_registry(ctx, comp) }
110
124
  end
111
125
  end
112
126
 
113
127
  # Execute a single compensation from registry
114
128
  # @param instance_id [String] Instance ID
115
129
  # @param comp [Hash] Compensation record from DB
116
- def execute_compensation_from_registry(instance_id, comp)
130
+ def execute_compensation_from_registry(ctx, comp)
131
+ instance_id = ctx.instance_id
132
+ lock_id = ctx.lock_id
117
133
  compensation_fn = Shikibu.get_compensation(comp[:activity_name])
118
134
 
119
135
  if compensation_fn.nil?
120
136
  # Inline block or unregistered compensation - cannot recover, skip with warning
121
- record_compensation_skipped(instance_id, comp)
137
+ record_compensation_skipped(instance_id, comp, lock_id)
122
138
  return
123
139
  end
124
140
 
125
- # Execute the compensation
141
+ # Execute the compensation (as an activity body, like the in-run path)
126
142
  args = comp[:args] || {}
127
143
  symbolized_args = args.transform_keys(&:to_sym)
128
- compensation_fn.call(nil, **symbolized_args)
144
+ ctx.current_activity_id = "compensation:#{comp[:id]}"
145
+ begin
146
+ compensation_fn.call(ctx, **symbolized_args)
147
+ ensure
148
+ ctx.current_activity_id = nil
149
+ end
129
150
 
130
151
  # Record success
131
152
  storage.append_history(
153
+ lock_id: lock_id,
132
154
  instance_id: instance_id,
133
155
  activity_id: "compensation:#{comp[:id]}",
134
156
  event_type: EventType::COMPENSATION_EXECUTED,
@@ -138,9 +160,12 @@ module Shikibu
138
160
  activity_name: comp[:activity_name]
139
161
  }
140
162
  )
163
+ rescue LockLostError
164
+ raise
141
165
  rescue StandardError => e
142
166
  # Record failure but continue
143
167
  storage.append_history(
168
+ lock_id: lock_id,
144
169
  instance_id: instance_id,
145
170
  activity_id: "compensation:#{comp[:id]}",
146
171
  event_type: EventType::COMPENSATION_FAILED,
@@ -155,8 +180,9 @@ module Shikibu
155
180
  end
156
181
 
157
182
  # Record that a compensation was skipped (inline or unregistered)
158
- def record_compensation_skipped(instance_id, comp)
183
+ def record_compensation_skipped(instance_id, comp, lock_id)
159
184
  storage.append_history(
185
+ lock_id: lock_id,
160
186
  instance_id: instance_id,
161
187
  activity_id: "compensation:#{comp[:id]}",
162
188
  event_type: EventType::COMPENSATION_FAILED,
@@ -173,24 +199,25 @@ module Shikibu
173
199
 
174
200
  private
175
201
 
176
- def execute_workflow(instance_id, workflow_class, input, replaying:, history_cache: {})
177
- # Acquire lock
178
- lock_timeout = workflow_class.lock_timeout
179
- unless storage.try_acquire_lock(instance_id, worker_id, timeout: lock_timeout)
180
- raise LockNotAcquiredError, instance_id
181
- end
202
+ def with_current_workflow_context(ctx)
203
+ previous_workflow_context = Thread.current[:shikibu_workflow_context]
204
+ Thread.current[:shikibu_workflow_context] = ctx
205
+ yield
206
+ ensure
207
+ Thread.current[:shikibu_workflow_context] = previous_workflow_context
208
+ end
209
+
210
+ # Run (or replay) the workflow under the instance lock. A resumed
211
+ # instance is set running again first; one that terminated meanwhile
212
+ # (e.g. was cancelled) refuses that write and the run ends at once.
213
+ def execute_workflow(instance_id, workflow_class, input, replaying:, history_cache: {}, lock_id: nil)
214
+ lock_id = run_lock(instance_id, lock_id, workflow_class.lock_timeout)
215
+ # Heartbeat interrupts the run if the lease is lost (see below).
216
+ heartbeat = start_lock_heartbeat(instance_id, lock_id, workflow_class.lock_timeout, Thread.current)
182
217
 
183
218
  begin
184
- # Create context
185
- ctx = WorkflowContext.new(
186
- instance_id: instance_id,
187
- workflow_name: workflow_class.workflow_name,
188
- worker_id: worker_id,
189
- storage: storage,
190
- hooks: hooks,
191
- history_cache: history_cache,
192
- replaying: replaying
193
- )
219
+ storage.update_instance_status(instance_id, Status::RUNNING, lock_id: lock_id) if replaying
220
+ ctx = build_context(instance_id, workflow_class, lock_id, history_cache, replaying)
194
221
 
195
222
  # Call hooks
196
223
  hooks&.on_workflow_start&.call(instance_id, workflow_class.workflow_name, input)
@@ -200,80 +227,114 @@ module Shikibu
200
227
  workflow.instance_variable_set(:@pending_compensations, [])
201
228
  workflow.context = ctx
202
229
 
203
- # Handle typed vs untyped input
204
- result = if workflow_class.typed_input?
205
- # Typed workflow: deserialize and pass single object
206
- typed_input = workflow_class.deserialize_input(input)
207
- workflow.execute(typed_input)
208
- else
209
- # Legacy: symbolize and spread as keyword args
210
- symbolized_input = symbolize_keys(input)
211
- workflow.execute(**symbolized_input)
212
- end
213
-
214
- # Serialize output
215
- serialized_output = workflow_class.serialize_output(result)
216
-
217
- # Mark completed
218
- storage.update_instance_status(instance_id, Status::COMPLETED, output_data: serialized_output)
219
- storage.clear_compensations(instance_id)
220
-
221
- # Cleanup direct subscriptions
222
- cleanup_subscriptions(ctx)
230
+ result = invoke_workflow(workflow, workflow_class, input, ctx)
223
231
 
224
- # Call hooks
225
- hooks&.on_workflow_complete&.call(instance_id, workflow_class.workflow_name, result)
232
+ # Even if workflow code rescued the abort error and returned, a
233
+ # poisoned run never completes: its recorded history ends here and a
234
+ # later resume re-executes the failed primitive.
235
+ raise ctx.run_abort_error if ctx.run_aborted?
226
236
 
227
- result
237
+ complete_workflow(instance_id, workflow_class, ctx, result, lock_id)
228
238
  rescue WaitForTimerSignal => e
229
- handle_timer_suspend(instance_id, e)
239
+ handle_timer_suspend(instance_id, e, lock_id)
230
240
  nil
231
241
  rescue WaitForChannelSignal => e
232
- handle_channel_suspend(instance_id, e)
242
+ handle_channel_suspend(instance_id, e, lock_id)
233
243
  nil
234
244
  rescue RecurSignal => e
235
- handle_recur(instance_id, workflow_class, e)
245
+ handle_recur(instance_id, workflow_class, e, lock_id)
236
246
  nil
237
247
  rescue WorkflowCancelledError
238
- storage.update_instance_status(instance_id, Status::CANCELLED)
248
+ storage.update_instance_status(instance_id, Status::CANCELLED, lock_id: lock_id)
239
249
  hooks&.on_workflow_cancelled&.call(instance_id, workflow_class.workflow_name)
240
250
  raise
251
+ rescue LockLostError
252
+ raise # no failure handling: handled below without further writes
253
+ rescue RunAbortedError => e
254
+ # A fenced step often poisons the run with LockLostError before the
255
+ # workflow has a chance to return it. Keep the same diagnostic the
256
+ # direct lock-loss path emits.
257
+ lock_error = lock_loss_in_cause(e)
258
+ handle_lock_lost(instance_id, lock_error) if lock_error
259
+ nil # infrastructure abort: no completion, failure status, or compensations
241
260
  rescue StandardError => e
242
- handle_failure(instance_id, workflow_class, workflow, e)
243
- raise
261
+ if ctx&.run_aborted?
262
+ nil # workflow code rescued/reshaped the abort; still no failure handling
263
+ else
264
+ handle_failure(instance_id, workflow_class, workflow, e, lock_id)
265
+ raise
266
+ end
244
267
  ensure
245
- storage.release_lock(instance_id, worker_id)
268
+ finish_run(heartbeat, instance_id, lock_id)
246
269
  end
270
+ rescue LockLostError => e
271
+ # From a fenced write or the heartbeat, also while a handler above was
272
+ # running: the new owner continues (or the instance terminated).
273
+ handle_lock_lost(instance_id, e)
274
+ nil
247
275
  end
248
276
 
249
- def handle_timer_suspend(instance_id, signal)
250
- # Update status
251
- storage.update_instance_status(
252
- instance_id,
253
- Status::WAITING_FOR_TIMER,
254
- current_activity_id: signal.activity_id
255
- )
277
+ # Invoke the workflow body with its input in the thread-local actor
278
+ # context. The context identifies nested starts as children.
279
+ def invoke_workflow(workflow, workflow_class, input, ctx)
280
+ with_current_workflow_context(ctx) do
281
+ if workflow_class.typed_input?
282
+ workflow.execute(workflow_class.deserialize_input(input))
283
+ else
284
+ workflow.execute(**symbolize_keys(input))
285
+ end
286
+ end
287
+ end
288
+
289
+ def complete_workflow(instance_id, workflow_class, ctx, result, lock_id)
290
+ serialized_output = workflow_class.serialize_output(result)
291
+ storage.update_instance_status(instance_id, Status::COMPLETED, output_data: serialized_output, lock_id: lock_id)
292
+ storage.clear_compensations(instance_id)
293
+ cleanup_subscriptions(ctx)
294
+ hooks&.on_workflow_complete&.call(instance_id, workflow_class.workflow_name, result)
295
+ result
296
+ end
256
297
 
257
- # Register timer
298
+ # Stop the heartbeat before releasing the lock; a LockLostError it
299
+ # already queued is delivered after this block (see execute_workflow).
300
+ def finish_run(heartbeat, instance_id, lock_id)
301
+ Thread.handle_interrupt(LockLostError => :never) do
302
+ heartbeat.kill
303
+ heartbeat.join
304
+ storage.release_lock(instance_id, lock_id)
305
+ end
306
+ end
307
+
308
+ def handle_timer_suspend(instance_id, signal, lock_id)
309
+ # Register the timer (fenced), then suspend: a cancel that landed
310
+ # during this run refuses the status write, and the timer just
311
+ # registered is dropped again.
258
312
  storage.register_timer(
259
313
  instance_id: instance_id,
260
314
  timer_id: signal.timer_id,
261
315
  expires_at: signal.expires_at,
262
- activity_id: signal.activity_id
316
+ activity_id: signal.activity_id,
317
+ lock_id: lock_id
263
318
  )
264
- end
265
-
266
- def handle_channel_suspend(instance_id, signal)
267
- # Update status
268
319
  storage.update_instance_status(
269
320
  instance_id,
270
- Status::WAITING_FOR_MESSAGE,
271
- current_activity_id: signal.activity_id
321
+ Status::WAITING_FOR_TIMER,
322
+ current_activity_id: signal.activity_id,
323
+ lock_id: lock_id
272
324
  )
325
+ rescue InstanceTerminatedError
326
+ storage.remove_timer(instance_id: instance_id, timer_id: signal.timer_id)
327
+ raise
328
+ end
273
329
 
274
- # Update subscription with activity_id and timeout
275
- storage.subscribe_to_channel(
330
+ def handle_channel_suspend(instance_id, signal, lock_id)
331
+ # Atomically register the wait and release the lock (single tx).
332
+ # If a pending message is found inside the tx the wait is skipped and
333
+ # the instance stays 'running' — the resumable sweep replays it into
334
+ # the pending message (missed-wakeup closure).
335
+ storage.register_channel_wait(
276
336
  instance_id: instance_id,
337
+ worker_id: lock_id,
277
338
  channel: signal.channel,
278
339
  mode: signal.mode,
279
340
  activity_id: signal.activity_id,
@@ -281,30 +342,20 @@ module Shikibu
281
342
  )
282
343
  end
283
344
 
284
- def handle_recur(instance_id, workflow_class, signal)
285
- # Archive history
286
- storage.archive_history(instance_id)
287
-
288
- # Update instance with new input and reset status
289
- storage.update_instance_status(instance_id, Status::RECURRED)
345
+ def handle_recur(instance_id, _workflow_class, signal, lock_id)
346
+ # One fenced transaction: archive this iteration, discard its
347
+ # subscriptions/timers/compensations, replace the input, and mark the
348
+ # same instance recurred. A failure leaves it running with its history
349
+ # intact, so a later resume simply recurs again.
350
+ storage.prepare_recur(instance_id: instance_id, input_data: signal.new_input, lock_id: lock_id)
290
351
 
291
- # Create new instance with continued_from link
292
- new_instance_id = SecureRandom.uuid
293
- storage.create_instance(
294
- instance_id: new_instance_id,
295
- workflow_name: workflow_class.workflow_name,
296
- source_hash: workflow_class.source_hash,
297
- owner_service: 'default',
298
- input_data: signal.new_input,
299
- status: Status::RUNNING
300
- )
301
-
302
- # The new instance will be picked up by the worker
352
+ # The same instance will be picked up by the worker
303
353
  end
304
354
 
305
- def handle_failure(instance_id, workflow_class, workflow, error)
355
+ def handle_failure(instance_id, workflow_class, workflow, error, lock_id)
306
356
  # Record failure in history
307
357
  storage.append_history(
358
+ lock_id: lock_id,
308
359
  instance_id: instance_id,
309
360
  activity_id: 'workflow_failed',
310
361
  event_type: EventType::WORKFLOW_FAILED,
@@ -315,21 +366,104 @@ module Shikibu
315
366
  )
316
367
 
317
368
  # Update status to compensating
318
- storage.update_instance_status(instance_id, Status::COMPENSATING)
369
+ storage.update_instance_status(instance_id, Status::COMPENSATING, lock_id: lock_id)
319
370
 
320
- # Execute compensations via workflow instance (LIFO order)
321
- workflow.run_compensations
371
+ # Execute compensations via workflow instance (LIFO order). The
372
+ # workflow context stays current so children spawned by a
373
+ # compensation inherit this instance as parent (sandboxing).
374
+ with_current_workflow_context(workflow.ctx) { workflow.run_compensations }
322
375
 
323
376
  # Clear compensation records from database
324
377
  storage.clear_compensations(instance_id)
325
378
 
326
379
  # Update final status
327
- storage.update_instance_status(instance_id, Status::FAILED)
380
+ storage.update_instance_status(instance_id, Status::FAILED, lock_id: lock_id)
328
381
 
329
382
  # Call hooks
330
383
  hooks&.on_workflow_failed&.call(instance_id, workflow_class.workflow_name, error)
331
384
  end
332
385
 
386
+ # Generate an epoch-bearing lock-holder identity (worker_id#<random>).
387
+ # A lease lost and re-acquired by the same worker is a different holder;
388
+ # locked_by equality checks then act as fencing tokens.
389
+ def new_lock_identity(worker_id)
390
+ "#{worker_id}##{SecureRandom.hex(8)}"
391
+ end
392
+
393
+ def lock_loss_in_cause(error)
394
+ current = error
395
+ while current
396
+ return current if current.is_a?(LockLostError)
397
+
398
+ current = current.cause
399
+ end
400
+ nil
401
+ end
402
+
403
+ # Lease lost mid-run: the new owner continues; do not attempt stale
404
+ # failure handling (fenced writes would fail anyway). An instance that
405
+ # terminated during the run (e.g. was cancelled) has nothing left to do.
406
+ def handle_lock_lost(instance_id, error)
407
+ return if error.is_a?(InstanceTerminatedError)
408
+
409
+ warn "[Shikibu::ReplayEngine] Lock lost for #{instance_id}; new owner continues"
410
+ end
411
+
412
+ # Spawn a lock-heartbeat thread: refreshes the lease and raises
413
+ # LockLostError into the owner thread if the lock is lost.
414
+ def start_lock_heartbeat(instance_id, lock_id, timeout, owner)
415
+ interval = [timeout / 3, 60].min
416
+ Thread.new do
417
+ loop do
418
+ sleep interval
419
+ begin
420
+ held = storage.refresh_lock(instance_id, lock_id, timeout: timeout)
421
+ rescue StandardError => e
422
+ # Transient (busy database, dropped connection): retry on the
423
+ # next tick, well within the lease; only a lost lock stops.
424
+ warn "[Shikibu::ReplayEngine] Lock heartbeat for #{instance_id} failed: #{e.class}: #{e.message}"
425
+ next
426
+ end
427
+ next if held
428
+
429
+ owner.raise(LockLostError, instance_id)
430
+ break
431
+ end
432
+ end
433
+ end
434
+
435
+ def build_context(instance_id, workflow_class, lock_id, history_cache, replaying)
436
+ WorkflowContext.new(
437
+ instance_id: instance_id,
438
+ workflow_name: workflow_class.workflow_name,
439
+ worker_id: worker_id,
440
+ lock_id: lock_id,
441
+ storage: storage,
442
+ hooks: hooks,
443
+ history_cache: history_cache,
444
+ replaying: replaying,
445
+ capability_key: capability_key
446
+ )
447
+ end
448
+
449
+ # Lock for a run: continue the caller's claimed epoch — its lease must
450
+ # still be held (another worker may have taken an expired claim), and is
451
+ # extended — or acquire a fresh one.
452
+ def run_lock(instance_id, lock_id, timeout)
453
+ return acquire_epoch_lock(instance_id, timeout) unless lock_id
454
+ raise LockNotAcquiredError, instance_id unless storage.refresh_lock(instance_id, lock_id, timeout: timeout)
455
+
456
+ lock_id
457
+ end
458
+
459
+ # Acquire the instance lock under a fresh epoch identity
460
+ def acquire_epoch_lock(instance_id, timeout)
461
+ lock_id = new_lock_identity(worker_id)
462
+ raise LockNotAcquiredError, instance_id unless storage.try_acquire_lock(instance_id, lock_id, timeout: timeout)
463
+
464
+ lock_id
465
+ end
466
+
333
467
  def cleanup_subscriptions(ctx)
334
468
  ctx.direct_subscriptions.each do |channel|
335
469
  storage.unsubscribe_from_channel(
@@ -356,7 +490,8 @@ module Shikibu
356
490
  event_type: event_type,
357
491
  result: data&.dig(:result),
358
492
  error_type: data&.dig(:error_type),
359
- error_message: data&.dig(:error_message)
493
+ error_message: data&.dig(:error_message),
494
+ code: data&.dig(:code)
360
495
  }
361
496
  end
362
497
  end