shikibu 0.2.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +121 -0
  3. data/lib/shikibu/activity.rb +84 -48
  4. data/lib/shikibu/actors.rb +129 -0
  5. data/lib/shikibu/app.rb +45 -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 +248 -100
  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/typed_payload.rb +189 -0
  23. data/lib/shikibu/version.rb +1 -1
  24. data/lib/shikibu/worker.rb +155 -73
  25. data/lib/shikibu/workflow.rb +203 -50
  26. data/lib/shikibu.rb +5 -0
  27. data/schema/SEMANTICS.md +351 -0
  28. data/schema/db/migrations/mysql/20261123000000_outbox_claimed_at.sql +5 -0
  29. data/schema/db/migrations/mysql/20261201000000_actor_registry.sql +24 -0
  30. data/schema/db/migrations/mysql/20261202000000_actor_capabilities.sql +15 -0
  31. data/schema/db/migrations/mysql/20261203000000_payload_blobs.sql +11 -0
  32. data/schema/db/migrations/mysql/20261204000000_actor_fs.sql +13 -0
  33. data/schema/db/migrations/mysql/20261205000000_actor_tasks.sql +15 -0
  34. data/schema/db/migrations/mysql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  35. data/schema/db/migrations/mysql/20261207000000_add_sandboxed.sql +5 -0
  36. data/schema/db/migrations/mysql/20261208000000_widen_actor_owner_columns.sql +15 -0
  37. data/schema/db/migrations/postgresql/20261123000000_outbox_claimed_at.sql +5 -0
  38. data/schema/db/migrations/postgresql/20261201000000_actor_registry.sql +23 -0
  39. data/schema/db/migrations/postgresql/20261202000000_actor_capabilities.sql +15 -0
  40. data/schema/db/migrations/postgresql/20261203000000_payload_blobs.sql +11 -0
  41. data/schema/db/migrations/postgresql/20261204000000_actor_fs.sql +13 -0
  42. data/schema/db/migrations/postgresql/20261205000000_actor_tasks.sql +15 -0
  43. data/schema/db/migrations/postgresql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  44. data/schema/db/migrations/postgresql/20261207000000_add_sandboxed.sql +5 -0
  45. data/schema/db/migrations/postgresql/20261208000000_widen_actor_owner_columns.sql +7 -0
  46. data/schema/db/migrations/sqlite/20261123000000_outbox_claimed_at.sql +5 -0
  47. data/schema/db/migrations/sqlite/20261201000000_actor_registry.sql +23 -0
  48. data/schema/db/migrations/sqlite/20261202000000_actor_capabilities.sql +15 -0
  49. data/schema/db/migrations/sqlite/20261203000000_payload_blobs.sql +11 -0
  50. data/schema/db/migrations/sqlite/20261204000000_actor_fs.sql +13 -0
  51. data/schema/db/migrations/sqlite/20261205000000_actor_tasks.sql +15 -0
  52. data/schema/db/migrations/sqlite/20261206000000_actor_tasks_claimed_at.sql +7 -0
  53. data/schema/db/migrations/sqlite/20261207000000_add_sandboxed.sql +5 -0
  54. data/schema/db/migrations/sqlite/20261208000000_widen_actor_owner_columns.sql +7 -0
  55. data/schema/docs/column-values.md +10 -0
  56. data/schema/spec/ActorFS.tla +117 -0
  57. data/schema/spec/ActorFS_lww_monotonic.cfg +7 -0
  58. data/schema/spec/ActorFS_new.cfg +8 -0
  59. data/schema/spec/ActorFS_old.cfg +7 -0
  60. data/schema/spec/CompetingMessageClaim.tla +127 -0
  61. data/schema/spec/CompetingMessageClaimSplit.tla +132 -0
  62. data/schema/spec/CompetingMessageClaimSplit_atomic_lost.cfg +7 -0
  63. data/schema/spec/CompetingMessageClaimSplit_atomic_once.cfg +7 -0
  64. data/schema/spec/CompetingMessageClaimSplit_fixed.cfg +7 -0
  65. data/schema/spec/CompetingMessageClaimSplit_split_lost.cfg +7 -0
  66. data/schema/spec/CompetingMessageClaimSplit_split_once.cfg +7 -0
  67. data/schema/spec/CompetingMessageClaimSplit_waitonly_lost.cfg +7 -0
  68. data/schema/spec/CompetingMessageClaimSplit_waitonly_once.cfg +7 -0
  69. data/schema/spec/CompetingMessageClaim_new.cfg +10 -0
  70. data/schema/spec/CompetingMessageClaim_old.cfg +11 -0
  71. data/schema/spec/EpochFencing.tla +87 -0
  72. data/schema/spec/EpochFencingRuns.tla +107 -0
  73. data/schema/spec/EpochFencingRuns_epoch.cfg +6 -0
  74. data/schema/spec/EpochFencingRuns_none.cfg +6 -0
  75. data/schema/spec/EpochFencingRuns_witness.cfg +6 -0
  76. data/schema/spec/EpochFencingRuns_worker.cfg +6 -0
  77. data/schema/spec/EpochFencingRuns_worker1.cfg +6 -0
  78. data/schema/spec/EpochFencing_new.cfg +8 -0
  79. data/schema/spec/EpochFencing_old.cfg +9 -0
  80. data/schema/spec/InstanceClaim.tla +196 -0
  81. data/schema/spec/InstanceClaimVerdict.tla +116 -0
  82. data/schema/spec/InstanceClaimVerdict_changedrows.cfg +6 -0
  83. data/schema/spec/InstanceClaimVerdict_changedrows_live.cfg +6 -0
  84. data/schema/spec/InstanceClaimVerdict_foundrows.cfg +6 -0
  85. data/schema/spec/InstanceClaimVerdict_foundrows_live.cfg +6 -0
  86. data/schema/spec/InstanceClaim_atomic_unfenced.cfg +9 -0
  87. data/schema/spec/InstanceClaim_live.cfg +9 -0
  88. data/schema/spec/InstanceClaim_new.cfg +9 -0
  89. data/schema/spec/InstanceClaim_old.cfg +11 -0
  90. data/schema/spec/InstanceClaim_racy_fenced.cfg +9 -0
  91. data/schema/spec/README.md +97 -0
  92. data/schema/spec/SupervisorRestart.tla +108 -0
  93. data/schema/spec/SupervisorRestartCAS.tla +84 -0
  94. data/schema/spec/SupervisorRestartCAS_nonsticky.cfg +6 -0
  95. data/schema/spec/SupervisorRestartCAS_snapshot.cfg +6 -0
  96. data/schema/spec/SupervisorRestartCAS_sticky.cfg +6 -0
  97. data/schema/spec/SupervisorRestart_racy.cfg +7 -0
  98. data/schema/spec/SupervisorRestart_strict.cfg +7 -0
  99. data/schema/spec/TaskClaim.tla +92 -0
  100. data/schema/spec/TaskClaimReadBack.tla +84 -0
  101. data/schema/spec/TaskClaimReadBack_byid.cfg +6 -0
  102. data/schema/spec/TaskClaimReadBack_order.cfg +6 -0
  103. data/schema/spec/TaskClaim_new.cfg +8 -0
  104. data/schema/spec/TaskClaim_old.cfg +9 -0
  105. data/schema/spec/TaskReclaim.tla +110 -0
  106. data/schema/spec/TaskReclaimAttempts.tla +73 -0
  107. data/schema/spec/TaskReclaimAttempts_attempt.cfg +6 -0
  108. data/schema/spec/TaskReclaimAttempts_claimant.cfg +6 -0
  109. data/schema/spec/TaskReclaim_new.cfg +8 -0
  110. data/schema/spec/TaskReclaim_old.cfg +8 -0
  111. data/schema/spec/WaitRegistration.tla +170 -0
  112. data/schema/spec/WaitRegistrationSub.tla +133 -0
  113. data/schema/spec/WaitRegistrationSub_fixed.cfg +6 -0
  114. data/schema/spec/WaitRegistrationSub_fixed_guarded.cfg +6 -0
  115. data/schema/spec/WaitRegistrationSub_guardonly_reg.cfg +6 -0
  116. data/schema/spec/WaitRegistrationSub_guardonly_res.cfg +6 -0
  117. data/schema/spec/WaitRegistrationSub_head_reg.cfg +6 -0
  118. data/schema/spec/WaitRegistrationSub_head_res.cfg +6 -0
  119. data/schema/spec/WaitRegistrationSub_noclear_reg.cfg +6 -0
  120. data/schema/spec/WaitRegistrationSub_noclear_res.cfg +6 -0
  121. data/schema/spec/WaitRegistrationSub_unfencedreg_reg.cfg +6 -0
  122. data/schema/spec/WaitRegistrationSub_unfencedreg_res.cfg +6 -0
  123. data/schema/spec/WaitRegistration_new.cfg +10 -0
  124. data/schema/spec/WaitRegistration_old.cfg +11 -0
  125. data/schema/spec/WaitRegistration_residual.cfg +11 -0
  126. data/schema/spec/WaitRegistration_sweep.cfg +11 -0
  127. data/schema/spec/actorfs_check_test.go +165 -0
  128. data/schema/spec/claim_check_test.go +387 -0
  129. data/schema/spec/competing_claim_test.go +194 -0
  130. data/schema/spec/epoch_check_test.go +128 -0
  131. data/schema/spec/go.mod +3 -0
  132. data/schema/spec/supervisorrestart_check_test.go +131 -0
  133. data/schema/spec/taskclaim_check_test.go +135 -0
  134. data/schema/spec/taskreclaim_check_test.go +125 -0
  135. data/schema/spec/tlc-check.sh +45 -0
  136. data/schema/spec/tlc-matrix.txt +68 -0
  137. data/schema/spec/wait_check_test.go +256 -0
  138. metadata +136 -2
