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
@@ -55,15 +55,68 @@ module Shikibu
55
55
  @is_leader
56
56
  end
57
57
 
58
+ # Fire one expired timer (the in-process timer loop and the Sidekiq
59
+ # TimerWorker both come here). Under the instance lock with fenced
60
+ # writes, and only while the instance still waits for a timer, so a stale
61
+ # timer never revives a finished or cancelled instance; a finished
62
+ # instance's timer is deleted. Returns true when the instance was set
63
+ # running, false when it was skipped (retry later while a run holds the
64
+ # lock or the instance is not waiting).
65
+ def fire_timer(timer)
66
+ instance_id = timer[:instance_id]
67
+ timer_id = timer[:timer_id]
68
+ activity_id = timer[:activity_id]
69
+ fired = false
70
+
71
+ with_instance_lock(instance_id) do |lock_id|
72
+ status = storage.get_instance(instance_id)&.dig(:status)
73
+ next unless status == Status::WAITING_FOR_TIMER || finished?(status)
74
+
75
+ storage.transaction do
76
+ unless finished?(status)
77
+ storage.append_history(
78
+ lock_id: lock_id,
79
+ instance_id: instance_id,
80
+ activity_id: activity_id || timer_id,
81
+ event_type: EventType::TIMER_EXPIRED,
82
+ event_data: { timer_id: timer_id, expired_at: Time.now.utc.iso8601 }
83
+ )
84
+ # Never from terminal: the fenced update refuses it
85
+ storage.update_instance_status(instance_id, Status::RUNNING, lock_id: lock_id)
86
+ fired = true
87
+ end
88
+
89
+ # An orphan if the instance finished
90
+ storage.remove_timer(instance_id: instance_id, timer_id: timer_id)
91
+ end
92
+ end
93
+ fired
94
+ rescue InstanceTerminatedError
95
+ false # cancelled meanwhile: the cancel removed the timer
96
+ rescue StandardError => e
97
+ log_error("fire_timer(#{instance_id})", e)
98
+ false
99
+ end
100
+
58
101
  private
59
102
 
103
+ # Generate an epoch-bearing lock-holder identity (worker_id#<random>).
104
+ # A lease lost and re-acquired by the same worker is a different holder;
105
+ # locked_by equality checks then act as fencing tokens.
106
+ def new_lock_identity(worker_id)
107
+ "#{worker_id}##{SecureRandom.hex(8)}"
108
+ end
109
+
60
110
  # Resume workflows that are in 'running' status but not locked
61
111
  def run_workflow_resumption
62
112
  consecutive_empty = 0
63
113
 
64
114
  while @running
65
115
  begin
66
- workflows = storage.find_resumable_workflows(limit: 10)
116
+ lock_id = new_lock_identity(worker_id)
117
+ workflows = storage.claim_resumable_workflows(
118
+ worker_id: lock_id, limit: 10, workflow_names: app.registered_workflows.keys
119
+ )
67
120
 
68
121
  if workflows.empty?
69
122
  consecutive_empty += 1
@@ -74,9 +127,11 @@ module Shikibu
74
127
  else
75
128
  consecutive_empty = 0
76
129
  workflows.each do |wf|
77
- break unless @running
130
+ # Shutting down: hand claimed-but-unstarted instances back
131
+ next storage.release_lock(wf[:instance_id], lock_id) unless @running
78
132
 
79
- resume_workflow_safe(wf[:instance_id])
133
+ # Continue the claim's lock epoch (no second acquisition)
134
+ resume_workflow_safe(wf[:instance_id], lock_id: lock_id)
80
135
  end
81
136
  end
82
137
  rescue StandardError => e
@@ -168,6 +223,40 @@ module Shikibu
168
223
  def run_stale_lock_cleanup
169
224
  while @running && @is_leader
170
225
  begin
