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
@@ -0,0 +1,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ # Module to detect and handle typed payload classes
5
+ # Supports dry-struct, Ruby 3.2+ Data classes, and duck-typed objects
6
+ #
7
+ # @example with dry-struct
8
+ # require 'dry-struct'
9
+ # class OrderInput < Dry::Struct
10
+ # attribute :order_id, Types::String
11
+ # attribute :amount, Types::Coercible::Decimal
12
+ # end
13
+ #
14
+ # TypedPayload.typed_class?(OrderInput) # => true
15
+ # TypedPayload.to_h(OrderInput.new(order_id: '123', amount: 99.99))
16
+ # # => { order_id: '123', amount: 99.99 }
17
+ #
18
+ # @example with Data class
19
+ # OrderInput = Data.define(:order_id, :amount)
20
+ # TypedPayload.typed_class?(OrderInput) # => true
21
+ #
22
+ module TypedPayload
23
+ class << self
24
+ # Check if dry-struct is available
25
+ # @return [Boolean]
26
+ def dry_struct_available?
27
+ return @dry_struct_available if defined?(@dry_struct_available)
28
+
29
+ @dry_struct_available = begin
30
+ require 'dry-struct'
31
+ true
32
+ rescue LoadError
33
+ false
34
+ end
35
+ end
36
+
37
+ # Check if an object is a typed payload class (not instance)
38
+ # @param obj [Object] Object to check
39
+ # @return [Boolean]
40
+ def typed_class?(obj)
41
+ return false unless obj.is_a?(Class)
42
+
43
+ # Check for dry-struct
44
+ return true if dry_struct_class?(obj)
45
+
46
+ # Check for Ruby 3.2+ Data class
47
+ return true if data_class?(obj)
48
+
49
+ # Check for duck-typed class with required methods
50
+ duck_typed_class?(obj)
51
+ end
52
+
53
+ # Check if an object is a typed payload instance
54
+ # @param obj [Object] Object to check
55
+ # @return [Boolean]
56
+ def typed_instance?(obj)
57
+ return true if dry_struct_instance?(obj)
58
+ return true if data_instance?(obj)
59
+
60
+ duck_typed_instance?(obj)
61
+ end
62
+
63
+ # Serialize a typed instance to a hash
64
+ # @param obj [Object] Typed instance or any object
65
+ # @return [Hash, Object] Serialized hash or original object
66
+ def to_h(obj)
67
+ deep_serialize(obj)
68
+ end
69
+
70
+ # Deserialize a hash to a typed instance
71
+ # @param hash [Hash] Hash to deserialize
72
+ # @param type_class [Class] Target type class
73
+ # @return [Object] Typed instance or original hash
74
+ def from_h(hash, type_class)
75
+ return hash unless typed_class?(type_class)
76
+ return hash unless hash.is_a?(Hash)
77
+
78
+ # Symbolize keys for compatibility
79
+ symbolized = deep_symbolize_keys(hash)
80
+
81
+ # All typed classes support .new(**hash) interface
82
+ type_class.new(**symbolized)
83
+ end
84
+
85
+ # Deserialize an array of typed objects
86
+ # @param array [Array<Hash>] Array of hashes
87
+ # @param element_type [Class] Element type class
88
+ # @return [Array] Array of typed instances
89
+ def from_array(array, element_type)
90
+ return array unless array.is_a?(Array)
91
+ return array unless typed_class?(element_type)
92
+
93
+ array.map do |item|
94
+ item.is_a?(Hash) ? from_h(item, element_type) : item
95
+ end
96
+ end
97
+
98
+ private
99
+
100
+ def dry_struct_class?(obj)
101
+ return false unless dry_struct_available?
102
+
103
+ obj.is_a?(Class) && obj < Dry::Struct
104
+ end
105
+
106
+ def dry_struct_instance?(obj)
107
+ return false unless dry_struct_available?
108
+
109
+ obj.is_a?(Dry::Struct)
110
+ end
111
+
112
+ def data_class?(obj)
113
+ return false unless defined?(Data)
114
+
115
+ obj.is_a?(Class) && obj < Data
116
+ end
117
+
118
+ def data_instance?(obj)
119
+ return false unless defined?(Data)
120
+
121
+ obj.is_a?(Data)
122
+ end
123
+
124
+ def duck_typed_class?(obj)
125
+ # A class is considered typed if it has new and instances have to_h
126
+ # but exclude Hash itself
127
+ return false if obj == Hash
128
+
129
+ obj.respond_to?(:new) &&
130
+ obj.method_defined?(:to_h)
131
+ end
132
+
133
+ def duck_typed_instance?(obj)
134
+ # An instance is typed if it has to_h but is not a Hash/Array
135
+ return false if obj.is_a?(Hash)
136
+ return false if obj.is_a?(Array)
137
+ return false unless obj.respond_to?(:to_h)
138
+
139
+ # Additional check: should have proper to_h implementation
140
+ # (not just Object#to_h which doesn't exist or returns weird things)
141
+ begin
142
+ result = obj.to_h
143
+ result.is_a?(Hash)
144
+ rescue StandardError
145
+ false
146
+ end
147
+ end
148
+
149
+ # Recursively serialize typed objects to hashes
150
+ # Note: Symbols are preserved here. They are converted to strings
151
+ # only during JSON serialization in the storage layer.
152
+ def deep_serialize(obj)
153
+ case obj
154
+ when Hash
155
+ obj.transform_values { |v| deep_serialize(v) }
156
+ when Array
157
+ obj.map { |v| deep_serialize(v) }
158
+ when ->(o) { dry_struct_instance?(o) || data_instance?(o) }
159
+ deep_serialize(obj.to_h)
160
+ when Time, DateTime
161
+ obj.iso8601
162
+ when Date
163
+ obj.to_s
164
+ when BigDecimal
165
+ obj.to_s('F')
166
+ else
167
+ # Symbols, Integers, Strings, etc. are preserved as-is
168
+ obj
169
+ end
170
+ end
171
+
172
+ # Recursively symbolize hash keys
173
+ def deep_symbolize_keys(hash)
174
+ return hash unless hash.is_a?(Hash)
175
+
176
+ symbolized = hash.transform_keys do |key|
177
+ key.is_a?(String) ? key.to_sym : key
178
+ end
179
+ symbolized.transform_values do |value|
180
+ case value
181
+ when Hash then deep_symbolize_keys(value)
182
+ when Array then value.map { |v| v.is_a?(Hash) ? deep_symbolize_keys(v) : v }
183
+ else value
184
+ end
185
+ end
186
+ end
187
+ end
188
+ end
189
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Shikibu
4
- VERSION = '0.2.0'
4
+ VERSION = '0.4.0'
5
5
  end
@@ -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)