@@ -3,20 +3,24 @@
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
15
16
  # @param workflow_class [Class] Workflow class
16
17
  # @param instance_id [String] Instance ID
17
- # @param input [Hash] Input parameters
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)
21
+ # Serialize input for storage (handles typed inputs)
22
+ serialized_input = workflow_class.serialize_input(input)
23
+
20
24
  # Save workflow definition
21
25
  storage.save_workflow_definition(
22
26
  workflow_name: workflow_class.workflow_name,
@@ -30,23 +34,30 @@ module Shikibu
30
34
  workflow_name: workflow_class.workflow_name,
31
35
  source_hash: workflow_class.source_hash,
32
36
  owner_service: 'default',
33
- input_data: input,
34
- status: Status::RUNNING
37
+ input_data: serialized_input,
38
+ status: Status::RUNNING,
39
+ sandboxed: sandboxed,
40
+ parent_instance_id: parent_instance_id
35
41
  )
36
42
 
37
43
  # Execute the workflow
38
- execute_workflow(instance_id, workflow_class, input, replaying: false)
44
+ execute_workflow(instance_id, workflow_class, serialized_input, replaying: false)
39
45
  end
40
46
 
41
47
  # Resume a workflow from its current state
42
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)
43
52
  # @return [Object, nil] Workflow result or nil if suspended