226
+ # Backstop: requeue channel waits stranded by the residual
227
+ # missed-wakeup race (publisher scan ran before the wait
228
+ # registration committed).
229
+ begin
230
+ requeued = storage.requeue_channel_waits_with_pending
231
+ warn "[Shikibu::Worker] Requeued #{requeued} channel wait(s) with pending messages" if requeued.positive?
232
+ rescue StandardError => e
233
+ log_error('requeue_channel_waits', e)
234
+ end
235
+
236
+ # Deliver DOWN notifications for terminated actors and free names
237
+ begin
238
+ downs = storage.emit_actor_down_for_terminated
239
+ warn "[Shikibu::Worker] Emitted #{downs} actor DOWN notifications" if downs.positive?
240
+ rescue StandardError => e
241
+ log_error('emit_actor_down', e)
242
+ end
243
+
244
+ begin
245
+ expired = storage.delete_expired_capabilities
246
+ warn "[Shikibu::Worker] Deleted #{expired} expired capabilities" if expired.positive?
247
+ rescue StandardError => e
248
+ log_error('delete_expired_capabilities', e)
249
+ end
250
+
251
+ # Orphan-task reclaim: 'claimed' rows older than the lock lease
252
+ # were abandoned by a crashed claimant — reopen them.
253
+ begin
254
+ reclaimed = storage.reclaim_stale_tasks(max_age_seconds: 300)
255
+ warn "[Shikibu::Worker] Reclaimed #{reclaimed} stale task(s)" if reclaimed.positive?
256
+ rescue StandardError => e
257
+ log_error('reclaim_stale_tasks', e)
258
+ end
259
+
171
260
  stale = storage.find_stale_locked_workflows(stale_threshold_seconds: 300)
172
261
 
173
262
  stale.each do |wf|
@@ -175,10 +264,9 @@ module Shikibu
175
264
 
176
265
  instance_id = wf[:instance_id]
177
266
 
178
- # Force release lock
179
- storage.db[:workflow_instances]
180
- .where(instance_id: instance_id)
181
- .update(locked_by: nil, locked_at: nil, lock_expires_at: nil)
267
+ # Force release only the stale holder the scan saw; a worker that
268
+ # re-acquired the lease meanwhile keeps it.
269
+ next unless storage.force_release_lock(instance_id, wf[:locked_by])
182
270
 
183
271
  # Resume the workflow (like Edda's auto_resume_stale_workflows_periodically)
184
272
  resume_workflow_safe(instance_id)
@@ -252,34 +340,20 @@ module Shikibu
252
340
  log_error('outbox_relay', e)
253
341
  end
254
342
 
255
- def resume_workflow_safe(instance_id)
256
- app.resume_workflow(instance_id)
343
+ def resume_workflow_safe(instance_id, lock_id: nil)
344
+ app.resume_workflow(instance_id, lock_id: lock_id)
257
345
  rescue LockNotAcquiredError
258
346
  # Another worker got it, that's fine
259
347
  rescue StandardError => e
260
348
  log_error("resume_workflow(#{instance_id})", e)
349
+ ensure
350
+ # A claimed lock is normally released by the run itself; release it
351
+ # here if the run never started (e.g. workflow not registered).
352
+ storage.release_lock(instance_id, lock_id) if lock_id
261
353
  end
262
354
 
263
355
  def handle_timer_expired(timer)
264
- instance_id = timer[:instance_id]
265
- timer_id = timer[:timer_id]
266
- activity_id = timer[:activity_id]
267
-
268
- # Record timer expiration in history
269
- storage.append_history(
270
- instance_id: instance_id,
271
- activity_id: activity_id || timer_id,
272
- event_type: EventType::TIMER_EXPIRED,
273
- event_data: { timer_id: timer_id, expired_at: Time.now.iso8601 }
274
- )
275
-
276
- # Remove timer subscription
277
- storage.remove_timer(instance_id: instance_id, timer_id: timer_id)
278
-
279
- # Update status to running for resumption
280
- storage.update_instance_status(instance_id, Status::RUNNING)
281
- rescue StandardError => e
282
- log_error("handle_timer_expired(#{instance_id})", e)
356
+ fire_timer(timer)
283
357
  end
284
358
 
285
359
  def handle_subscription_timeout(sub)
@@ -287,19 +361,37 @@ module Shikibu
287
361
  channel = sub[:channel]
288
362
  activity_id = sub[:activity_id]
289
363
 