44
- def resume_workflow(instance_id)
53
+ def resume_workflow(instance_id, lock_id: nil)
45
54
  instance = storage.get_instance(instance_id)
46
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])
47
58
 
48
59
  # Handle crash recovery for compensating workflows (Romancy/Edda compatible)
49
- 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
50
61
 
51
62
  workflow_class = Shikibu.get_workflow(instance[:workflow_name])
52
63
  raise WorkflowNotRegisteredError, instance[:workflow_name] unless workflow_class
@@ -60,7 +71,8 @@ module Shikibu
60
71
  workflow_class,
61
72
  instance[:input_data],
62
73
  replaying: true,
63
- history_cache: history_cache
74
+ history_cache: history_cache,
75
+ lock_id: lock_id
64
76
  )
65
77
  end
66
78
 
@@ -68,28 +80,31 @@ module Shikibu
68
80
  # This executes remaining compensations from DB using the global registry
69
81
  # @param instance_id [String] Instance ID
70
82
  # @return [nil]
71
- def resume_compensating_workflow(instance_id)
72
- # Acquire lock
73
- 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)
74
86
 
75
87
  begin
76
- execute_compensations_from_db(instance_id)
88
+ execute_compensations_from_db(instance_id, lock_id)
77
89
 
78
90
  # Clear compensations and update status
79
91
  storage.clear_compensations(instance_id)
80
- storage.update_instance_status(instance_id, Status::FAILED)
92
+ storage.update_instance_status(instance_id, Status::FAILED, lock_id: lock_id)
81
93
 
82
94
  nil
83
95
  ensure
84
- storage.release_lock(instance_id, worker_id)
96
+ storage.release_lock(instance_id, lock_id)
85
97
  end
86
98
  end
87
99
 
88
100
  # Execute compensations from DB (for crash recovery)
89
101
  # Uses global registry to find compensation functions
90
102
  # @param instance_id [String] Instance ID
91
- def execute_compensations_from_db(instance_id)
103
+ def execute_compensations_from_db(instance_id, lock_id = nil)
92
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)
93
108
 
94
109
  # Get already executed compensation IDs from history (idempotency)
95
110
  history = storage.get_history(instance_id)
@@ -103,29 +118,39 @@ module Shikibu
103
118
  compensations.each do |comp|
104
119
  next if executed_ids.include?(comp[:id])
105
120
 
106
- 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) }
107
124
  end
108
125
  end
109
126
 
110
127
  # Execute a single compensation from registry
111
128
  # @param instance_id [String] Instance ID
112
129
  # @param comp [Hash] Compensation record from DB