290
- # Record timeout in history
291
- storage.append_history(
292
- instance_id: instance_id,
293
- activity_id: activity_id,
294
- event_type: EventType::MESSAGE_TIMEOUT,
295
- event_data: { channel: channel, timed_out_at: Time.now.iso8601 }
296
- )
297
-
298
- # Remove subscription
299
- storage.unsubscribe_from_channel(instance_id: instance_id, channel: channel)
364
+ with_instance_lock(instance_id) do |lock_id|
365
+ # Fire only for the wait the scan saw: not satisfied, re-registered
366
+ # or given a new deadline since.
367
+ current = storage.get_subscription(instance_id: instance_id, channel: channel)
368
+ next unless current && current[:activity_id] == activity_id && current[:timeout_at] == sub[:timeout_at]
369
+
370
+ waiting = storage.get_instance(instance_id)&.dig(:status) == Status::WAITING_FOR_MESSAGE
371
+ storage.transaction do
372
+ if waiting
373
+ # Record timeout in history
374
+ storage.append_history(
375
+ lock_id: lock_id,
376
+ instance_id: instance_id,
377
+ activity_id: activity_id,
378
+ event_type: EventType::MESSAGE_TIMEOUT,
379
+ event_data: { channel: channel, timed_out_at: Time.now.utc.iso8601 }
380
+ )
381
+
382
+ # Update status to running for resumption (never from terminal)
383
+ storage.update_instance_status(instance_id, Status::RUNNING, lock_id: lock_id)
384
+ end
300
385
 
301
- # Update status to running for resumption
302
- storage.update_instance_status(instance_id, Status::RUNNING)
386
+ # Clear the wait (fired, or stale when not waiting); the
387
+ # subscription (and its broadcast cursor) stays
388
+ storage.db[:channel_subscriptions]
389
+ .where(instance_id: instance_id, channel: channel)
390
+ .update(activity_id: nil, timeout_at: nil)
391
+ end
392
+ end
393
+ rescue InstanceTerminatedError
394
+ nil # cancelled meanwhile: the cancel cleared the wait
303
395
  rescue StandardError => e
304
396
  log_error("handle_subscription_timeout(#{instance_id})", e)
305
397
  end
@@ -326,46 +418,36 @@ module Shikibu
326
418
 
327
419
  next unless message
328
420
 
329
- deliver_message(sub, message)
330
- delivered_count += 1
421
+ # Delivery holds the instance lock, fences its writes and consumes
422
+ # the message (cursor advance / competing delete).
423
+ delivered = storage.deliver_channel_message(
424
+ instance_id: sub[:instance_id],
425
+ channel: sub[:channel],
426
+ message_id: message[:message_id],
427
+ worker_id: worker_id
428
+ )
429
+ delivered_count += 1 if delivered
331
430
  end
332
431
 
333
432
  delivered_count
334
433
  end
335
434
 
336
- def deliver_message(sub, message)
337
- instance_id = sub[:instance_id]
338
- activity_id = sub[:activity_id]
339
- mode = sub[:mode]
340
-
341
- # For competing mode, try to claim
342
- if (mode == ChannelMode::COMPETING) && !storage.claim_message(message_id: message[:message_id],
343
- instance_id: instance_id)
344
- return
345
- end
346
-
347
- # Record message received in history
348
- storage.append_history(
349
- instance_id: instance_id,
350
- activity_id: activity_id,
351
- event_type: EventType::CHANNEL_MESSAGE_RECEIVED,
352
- event_data: {
353
- channel: sub[:channel],
354
- message_id: message[:message_id],
355
- data: message[:data],
356
- metadata: message[:metadata]
357
- }
358
- )
435
+ # Terminal or deleted instance: its timers/waits are orphans
436
+ def finished?(status)
437
+ status.nil? || Status::TERMINAL.include?(status)
438
+ end
359
439
 
360
- # Clear activity_id from subscription (no longer waiting)
361
- storage.db[:channel_subscriptions]
362
- .where(instance_id: instance_id, channel: sub[:channel])
363
- .update(activity_id: nil, timeout_at: nil)
440
+ # Run block holding a fresh epoch lock on the instance; returns nil
441
+ # without running it when the instance is locked elsewhere.
442
+ def with_instance_lock(instance_id)
443
+ lock_id = new_lock_identity(worker_id)
444
+ return nil unless storage.try_acquire_lock(instance_id, lock_id)
364
445
 