113
- 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
114
133
  compensation_fn = Shikibu.get_compensation(comp[:activity_name])
115
134
 
116
135
  if compensation_fn.nil?
117
136
  # Inline block or unregistered compensation - cannot recover, skip with warning
118
- record_compensation_skipped(instance_id, comp)
137
+ record_compensation_skipped(instance_id, comp, lock_id)
119
138
  return
120
139
  end
121
140
 
122
- # Execute the compensation
141
+ # Execute the compensation (as an activity body, like the in-run path)
123
142
  args = comp[:args] || {}
124
143
  symbolized_args = args.transform_keys(&:to_sym)
125
- 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
126
150
 
127
151
  # Record success
128
152
  storage.append_history(
153
+ lock_id: lock_id,
129
154
  instance_id: instance_id,
130
155
  activity_id: "compensation:#{comp[:id]}",
131
156
  event_type: EventType::COMPENSATION_EXECUTED,
@@ -135,9 +160,12 @@ module Shikibu
135
160
  activity_name: comp[:activity_name]
136
161
  }
137
162
  )
163
+ rescue LockLostError
164
+ raise
138
165
  rescue StandardError => e
139
166
  # Record failure but continue
140
167
  storage.append_history(
168
+ lock_id: lock_id,
141
169
  instance_id: instance_id,
142
170
  activity_id: "compensation:#{comp[:id]}",
143
171
  event_type: EventType::COMPENSATION_FAILED,
@@ -152,8 +180,9 @@ module Shikibu
152
180
  end
153
181
 
154
182
  # Record that a compensation was skipped (inline or unregistered)
155
- def record_compensation_skipped(instance_id, comp)
183
+ def record_compensation_skipped(instance_id, comp, lock_id)
156
184
  storage.append_history(
185
+ lock_id: lock_id,
157
186
  instance_id: instance_id,
158
187
  activity_id: "compensation:#{comp[:id]}",
159
188
  event_type: EventType::COMPENSATION_FAILED,
@@ -170,24 +199,25 @@ module Shikibu
170
199
 
171
200
  private
172
201
 
173
- def execute_workflow(instance_id, workflow_class, input, replaying:, history_cache: {})
174
- # Acquire lock
175
- lock_timeout = workflow_class.lock_timeout
176
- unless storage.try_acquire_lock(instance_id, worker_id, timeout: lock_timeout)
177
- raise LockNotAcquiredError, instance_id
178
- 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)
179
217
 
180
218
  begin
181
- # Create context
182
- ctx = WorkflowContext.new(
183
- instance_id: instance_id,
184
- workflow_name: workflow_class.workflow_name,
185
- worker_id: worker_id,
186
- storage: storage,
187
- hooks: hooks,
188
- history_cache: history_cache,
189
- replaying: replaying
190
- )
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)
191
221
 
192
222
  # Call hooks
193
223
  hooks&.on_workflow_start&.call(instance_id, workflow_class.workflow_name, input)
@@ -197,70 +227,114 @@ module Shikibu
197
227
  workflow.instance_variable_set(:@pending_compensations, [])
198
228
  workflow.context = ctx
199
229
 
200
- # Symbolize input keys
201
- symbolized_input = symbolize_keys(input)
202
- result = workflow.execute(**symbolized_input)
203
-
204
- # Mark completed
205
- storage.update_instance_status(instance_id, Status::COMPLETED, output_data: result)
206
- storage.clear_compensations(instance_id)
207
-
208
- # Cleanup direct subscriptions
209
- cleanup_subscriptions(ctx)
230
+ result = invoke_workflow(workflow, workflow_class, input, ctx)
210
231
 
211
- # Call hooks
212
- 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?
213
236
 
214
- result
237
+ complete_workflow(instance_id, workflow_class, ctx, result, lock_id)
215
238
  rescue WaitForTimerSignal => e
216
- handle_timer_suspend(instance_id, e)
239
+ handle_timer_suspend(instance_id, e, lock_id)
217
240
  nil
218
241
  rescue WaitForChannelSignal => e
219
- handle_channel_suspend(instance_id, e)
242
+ handle_channel_suspend(instance_id, e, lock_id)
220
243
  nil
221
244
  rescue RecurSignal => e
222
- handle_recur(instance_id, workflow_class, e)
245
+ handle_recur(instance_id, workflow_class, e, lock_id)
223
246
  nil
224
247
  rescue WorkflowCancelledError
225
- storage.update_instance_status(instance_id, Status::CANCELLED)
248
+ storage.update_instance_status(instance_id, Status::CANCELLED, lock_id: lock_id)
226
249
  hooks&.on_workflow_cancelled&.call(instance_id, workflow_class.workflow_name)