365
- # Update status to running for resumption
366
- storage.update_instance_status(instance_id, Status::RUNNING)
367
- rescue StandardError => e
368
- log_error("deliver_message(#{instance_id})", e)
446
+ begin
447
+ yield lock_id
448
+ ensure
449
+ storage.release_lock(instance_id, lock_id)
450
+ end
369
451
  end
370
452
 
371
453
  def calculate_backoff(consecutive_empty)
@@ -167,8 +167,8 @@ module Shikibu
167
167
  # @param input [Hash] Input parameters
168
168
  # @param instance_id [String, nil] Optional custom instance ID
169
169
  # @return [String] The instance ID
170
- def start(app, instance_id: nil, **input)
171
- app.start_workflow(self, instance_id: instance_id, **input)
170
+ def start(app, instance_id: nil, sandboxed: false, **input)
171
+ app.start_workflow(self, instance_id: instance_id, sandboxed: sandboxed, **input)
172
172
  end
173
173
 
174
174
  # Run workflow using global Shikibu.app
@@ -214,12 +214,12 @@ module Shikibu
214
214
  # @return [Object] Activity result
215
215
  # @raise [ArgumentError] If returns is not a valid typed class
216
216
  def activity(name, retry_policy: nil, returns: nil, &)
217
+ ctx.raise_if_run_aborted!
217
218
  if returns && !TypedPayload.typed_class?(returns)
218
219
  raise ArgumentError, "returns: must be a typed class (Dry::Struct, Data, or duck-typed), got #{returns.inspect}"
219
220
  end
220
221
 
221
222
  activity_id = ctx.generate_activity_id(name.to_s)
222
- ctx.current_activity_id = activity_id
223
223
 
224
224
  # Check for cached result during replay
225
225
  if ctx.replaying? && ctx.cached_result?(activity_id)
@@ -246,8 +246,6 @@ module Shikibu
246
246
  result = execute_activity(activity_id, name.to_s, retry_policy || RetryPolicy.default, &)
247
247
  ctx.record_last_activity_id(activity_id)
248
248
  result
249
- ensure
250
- ctx.current_activity_id = nil
251
249
  end
252
250
 
253
251
  # Register a compensation action to run on failure (Romancy/Edda compatible)
@@ -307,20 +305,20 @@ module Shikibu
307
305
  ctx.unsubscribe(channel)
308
306
  end
309
307
 
310
- def receive(channel, timeout: nil, mode: ChannelMode::BROADCAST)
311
- ctx.receive(channel, timeout: timeout, mode: mode)
308
+ def receive(channel, timeout: nil, mode: ChannelMode::BROADCAST, capability_token: nil)
309
+ ctx.receive(channel, timeout: timeout, mode: mode, capability_token: capability_token)
312
310
  end
313
311
 
314
- def try_receive(channel, mode: ChannelMode::BROADCAST)
315
- ctx.try_receive(channel, mode: mode)
312
+ def try_receive(channel, mode: ChannelMode::BROADCAST, capability_token: nil)
313
+ ctx.try_receive(channel, mode: mode, capability_token: capability_token)
316
314
  end
317
315
 
318
- def publish(channel, data, metadata: nil)
319
- ctx.publish(channel, data, metadata: metadata)
316
+ def publish(channel, data, metadata: nil, capability_token: nil)
317
+ ctx.publish(channel, data, metadata: metadata, capability_token: capability_token)
320
318
  end
321
319
 
322
- def send_to(target_instance_id, channel, data)
323
- ctx.send_to(target_instance_id, channel, data)
320
+ def send_to(target_instance_id, channel, data, metadata: nil, capability_token: nil)
321
+ ctx.send_to(target_instance_id, channel, data, metadata: metadata, capability_token: capability_token)
324
322
  end
325
323
 
326
324
  def recur(**new_input)
@@ -376,10 +374,18 @@ module Shikibu
376
374
  def execute_single_compensation(comp, compensation_id)
377
375
  # Execute compensation and record result atomically in a transaction
378
376
  ctx.storage.transaction do