227
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
228
260
  rescue StandardError => e
229
- handle_failure(instance_id, workflow_class, workflow, e)
230
- 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
231
267
  ensure
232
- storage.release_lock(instance_id, worker_id)
268
+ finish_run(heartbeat, instance_id, lock_id)
233
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
234
275
  end
235
276
 
236
- def handle_timer_suspend(instance_id, signal)
237
- # Update status
238
- storage.update_instance_status(
239
- instance_id,
240
- Status::WAITING_FOR_TIMER,
241
- current_activity_id: signal.activity_id
242
- )
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
243
288
 
244
- # Register timer
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
297
+
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.
245
312
  storage.register_timer(
246
313
  instance_id: instance_id,
247
314
  timer_id: signal.timer_id,
248
315
  expires_at: signal.expires_at,
249
- activity_id: signal.activity_id
316
+ activity_id: signal.activity_id,
317
+ lock_id: lock_id
250
318
  )
251
- end
252
-
253
- def handle_channel_suspend(instance_id, signal)
254
- # Update status
255
319
  storage.update_instance_status(
256
320
  instance_id,
257
- Status::WAITING_FOR_MESSAGE,
258
- current_activity_id: signal.activity_id
321
+ Status::WAITING_FOR_TIMER,
322
+ current_activity_id: signal.activity_id,
323
+ lock_id: lock_id
259
324
  )
325
+ rescue InstanceTerminatedError
326
+ storage.remove_timer(instance_id: instance_id, timer_id: signal.timer_id)
327
+ raise
328
+ end
260
329
 
261
- # Update subscription with activity_id and timeout
262
- 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(
263
336
  instance_id: instance_id,
337
+ worker_id: lock_id,
264
338
  channel: signal.channel,
265
339
  mode: signal.mode,
266
340
  activity_id: signal.activity_id,
@@ -268,30 +342,20 @@ module Shikibu
268
342
  )
269
343
  end
270
344
 
271
- def handle_recur(instance_id, workflow_class, signal)
272
- # Archive history
273
- storage.archive_history(instance_id)
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)
274
351
 
275
- # Update instance with new input and reset status
276
- storage.update_instance_status(instance_id, Status::RECURRED)
277
-
278
- # Create new instance with continued_from link
279
- new_instance_id = SecureRandom.uuid
280
- storage.create_instance(
281
- instance_id: new_instance_id,
282
- workflow_name: workflow_class.workflow_name,
283
- source_hash: workflow_class.source_hash,
284
- owner_service: 'default',
285
- input_data: signal.new_input,
286
- status: Status::RUNNING
287
- )
288
-
289
- # The new instance will be picked up by the worker
352
+ # The same instance will be picked up by the worker
290
353
  end
291
354
 
292
- def handle_failure(instance_id, workflow_class, workflow, error)
355
+ def handle_failure(instance_id, workflow_class, workflow, error, lock_id)
293
356
  # Record failure in history
294
357
  storage.append_history(
358
+ lock_id: lock_id,
295
359
  instance_id: instance_id,
296
360
  activity_id: 'workflow_failed',
297
361
  event_type: EventType::WORKFLOW_FAILED,
@@ -302,21 +366,104 @@ module Shikibu
302
366
  )
303
367
 
304
368
  # Update status to compensating
305
- storage.update_instance_status(instance_id, Status::COMPENSATING)
369
+ storage.update_instance_status(instance_id, Status::COMPENSATING, lock_id: lock_id)
306
370
 
307
- # Execute compensations via workflow instance (LIFO order)
308
- 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 }
309
375
 
310
376
  # Clear compensation records from database
311
377
  storage.clear_compensations(instance_id)
312
378
 
313
379
  # Update final status
314
- storage.update_instance_status(instance_id, Status::FAILED)
380
+ storage.update_instance_status(instance_id, Status::FAILED, lock_id: lock_id)
315
381
 
316
382
  # Call hooks
317
383
  hooks&.on_workflow_failed&.call(instance_id, workflow_class.workflow_name, error)
318
384
  end
319
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
+
320
467
  def cleanup_subscriptions(ctx)
321
468
  ctx.direct_subscriptions.each do |channel|
322
469
  storage.unsubscribe_from_channel(
@@ -343,7 +490,8 @@ module Shikibu
343
490
  event_type: event_type,
344
491
  result: data&.dig(:result),
345
492
  error_type: data&.dig(:error_type),
346
- error_message: data&.dig(:error_message)
493
+ error_message: data&.dig(:error_message),
494
+ code: data&.dig(:code)
347
495
  }
348
496
  end
349
497
  end