379
- comp[:block].call
377
+ # Mark as in-activity so FS ops are allowed inside compensations
378
+ prev_activity_id = ctx.current_activity_id
379
+ ctx.current_activity_id = "compensation:#{compensation_id || comp[:activity_id]}"
380
+ begin
381
+ comp[:block].call
382
+ ensure
383
+ ctx.current_activity_id = prev_activity_id
384
+ end
380
385
 
381
386
  # Record successful compensation (Romancy/Edda compatible format)
382
387
  ctx.storage.append_history(
388
+ lock_id: ctx.lock_id,
383
389
  instance_id: ctx.instance_id,
384
390
  activity_id: "compensation:#{compensation_id || comp[:activity_id]}",
385
391
  event_type: EventType::COMPENSATION_EXECUTED,
@@ -393,6 +399,7 @@ module Shikibu
393
399
  rescue StandardError => e
394
400
  # Record failed compensation but continue with others (outside transaction)
395
401
  ctx.storage.append_history(
402
+ lock_id: ctx.lock_id,
396
403
  instance_id: ctx.instance_id,
397
404
  activity_id: "compensation:#{compensation_id || comp[:activity_id]}",
398
405
  event_type: EventType::COMPENSATION_FAILED,
@@ -406,6 +413,17 @@ module Shikibu
406
413
  )
407
414
  end
408
415
 
416
+ # Record a completed activity in history, fenced by the lock epoch
417
+ def record_activity_completed(ctx, activity_id, event_data:)
418
+ ctx.storage.append_history(
419
+ lock_id: ctx.lock_id,
420
+ instance_id: ctx.instance_id,
421
+ activity_id: activity_id,
422
+ event_type: EventType::ACTIVITY_COMPLETED,
423
+ event_data: event_data
424
+ )
425
+ end
426
+
409
427
  def execute_activity(activity_id, name, retry_policy, &block)
410
428
  attempt = 0
411
429
  started_at = Time.now
@@ -413,20 +431,27 @@ module Shikibu
413
431
 
414
432
  loop do
415
433
  attempt += 1
434
+ # Only an error from the body is the activity's outcome. One while
435
+ # beginning, recording or committing the attempt is a storage error:
436
+ # the run ends instead and a later run executes the activity again.
437
+ phase = :body # a hook error stays an activity failure
416
438
 
417
439
  begin
418
440
  # Call hooks
419
441
  ctx.hooks&.on_activity_start&.call(ctx.instance_id, activity_id, name, attempt)
420
442
 
421
- # Execute activity and record result atomically in a transaction
422
- result = ctx.storage.transaction do
423
- res = block.call
443
+ # Execute activity and record result atomically in a transaction.
444
+ # current_activity_id marks the executing body (FS gate, direct
445
+ # kernel calls).
446
+ phase = :begin
447
+ result = ctx.storage.attempt_transaction do
448
+ phase = :body
449
+ res = with_activity_body(activity_id, &block)
450
+ phase = :record
424
451
 
425
452
  # Record successful result (atomic with activity execution)
426
- ctx.storage.append_history(
427
- instance_id: ctx.instance_id,
428
- activity_id: activity_id,
429
- event_type: EventType::ACTIVITY_COMPLETED,
453
+ record_activity_completed(
454
+ ctx, activity_id,
430
455
  event_data: { result: res }
431
456
  )
432
457
 
@@ -443,33 +468,22 @@ module Shikibu
443
468
  ctx.hooks&.on_activity_complete&.call(ctx.instance_id, activity_id, name, result, false)
444
469
 
445
470
  return result
471
+ rescue LockLostError => e
472
+ # Lease lost: abort the run without retrying or further writes
473
+ ctx.poison_run!(e)
474
+ raise
475
+ rescue WorkflowCancelledError
476
+ # Cancellation ends the run; it is never an activity failure.
477
+ raise
446
478
  rescue StandardError => e
479
+ raise if ctx.storage.nested_write_conflict?(e) # the outer attempt restarts
480
+
481
+ ctx.abort_run!(e) unless phase == :body
447
482
  last_error = e
448
483
 
449
484
  # Check if retryable
450
485
  unless retry_policy.retryable?(e) && retry_policy.should_retry?(attempt, started_at)
451
- # Record failure
452
- ctx.storage.append_history(
453
- instance_id: ctx.instance_id,
454
- activity_id: activity_id,
455
- event_type: EventType::ACTIVITY_FAILED,
456
- event_data: {
457
- error_type: e.class.name,
458
- error_message: e.message,
459
- attempts: attempt
460
- }
461
- )
462
-
463
- # Cache for replay
464
- ctx.cache_result(activity_id, {
465
- event_type: EventType::ACTIVITY_FAILED,
466
- error_type: e.class.name,
467
- error_message: e.message
468
- })
469
-
470
- # Call hooks
471
- ctx.hooks&.on_activity_failed&.call(ctx.instance_id, activity_id, name, e, attempt)
472
-
486
+ record_activity_failure(activity_id, name, e, attempt)
473
487
  raise
474
488
  end
475
489
 
@@ -483,19 +497,63 @@ module Shikibu
483
497
  end
484
498
  end
485
499
 
500
+ # Record the failure the activity gave up with. Failing to record it is
501
+ # a storage error, not an outcome: the run ends (lock loss included).
502
+ def record_activity_failure(activity_id, name, error, attempt)
503
+ begin
504
+ ctx.storage.append_history(
505
+ lock_id: ctx.lock_id,
506
+ instance_id: ctx.instance_id,
507
+ activity_id: activity_id,
508
+ event_type: EventType::ACTIVITY_FAILED,
509
+ event_data: {
510
+ error_type: error.class.name,
511
+ error_message: error.message,
512
+ attempts: attempt
513
+ }
514
+ )
515
+ rescue LockLostError => e
516
+ ctx.poison_run!(e)
517
+ raise
518
+ rescue StandardError => e
519
+ ctx.abort_run!(e)
520
+ end
521
+ ctx.cache_result(activity_id, {
522
+ event_type: EventType::ACTIVITY_FAILED,
523
+ error_type: error.class.name,
524
+ error_message: error.message
525
+ })
526
+ ctx.hooks&.on_activity_failed&.call(ctx.instance_id, activity_id, name, error, attempt)
527
+ end
528
+
529
+ def with_activity_body(activity_id)
530
+ previous = ctx.current_activity_id
531
+ ctx.current_activity_id = activity_id
532
+ yield
533
+ ensure
534
+ ctx.current_activity_id = previous
535
+ end
536
+
486
537
  def handle_cached_result(activity_id, cached)
487
538
  name = activity_id.split(':').first
488
539
  ctx.hooks&.on_activity_complete&.call(ctx.instance_id, activity_id, name, cached[:result], true)
489
540
  end
490
541
 
542
+ # Rebuild a recorded activity failure as its error class; a name that is
543
+ # not a StandardError class (or cannot take just a message) replays as a
544
+ # StandardError with the recorded message.
491
545
  def reconstruct_error(cached)
492
546
  error_class = begin
493
- Object.const_get(cached[:error_type])
494
- rescue StandardError
495
- StandardError
547
+ Object.const_get(cached[:error_type].to_s)
548
+ rescue NameError
549
+ nil
550
+ end
551
+ error_class = StandardError unless error_class.is_a?(Class) && error_class <= StandardError
552
+ begin
553
+ error_class.new(cached[:error_message])
554
+ rescue ArgumentError
555
+ StandardError.new(cached[:error_message])
496
556
  end
497
-
498
- error_class.new(cached[:error_message])
499
557
  end
500
558
  end
501
559
  end
data/lib/shikibu.rb CHANGED
@@ -131,6 +131,10 @@ require_relative 'shikibu/notify/notify_base'
131
131
  require_relative 'shikibu/notify/wake_event'
132
132
  require_relative 'shikibu/locking'
133
133
  require_relative 'shikibu/channels'
134
+ require_relative 'shikibu/actors'
135
+ require_relative 'shikibu/blobs'
136
+ require_relative 'shikibu/fs'
137
+ require_relative 'shikibu/tasks'
134
138
  require_relative 'shikibu/context'
135
139
  require_relative 'shikibu/typed_payload'
136
140
  require_relative 'shikibu/workflow'