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,19 +3,33 @@
3
3
  require 'sequel'
4
4
  require 'json'
5
5
  require 'securerandom'
6
+ require_relative 'channel_ops'
7
+ require_relative 'cursor_ops'
8
+ require_relative 'actor_ops'
9
+ require_relative 'sqlite_ops'
6
10
 
7
11
  module Shikibu
8
12
  module Storage
9
13
  # Sequel-based storage implementation
10
14
  class SequelStorage
15
+ include ChannelOps
16
+ include BroadcastCursorOps
17
+ include ActorOps
18
+ include SqliteOps
19
+
11
20
  attr_reader :db
12
21
  attr_accessor :notify_enabled
13
22
 
14
23
  DEFAULT_LOCK_TIMEOUT = 300 # 5 minutes
24
+ RESUMABLE_STATUSES = [Status::RUNNING, Status::RECURRED].freeze
15
25
 
16
26
  def initialize(database_url, auto_migrate: false)
17
27
  @database_url = database_url
18
- @db = Sequel.connect(database_url)
28
+ @db = Sequel.connect(database_url, **session_options(database_url))
29
+ # Every timestamp is a UTC wall-clock value (the cross-language
30
+ # contract): Time values are written in UTC and naive TIMESTAMP
31
+ # columns read back from PostgreSQL/MySQL are interpreted as UTC.
32
+ @db.timezone = :utc
19
33
  @notify_enabled = false
20
34
 
21
35
  # Enable extensions based on database type
@@ -44,10 +58,21 @@ module Shikibu
44
58
  # @raise [RuntimeError] If called outside of a transaction
45
59
  def register_post_commit_callback(&block)
46
60
  raise 'Not in transaction' unless in_transaction?
61
+ # A raw Sequel transaction (not opened via #transaction) has no
62
+ # callback list of ours; defer to Sequel's own commit hook.
63
+ return @db.after_commit(&block) if transaction_state[:depth].zero?
47
64
 
48
65
  transaction_state[:callbacks] << block
49
66
  end
50
67
 
68
+ # Run block after the current transaction commits (dropped on
69
+ # rollback), or immediately when no transaction is open.
70
+ def after_commit(&)
71
+ return yield unless in_transaction?
72
+
73
+ register_post_commit_callback(&)
74
+ end
75
+
51
76
  def transaction(&)
52
77
  state = transaction_state
53
78
  state[:depth] += 1
@@ -82,13 +107,12 @@ module Shikibu
82
107
 
83
108
  def save_workflow_definition(workflow_name:, source_hash:, source_code:)
84
109
  if mysql?
85
- # MySQL: Use INSERT IGNORE + UPDATE
86
- @db[:workflow_definitions].insert_ignore.insert(
87
- workflow_name: workflow_name,
88
- source_hash: source_hash,
89
- source_code: source_code,
90
- created_at: current_timestamp
91
- )
110
+ # The same name and hash is the same source: a duplicate is already there
111
+ insert_unless_exists(:workflow_definitions, %i[workflow_name source_hash],
112
+ workflow_name: workflow_name,
113
+ source_hash: source_hash,
114
+ source_code: source_code,
115
+ created_at: current_timestamp)
92
116
  else
93
117
  # PostgreSQL/SQLite: Use ON CONFLICT
94
118
  @db[:workflow_definitions].insert_conflict(
@@ -119,8 +143,23 @@ module Shikibu
119
143
  source_hash:,
120
144
  owner_service:,
121
145
  input_data:,
122
- status: Status::RUNNING
146
+ status: Status::RUNNING,
147
+ continued_from: nil,
148
+ sandboxed: false,
149
+ parent_instance_id: nil
123
150
  )
151
+ unless sandboxed
152
+ [parent_instance_id, continued_from].compact.uniq.each do |parent_id|
153
+ parent_sandboxed = @db[:workflow_instances].where(instance_id: parent_id).get(:sandboxed)
154
+ raise ArgumentError, "parent instance #{parent_id} not found" if parent_sandboxed.nil?
155
+
156
+ if parent_sandboxed.to_i != 0
157
+ sandboxed = true
158
+ break
159
+ end
160
+ end
161
+ end
162
+
124
163
  @db[:workflow_instances].insert(
125
164
  instance_id: instance_id,
126
165
  workflow_name: workflow_name,
@@ -129,6 +168,8 @@ module Shikibu
129
168
  framework: FRAMEWORK,
130
169
  status: status,
131
170
  input_data: serialize_json(input_data),
171
+ continued_from: continued_from,
172
+ sandboxed: sandboxed ? 1 : 0,
132
173
  started_at: current_timestamp,
133
174
  updated_at: current_timestamp
134
175
  )
@@ -142,7 +183,8 @@ module Shikibu
142
183
  deserialize_instance(row)
143
184
  end
144
185
 
145
- def update_instance_status(instance_id, status, output_data: nil, current_activity_id: nil)
186
+ def update_instance_status(instance_id, status, output_data: nil, current_activity_id: nil,
187
+ lock_id: nil)
146
188
  updates = {
147
189
  status: status,
148
190
  updated_at: current_timestamp
@@ -150,9 +192,56 @@ module Shikibu
150
192
  updates[:output_data] = serialize_json(output_data) if output_data
151
193
  updates[:current_activity_id] = current_activity_id if current_activity_id
152
194
 
153
- @db[:workflow_instances]
154
- .where(instance_id: instance_id)
155
- .update(updates)
195
+ dataset = @db[:workflow_instances].where(instance_id: instance_id)
196
+ dataset = dataset.where(locked_by: lock_id) if lock_id
197
+ # Terminal statuses are absorbing: never flip back to running/waiting
198
+ # or to another terminal status; rewriting the same one is a no-op.
199
+ dataset = dataset.where(Sequel.|({ status: status }, Sequel.~(status: Status::TERMINAL)))
200
+ changed = dataset.update(updates)
201
+ raise_status_write_refused(instance_id, lock_id) if lock_id && changed.zero?
202
+
203
+ changed.positive?
204
+ end
205
+
206
+ # Cancel a cancellable instance and drop its timers and channel
207
+ # subscriptions so nothing can resume it. Returns true if cancelled.
208
+ # Compensating instances are not cancellable: their compensations must finish.
209
+ def cancel_instance(instance_id)
210
+ @db.transaction do
211
+ changed = @db[:workflow_instances]
212
+ .where(instance_id: instance_id, status: Status::CANCELLABLE)
213
+ .update(status: Status::CANCELLED, updated_at: current_timestamp)
214
+ next false if changed.zero?
215
+
216
+ @db[:workflow_timer_subscriptions].where(instance_id: instance_id).delete
217
+ @db[:channel_subscriptions].where(instance_id: instance_id).delete
218
+ true
219
+ end
220
+ end
221
+
222
+ # End one recur iteration in a single fenced transaction. The lock proof
223
+ # inside archive_history happens before any cleanup, so a stale run rolls
224
+ # everything back. channel_delivery_cursors deliberately survive: broadcast
225
+ # progress is part of the instance identity, not of one iteration's waits.
226
+ def prepare_recur(instance_id:, input_data:, lock_id:)
227
+ transaction do
228
+ archive_history(instance_id, lock_id: lock_id)
229
+ @db[:channel_subscriptions].where(instance_id: instance_id).delete
230
+ @db[:workflow_timer_subscriptions].where(instance_id: instance_id).delete
231
+ @db[:workflow_group_memberships].where(instance_id: instance_id).delete
232
+ clear_compensations(instance_id)
233
+
234
+ changed = @db[:workflow_instances]
235
+ .where(instance_id: instance_id, locked_by: lock_id)
236
+ .exclude(status: Status::TERMINAL)
237
+ .update(
238
+ status: Status::RECURRED,
239
+ input_data: serialize_json(input_data),
240
+ current_activity_id: nil,
241
+ updated_at: current_timestamp
242
+ )
243
+ raise_status_write_refused(instance_id, lock_id) if changed.zero?
244
+ end
156
245
  end
157
246
 
158
247
  def list_instances(limit: 100, offset: 0, status_filter: nil, workflow_name: nil)
@@ -166,7 +255,7 @@ module Shikibu
166
255
 
167
256
  def find_resumable_workflows(limit: 10)
168
257
  @db[:workflow_instances]
169
- .where(status: Status::RUNNING)
258
+ .where(status: RESUMABLE_STATUSES)
170
259
  .where(locked_by: nil)
171
260
  .where(framework: FRAMEWORK)
172
261
  .order(:updated_at)
@@ -175,10 +264,44 @@ module Shikibu
175
264
  .map(&:to_h)
176
265
  end
177
266
 
267
+ # Atomically claim resumable workflows (status='running', unlocked):
268
+ # select candidates under FOR UPDATE SKIP LOCKED (Postgres/MySQL) then
269
+ # stamp the caller's lock identity, in one transaction. Returned rows
270
+ # are already locked by worker_id. workflow_names limits the claim to
271
+ # the workflows this worker has registered (nil = any): claiming what
272
+ # it cannot run only to release it again would starve the instance.
273
+ # No source-hash filter: a resume runs the registered class whatever
274
+ # hash the instance was started under.
275
+ def claim_resumable_workflows(worker_id:, limit: 10, timeout: DEFAULT_LOCK_TIMEOUT, workflow_names: nil)
276
+ now = current_timestamp
277
+ expires = now + timeout
278
+
279
+ immediate_transaction do
280
+ dataset = @db[:workflow_instances]
281
+ .where(status: RESUMABLE_STATUSES)
282
+ .where(locked_by: nil)
283
+ .where(framework: FRAMEWORK)
284
+ .order(:updated_at)
285
+ .limit(limit)
286
+ dataset = dataset.where(workflow_name: workflow_names) if workflow_names
287
+ dataset = dataset.for_update.skip_locked unless @db.database_type == :sqlite
288
+
289
+ rows = dataset.select(:instance_id, :workflow_name, :source_hash).all
290
+ return [] if rows.empty?
291
+
292
+ ids = rows.map { |r| r[:instance_id] }
293
+ @db[:workflow_instances]
294
+ .where(instance_id: ids)
295
+ .update(locked_by: worker_id, locked_at: now, lock_expires_at: expires, updated_at: now)
296
+
297
+ rows.map(&:to_h)
298
+ end
299
+ end
300
+
178
301
  def find_stale_locked_workflows(stale_threshold_seconds: 300)
179
- threshold = Time.now - stale_threshold_seconds
302
+ threshold = current_timestamp - stale_threshold_seconds
180
303
  @db[:workflow_instances]
181
- .where(status: Status::RUNNING)
304
+ .where(status: RESUMABLE_STATUSES)
182
305
  .where { lock_expires_at < threshold }
183
306
  .where(framework: FRAMEWORK)
184
307
  .select(:instance_id, :workflow_name, :locked_by)
@@ -190,55 +313,28 @@ module Shikibu
190
313
  # ============================================
191
314
 
192
315
  def try_acquire_lock(instance_id, worker_id, timeout: DEFAULT_LOCK_TIMEOUT)
193
- now = Time.now
316
+ now = current_timestamp
194
317
  expires_at = now + timeout
195
318
 
196
- if supports_skip_locked?
197
- # PostgreSQL/MySQL: Use SELECT FOR UPDATE SKIP LOCKED
198
- # This prevents blocking when another worker holds the lock
199
- @db.transaction do
200
- row = @db[:workflow_instances]
201
- .where(instance_id: instance_id)
202
- .for_update
203
- .skip_locked
204
- .first
205
-
206
- # Row is locked by another transaction, skip
207
- return false unless row
208
-
209
- # Check if lock is available (not locked or expired)
210
- return false if row[:locked_by] && row[:lock_expires_at] && row[:lock_expires_at] > now
211
-
212
- @db[:workflow_instances]
213
- .where(instance_id: instance_id)
214
- .update(
215
- locked_by: worker_id,
216
- locked_at: now,
217
- lock_expires_at: expires_at,
218
- lock_timeout_seconds: timeout
219
- )
220
-
221
- true
222
- end
223
- else
224
- # SQLite: Use atomic UPDATE (table-level locking)
225
- affected = @db[:workflow_instances]
226
- .where(instance_id: instance_id)
227
- .where(
228
- Sequel.|(
229
- { locked_by: nil },
230
- Sequel.lit('lock_expires_at < ?', now)
231
- )
232
- )
233
- .update(
234
- locked_by: worker_id,
235
- locked_at: now,
236
- lock_expires_at: expires_at,
237
- lock_timeout_seconds: timeout
319
+ # Single conditional UPDATE: claim the row only when it is unlocked
320
+ # or its lease has expired. Atomic on all dialects — no SELECT FOR
321
+ # UPDATE needed, and it cannot block on another claimant's row lock.
322
+ affected = @db[:workflow_instances]
323
+ .where(instance_id: instance_id)
324
+ .where(
325
+ Sequel.|(
326
+ { locked_by: nil },
327
+ Sequel.lit('lock_expires_at < ?', now)
238
328
  )
329
+ )
330
+ .update(
331
+ locked_by: worker_id,
332
+ locked_at: now,
333
+ lock_expires_at: expires_at,
334
+ lock_timeout_seconds: timeout
335
+ )
239
336
 
240
- affected.positive?
241
- end
337
+ affected.positive?
242
338
  end
243
339
 
244
340
  def release_lock(instance_id, worker_id)
@@ -253,7 +349,7 @@ module Shikibu
253
349
  end
254
350
 
255
351
  def refresh_lock(instance_id, worker_id, timeout: DEFAULT_LOCK_TIMEOUT)
256
- now = Time.now
352
+ now = current_timestamp
257
353
  expires_at = now + timeout
258
354
 
259
355
  affected = @db[:workflow_instances]
@@ -266,42 +362,68 @@ module Shikibu
266
362
  affected.positive?
267
363
  end
268
364
 
269
- def lock_held_by?(instance_id, worker_id)
270
- row = @db[:workflow_instances]
271
- .where(instance_id: instance_id)
272
- .select(:locked_by, :lock_expires_at)
273
- .first
365
+ # Lock proof (fencing check): touch the row only while lock_id still
366
+ # holds it. Like any update of the row it locks it until the
367
+ # transaction ends, so what follows in the transaction is ordered
368
+ # against a lease steal, and a run that lost its lease stops here.
369
+ # @raise [LockLostError] unless lock_id holds the instance
370
+ def assert_lock_held!(instance_id, lock_id)
371
+ changed = @db[:workflow_instances]
372
+ .where(instance_id: instance_id, locked_by: lock_id)
373
+ .update(updated_at: current_timestamp)
374
+ raise LockLostError, instance_id if changed.zero?
375
+ end
274
376
 
275
- return false unless row
276
- return false if row[:locked_by] != worker_id
277
- return false if row[:lock_expires_at] && row[:lock_expires_at] < Time.now
377
+ def lock_held_by?(instance_id, worker_id)
378
+ # Compare in SQL: SQLite returns timestamps as strings.
379
+ now = current_timestamp
380
+ @db[:workflow_instances]
381
+ .where(instance_id: instance_id, locked_by: worker_id)
382
+ .where(Sequel.|({ lock_expires_at: nil }, Sequel.lit('lock_expires_at >= ?', now)))
383
+ .any?
384
+ end
278
385
 
279
- true
386
+ # Stale-lock sweep: release the lease only if it is still held by the
387
+ # holder the sweep observed (a fresh re-acquisition is left alone).
388
+ def force_release_lock(instance_id, expected_holder)
389
+ @db[:workflow_instances]
390
+ .where(instance_id: instance_id, locked_by: expected_holder)
391
+ .update(locked_by: nil, locked_at: nil, lock_expires_at: nil)
392
+ .positive?
280
393
  end
281
394
 
282
395
  # ============================================
283
396
  # Workflow History
284
397
  # ============================================
285
398
 
286
- def append_history(instance_id:, activity_id:, event_type:, event_data:, data_type: DataType::JSON)
287
- if data_type == DataType::BINARY
288
- @db[:workflow_history].insert(
289
- instance_id: instance_id,
290
- activity_id: activity_id,
291
- event_type: event_type,
292
- data_type: data_type,
293
- event_data_binary: Sequel.blob(event_data),
294
- created_at: current_timestamp
295
- )
296
- else
297
- @db[:workflow_history].insert(
298
- instance_id: instance_id,
299
- activity_id: activity_id,
300
- event_type: event_type,
301
- data_type: data_type,
302
- event_data: serialize_json(event_data),
303
- created_at: current_timestamp
304
- )
399
+ def append_history(instance_id:, activity_id:, event_type:, event_data:, data_type: DataType::JSON,
400
+ lock_id: nil)
401
+ # Savepoint: a duplicate insert must not abort an enclosing
402
+ # transaction (PostgreSQL aborts the whole transaction otherwise).
403
+ @db.transaction(savepoint: true) do
404
+ # Fenced write: prove we still hold this lock epoch before the row
405
+ # becomes visible.
406
+ assert_lock_held!(instance_id, lock_id) if lock_id
407
+
408
+ if data_type == DataType::BINARY
409
+ @db[:workflow_history].insert(
410
+ instance_id: instance_id,
411
+ activity_id: activity_id,
412
+ event_type: event_type,
413
+ data_type: data_type,
414
+ event_data_binary: Sequel.blob(event_data),
415
+ created_at: current_timestamp
416
+ )
417
+ else
418
+ @db[:workflow_history].insert(
419
+ instance_id: instance_id,
420
+ activity_id: activity_id,
421
+ event_type: event_type,
422
+ data_type: data_type,
423
+ event_data: serialize_json(event_data),
424
+ created_at: current_timestamp
425
+ )
426
+ end
305
427
  end
306
428
  rescue Sequel::UniqueConstraintViolation
307
429
  # Activity already recorded (idempotent)
@@ -315,22 +437,22 @@ module Shikibu
315
437
  .map { |row| deserialize_history_event(row) }
316
438
  end
317
439
 
318
- def archive_history(instance_id)
440
+ # Move the instance's history into the archive. Fenced by lock_id when
441
+ # given; rows are copied with bound values (no dialect-specific
442
+ # timestamp literal in an INSERT ... SELECT).
443
+ def archive_history(instance_id, lock_id: nil)
319
444
  now = current_timestamp
445
+ columns = %i[instance_id activity_id event_type data_type event_data event_data_binary created_at]
320
446
 
321
- # Copy to archive
322
- @db[:workflow_history_archive].insert(
323
- @db[:workflow_history]
324
- .where(instance_id: instance_id)
325
- .select(
326
- :instance_id, :activity_id, :event_type, :data_type,
327
- :event_data, :event_data_binary, :created_at,
328
- Sequel.lit("'#{now}'").as(:archived_at)
329
- )
330
- )
447
+ @db.transaction do
448
+ assert_lock_held!(instance_id, lock_id) if lock_id
331
449
 
332
- # Delete from main history
333
- @db[:workflow_history].where(instance_id: instance_id).delete
450
+ rows = @db[:workflow_history].where(instance_id: instance_id).order(:id).select(*columns).all
451
+ @db[:workflow_history_archive].multi_insert(rows.map { |r| r.merge(archived_at: now) }) unless rows.empty?
452
+
453
+ # Delete from main history
454
+ @db[:workflow_history].where(instance_id: instance_id).delete
455
+ end
334
456
  end
335
457
 
336
458
  # ============================================
@@ -371,35 +493,40 @@ module Shikibu
371
493
  # Timer Subscriptions
372
494
  # ============================================
373
495
 
374
- def register_timer(instance_id:, timer_id:, expires_at:, activity_id: nil)
375
- if mysql?
376
- # MySQL: Use INSERT ... ON DUPLICATE KEY UPDATE
377
- @db[:workflow_timer_subscriptions].on_duplicate_key_update(
378
- expires_at: expires_at,
379
- activity_id: activity_id
380
- ).insert(
381
- instance_id: instance_id,
382
- timer_id: timer_id,
383
- expires_at: expires_at,
384
- activity_id: activity_id,
385
- created_at: current_timestamp
386
- )
387
- else
388
- @db[:workflow_timer_subscriptions].insert_conflict(
389
- target: %i[instance_id timer_id],
390
- update: { expires_at: expires_at, activity_id: activity_id }
391
- ).insert(
392
- instance_id: instance_id,
393
- timer_id: timer_id,
394
- expires_at: expires_at,
395
- activity_id: activity_id,
396
- created_at: current_timestamp
397
- )
496
+ # Register (upsert) a timer; fenced by lock_id when given.
497
+ def register_timer(instance_id:, timer_id:, expires_at:, activity_id: nil, lock_id: nil)
498
+ @db.transaction do
499
+ assert_lock_held!(instance_id, lock_id) if lock_id
500
+
501
+ if mysql?
502
+ # MySQL: Use INSERT ... ON DUPLICATE KEY UPDATE
503
+ @db[:workflow_timer_subscriptions].on_duplicate_key_update(
504
+ expires_at: expires_at,
505
+ activity_id: activity_id
506
+ ).insert(
507
+ instance_id: instance_id,
508
+ timer_id: timer_id,
509
+ expires_at: expires_at,
510
+ activity_id: activity_id,
511
+ created_at: current_timestamp
512
+ )
513
+ else
514
+ @db[:workflow_timer_subscriptions].insert_conflict(
515
+ target: %i[instance_id timer_id],
516
+ update: { expires_at: expires_at, activity_id: activity_id }
517
+ ).insert(
518
+ instance_id: instance_id,
519
+ timer_id: timer_id,
520
+ expires_at: expires_at,
521
+ activity_id: activity_id,
522
+ created_at: current_timestamp
523
+ )
524
+ end
398
525
  end
399
526
  end
400
527
 
401
528
  def find_expired_timers(limit: 100)
402
- now = Time.now
529
+ now = current_timestamp
403
530
  @db[:workflow_timer_subscriptions]
404
531
  .where { expires_at <= now }
405
532
  .order(:expires_at)
@@ -413,75 +540,62 @@ module Shikibu
413
540
  .delete
414
541
  end
415
542
 
543
+ # One timer, if it exists and is due (the same test as find_expired_timers)
544
+ def find_expired_timer(instance_id:, timer_id:)
545
+ now = current_timestamp
546
+ @db[:workflow_timer_subscriptions]
547
+ .where(instance_id: instance_id, timer_id: timer_id)
548
+ .where { expires_at <= now }
549
+ .first
550
+ end
551
+
416
552
  # ============================================
417
553
  # Channel Messages
418
554
  # ============================================
419
555
 
420
- def publish_message(channel:, data:, metadata: nil, data_type: DataType::JSON)
421
- message_id = SecureRandom.uuid
422
-
423
- if data_type == DataType::BINARY
424
- @db[:channel_messages].insert(
425
- channel: channel,
426
- message_id: message_id,
427
- data_type: data_type,
428
- data_binary: Sequel.blob(data),
429
- metadata: metadata ? serialize_json(metadata) : nil,
430
- published_at: current_timestamp
431
- )
432
- else
433
- @db[:channel_messages].insert(
434
- channel: channel,
435
- message_id: message_id,
436
- data_type: data_type,
437
- data: serialize_json(data),
438
- metadata: metadata ? serialize_json(metadata) : nil,
439
- published_at: current_timestamp
440
- )
441
- end
442
-
443
- # Send NOTIFY for new message (deferred if in transaction)
444
- notify_payload = { ch: channel, msg_id: message_id }
445
- if in_transaction?
446
- register_post_commit_callback do
447
- send_notify(Notify::Channel::CHANNEL_MESSAGE, notify_payload)
556
+ def subscribe_to_channel(instance_id:, channel:, mode:, activity_id: nil, timeout_at: nil)
557
+ row = {
558
+ instance_id: instance_id,
559
+ channel: channel,
560
+ mode: mode,
561
+ activity_id: activity_id,
562
+ timeout_at: timeout_at,
563
+ subscribed_at: current_timestamp
564
+ }
565
+ # A new broadcast subscriber only sees messages published after it
566
+ # subscribed (cursor starts at the channel's current MAX(id), as in
567
+ # edda). A durable delivery cursor wins: it survives recur cleanup,
568
+ # so re-subscribing in the next iteration continues where the last one
569
+ # stopped instead of skipping messages published meanwhile.
570
+ if mode == ChannelMode::BROADCAST
571
+ existing = get_subscription(instance_id: instance_id, channel: channel)
572
+ durable_cursor = broadcast_delivery_cursor(instance_id: instance_id, channel: channel)
573
+ if durable_cursor.nil?
574
+ legacy_cursor = existing&.dig(:cursor_message_id)
575
+ durable_cursor = legacy_cursor.nil? ? new_broadcast_cursor(channel) : legacy_cursor
576
+ record_broadcast_delivery_cursor(instance_id: instance_id, channel: channel, cursor_id: durable_cursor)
448
577
  end
449
- else
450
- send_notify(Notify::Channel::CHANNEL_MESSAGE, notify_payload)
578
+ row[:cursor_message_id] = durable_cursor
451
579
  end
452
580
 
453
- message_id
454
- end
455
-
456
- def subscribe_to_channel(instance_id:, channel:, mode:, activity_id: nil, timeout_at: nil)
457
581
  if mysql?
458
582
  @db[:channel_subscriptions].on_duplicate_key_update(
459
583
  mode: mode,
460
584
  activity_id: activity_id,
461
585
  timeout_at: timeout_at
462
- ).insert(
463
- instance_id: instance_id,
464
- channel: channel,
465
- mode: mode,
466
- activity_id: activity_id,
467
- timeout_at: timeout_at,
468
- subscribed_at: current_timestamp
469
- )
586
+ ).insert(row)
470
587
  else
471
588
  @db[:channel_subscriptions].insert_conflict(
472
589
  target: %i[instance_id channel],
473
590
  update: { mode: mode, activity_id: activity_id, timeout_at: timeout_at }
474
- ).insert(
475
- instance_id: instance_id,
476
- channel: channel,
477
- mode: mode,
478
- activity_id: activity_id,
479
- timeout_at: timeout_at,
480
- subscribed_at: current_timestamp
481
- )
591
+ ).insert(row)
482
592
  end
483
593
  end
484
594
 
595
+ def new_broadcast_cursor(channel)
596
+ @db[:channel_messages].where(channel: channel).max(:id) || 0
597
+ end
598
+
485
599
  def unsubscribe_from_channel(instance_id:, channel:)
486
600
  @db[:channel_subscriptions]
487
601
  .where(instance_id: instance_id, channel: channel)
@@ -514,95 +628,16 @@ module Shikibu
514
628
  end
515
629
 
516
630
  def find_timed_out_subscriptions(limit: 100)
517
- now = Time.now
631
+ now = current_timestamp
632
+ ruby_instances = @db[:workflow_instances].where(framework: 'ruby').select(:instance_id)
518
633
  @db[:channel_subscriptions]
634
+ .where(instance_id: ruby_instances)
519
635
  .where { timeout_at <= now }
520
636
  .where { Sequel.~(timeout_at: nil) }
521
637
  .limit(limit)
522
638
  .map(&:to_h)
523
639
  end
524
640
 
525
- def claim_message(message_id:, instance_id:)
526
- @db[:channel_message_claims].insert(
527
- message_id: message_id,
528
- instance_id: instance_id,
529
- claimed_at: current_timestamp
530
- )
531
- true
532
- rescue Sequel::UniqueConstraintViolation
533
- false
534
- end
535
-
536
- def get_next_message(channel:, mode:, instance_id:, cursor_id: nil)
537
- case mode
538
- when ChannelMode::COMPETING
539
- get_next_competing_message(channel, instance_id)
540
- when ChannelMode::BROADCAST
541
- get_next_broadcast_message(channel, instance_id, cursor_id)
542
- end
543
- end
544
-
545
- # Deliver a channel message directly to a specific workflow instance
546
- # Used for Point-to-Point delivery (e.g., shikibuinstanceid targeting)
547
- # @param instance_id [String] Target workflow instance ID
548
- # @param channel [String] Channel name (event type)
549
- # @param message_id [String] Message ID
550
- # @param data [Object] Message data
551
- # @param metadata [Hash] Message metadata
552
- # @param worker_id [String] Worker ID for locking
553
- # @return [Hash, nil] Delivery result or nil if delivery failed
554
- def deliver_channel_message(instance_id:, channel:, message_id:, data:, metadata:, worker_id:)
555
- # Try to acquire lock on the workflow instance
556
- return nil unless try_acquire_lock(instance_id, worker_id)
557
-
558
- begin
559
- result = @db.transaction do
560
- # Find waiting subscription for this channel
561
- sub = @db[:channel_subscriptions]
562
- .where(instance_id: instance_id, channel: channel)
563
- .where { Sequel.~(activity_id: nil) }
564
- .first
565
-
566
- # No waiting subscription found
567
- next nil unless sub
568
-
569
- activity_id = sub[:activity_id]
570
-
571
- # Record message received in history (for deterministic replay)
572
- append_history(
573
- instance_id: instance_id,
574
- activity_id: activity_id,
575
- event_type: EventType::CHANNEL_MESSAGE_RECEIVED,
576
- event_data: {
577
- channel: channel,
578
- message_id: message_id,
579
- data: data,
580
- metadata: metadata,
581
- published_at: Time.now.iso8601
582
- }
583
- )
584
-
585
- # Clear activity_id from subscription (no longer waiting)
586
- @db[:channel_subscriptions]
587
- .where(instance_id: instance_id, channel: channel)
588
- .update(activity_id: nil, timeout_at: nil)
589
-
590
- # Update workflow instance status to running
591
- update_instance_status(instance_id, Status::RUNNING)
592
-
593
- { instance_id: instance_id, activity_id: activity_id }
594
- end
595
-
596
- # Send NOTIFY for workflow resumable (outside transaction for PostgreSQL)
597
- send_notify(Notify::Channel::WORKFLOW_RESUMABLE, { wf_id: instance_id }) if result
598
-
599
- result
600
- ensure
601
- # Always release the lock
602
- release_lock(instance_id, worker_id)
603
- end
604
- end
605
-
606
641
  # ============================================
607
642
  # Outbox
608
643
  # ============================================
@@ -642,12 +677,21 @@ module Shikibu
642
677
  end
643
678
 
644
679
  def get_pending_outbox_events(limit: 100)
680
+ stale_before = current_timestamp - ChannelOps::OUTBOX_CLAIM_STALE_SECONDS
681
+ claimable = Sequel.|(
682
+ { status: [OutboxStatus::PENDING, OutboxStatus::FAILED] },
683
+ Sequel.&(
684
+ { status: OutboxStatus::PROCESSING },
685
+ Sequel.lit('COALESCE(claimed_at, published_at) < ?', stale_before)
686
+ )
687
+ )
688
+
645
689
  if supports_skip_locked?
646
690
  # PostgreSQL/MySQL: Use SELECT FOR UPDATE SKIP LOCKED
647
691
  # This allows multiple workers to fetch different events without blocking
648
692
  @db.transaction do
649
693
  rows = @db[:outbox_events]
650
- .where(status: [OutboxStatus::PENDING, OutboxStatus::FAILED])
694
+ .where(claimable)
651
695
  .order(:created_at)
652
696
  .limit(limit)
653
697
  .for_update
@@ -656,21 +700,34 @@ module Shikibu
656
700
 
657
701
  return [] if rows.empty?
658
702
 
659
- # Mark as processing to prevent duplicate fetches
703
+ # Mark as processing and stamp the claim time so a crashed
704
+ # relayer's claim becomes reclaimable after the staleness window.
660
705
  event_ids = rows.map { |r| r[:event_id] }
661
706
  @db[:outbox_events]
662
707
  .where(event_id: event_ids)
663
- .update(status: OutboxStatus::PROCESSING)
708
+ .update(status: OutboxStatus::PROCESSING, claimed_at: current_timestamp)
664
709
 
665
710
  rows.map { |row| deserialize_outbox_event(row) }
666
711
  end
667
712
  else
668
- # SQLite: Simple query (table-level locking)
669
- @db[:outbox_events]
670
- .where(status: [OutboxStatus::PENDING, OutboxStatus::FAILED])
671
- .order(:created_at)
672
- .limit(limit)
673
- .map { |row| deserialize_outbox_event(row) }
713
+ # SQLite: an IMMEDIATE transaction takes the write lock before the
714
+ # SELECT, so two relayers cannot both claim the same rows.
715
+ @db.transaction(mode: :immediate) do
716
+ rows = @db[:outbox_events]
717
+ .where(claimable)
718
+ .order(:created_at)
719
+ .limit(limit)
720
+ .all
721
+
722
+ return [] if rows.empty?
723
+
724
+ event_ids = rows.map { |r| r[:event_id] }
725
+ @db[:outbox_events]
726
+ .where(event_id: event_ids)
727
+ .update(status: OutboxStatus::PROCESSING, claimed_at: current_timestamp)
728
+
729
+ rows.map { |row| deserialize_outbox_event(row) }
730
+ end
674
731
  end
675
732
  end
676
733
 
@@ -679,7 +736,8 @@ module Shikibu
679
736
  .where(event_id: event_id)
680
737
  .update(
681
738
  status: OutboxStatus::PUBLISHED,
682
- published_at: current_timestamp
739
+ published_at: current_timestamp,
740
+ claimed_at: nil
683
741
  )
684
742
  end
685
743
 
@@ -689,7 +747,8 @@ module Shikibu
689
747
  .update(
690
748
  status: OutboxStatus::FAILED,
691
749
  last_error: error_message,
692
- retry_count: Sequel[:retry_count] + 1
750
+ retry_count: Sequel[:retry_count] + 1,
751
+ claimed_at: nil
693
752
  )
694
753
  end
695
754
 
@@ -698,7 +757,8 @@ module Shikibu
698
757
  .where(event_id: event_id)
699
758
  .update(
700
759
  status: OutboxStatus::EXPIRED,
701
- last_error: error_message
760
+ last_error: error_message,
761
+ claimed_at: nil
702
762
  )
703
763
  end
704
764
 
@@ -707,7 +767,8 @@ module Shikibu
707
767
  .where(event_id: event_id)
708
768
  .update(
709
769
  status: OutboxStatus::INVALID,
710
- last_error: error_message
770
+ last_error: error_message,
771
+ claimed_at: nil
711
772
  )
712
773
  end
713
774
 
@@ -716,7 +777,7 @@ module Shikibu
716
777
  # ============================================
717
778
 
718
779
  def try_acquire_system_lock(lock_name, worker_id, timeout: 30)
719
- now = Time.now
780
+ now = current_timestamp
720
781
  expires_at = now + timeout
721
782
 
722
783
  # Try to insert new lock
@@ -752,7 +813,7 @@ module Shikibu
752
813
  end
753
814
 
754
815
  def refresh_system_lock(lock_name, worker_id, timeout: 30)
755
- now = Time.now
816
+ now = current_timestamp
756
817
  expires_at = now + timeout
757
818
 
758
819
  affected = @db[:system_locks]
@@ -776,16 +837,6 @@ module Shikibu
776
837
  send_notify(Notify::Channel::WORKFLOW_RESUMABLE, { wf_id: instance_id, wf_name: workflow_name })
777
838
  end
778
839
 
779
- # Cleanup old channel messages older than retention_days
780
- # @param retention_days [Integer] Number of days to retain messages
781
- # @return [Integer] Number of deleted messages
782
- def cleanup_old_channel_messages(retention_days:)
783
- cutoff_time = Time.now - (retention_days * 24 * 60 * 60)
784
- @db[:channel_messages]
785
- .where { published_at < cutoff_time }
786
- .delete
787
- end
788
-
789
840
  private
790
841
 
791
842
  def configure_database
@@ -795,6 +846,20 @@ module Shikibu
795
846
  end
796
847
  end
797
848
 
849
+ # For the kernel's own transactions that read before they write (a
850
+ # pending re-check before a wait registration, a candidate scan before
851
+ # a claim). SQLite begins them IMMEDIATE: a deferred transaction that
852
+ # has read cannot take the write lock once another connection has
853
+ # written since (SQLITE_BUSY, or SQLITE_BUSY_SNAPSHOT under WAL, at
854
+ # once, whatever the busy timeout). Activity transactions stay
855
+ # deferred: they run user code of any length, and holding the write
856
+ # lock across it would stall every other writer.
857
+ def immediate_transaction(&)
858
+ return @db.transaction(mode: :immediate, &) if @db.database_type == :sqlite
859
+
860
+ @db.transaction(&)
861
+ end
862
+
798
863
  # Send PostgreSQL NOTIFY (PostgreSQL-only, no-op for other databases)
799
864
  # @param channel [String] Notification channel name
800
865
  # @param payload [Hash] Payload to send as JSON
@@ -812,6 +877,55 @@ module Shikibu
812
877
  Time.now.utc
813
878
  end
814
879
 
880
+ # Per-connection session setup.
881
+ # PostgreSQL/MySQL: pin the session to UTC. The schema's zone-less
882
+ # TIMESTAMP columns hold UTC wall clocks, and the server's own clock
883
+ # (NOW()/CURRENT_TIMESTAMP defaults, other ports' comparisons) must
884
+ # agree with them whatever the server's default zone is.
885
+ # MySQL: READ COMMITTED, as on PostgreSQL. The kernel's protocols do
886
+ # not expect REPEATABLE READ's stale snapshots and gap locks.
887
+ # SQLite: wait for locks with a busy handler that releases the GVL;
888
+ # the busy_timeout Sequel sets holds it, so a thread waiting for a
889
+ # lock another thread holds stalls that holder until the wait fails.
890
+ def session_options(database_url)
891
+ case database_url.to_s
892
+ when /\Apostgres/ then { connect_sqls: ["SET TIME ZONE 'UTC'"] }
893
+ when /\Amysql/
894
+ { connect_sqls: ["SET time_zone = '+00:00'", 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED'] }
895
+ when /\Asqlite/ then { after_connect: method(:configure_sqlite_connection) }
896
+ else {}
897
+ end
898
+ end
899
+
900
+ # A fenced status write matched no row: the instance already
901
+ # terminated while lock_id still holds it, or the lock was lost.
902
+ def raise_status_write_refused(instance_id, lock_id)
903
+ row = @db[:workflow_instances].where(instance_id: instance_id).select(:locked_by, :status).first
904
+ if row && row[:locked_by] == lock_id && Status::TERMINAL.include?(row[:status])
905
+ raise InstanceTerminatedError, instance_id
906
+ end
907
+
908
+ raise LockLostError, instance_id
909
+ end
910
+
911
+ # Insert a row unless one with the same unique key exists. PostgreSQL
912
+ # and SQLite skip it with ON CONFLICT DO NOTHING (a unique violation
913
+ # would abort an enclosing PostgreSQL transaction); MySQL keeps the
914
+ # transaction usable after a duplicate-key error, which is rescued.
915
+ # INSERT IGNORE (and SQLite's INSERT OR IGNORE) would also turn
916
+ # truncation, NOT NULL and foreign-key errors into a silent no-op.
917
+ def insert_unless_exists(table, target, row)
918
+ if mysql?
919
+ begin
920
+ @db[table].insert(row)
921
+ rescue Sequel::UniqueConstraintViolation
922
+ nil
923
+ end
924
+ else
925
+ @db[table].insert_conflict(target: target).insert(row)
926
+ end
927
+ end
928
+
815
929
  def mysql?
816
930
  @db.database_type == :mysql
817
931
  end
@@ -842,6 +956,7 @@ module Shikibu
842
956
  status: row[:status],
843
957
  current_activity_id: row[:current_activity_id],
844
958
  continued_from: row[:continued_from],
959
+ sandboxed: row[:sandboxed].to_i != 0,
845
960
  started_at: row[:started_at],
846
961
  updated_at: row[:updated_at],
847
962
  input_data: parse_json(row[:input_data]),
@@ -888,45 +1003,6 @@ module Shikibu
888
1003
  created_at: row[:created_at]
889
1004
  }
890
1005
  end
891
-
892
- def get_next_competing_message(channel, _instance_id)
893
- # Find unclaimed message
894
- row = @db[:channel_messages]
895
- .left_join(:channel_message_claims, message_id: :message_id)
896
- .where(Sequel[:channel_messages][:channel] => channel)
897
- .where(Sequel[:channel_message_claims][:message_id] => nil)
898
- .order(Sequel[:channel_messages][:published_at])
899
- .select(Sequel[:channel_messages].*)
900
- .first
901
- deserialize_channel_message(row)
902
- end
903
-
904
- def get_next_broadcast_message(channel, _instance_id, cursor_id)
905
- query = @db[:channel_messages].where(channel: channel)
906
- query = query.where { id > cursor_id } if cursor_id
907
- row = query.order(:id).first
908
- deserialize_channel_message(row)
909
- end
910
-
911
- def deserialize_channel_message(row)
912
- return nil unless row
913
-
914
- data = if row[:data_type] == DataType::BINARY
915
- row[:data_binary]
916
- else
917
- parse_json(row[:data])
918
- end
919
- metadata = parse_json(row[:metadata])
920
-
921
- {
922
- id: row[:id],
923
- message_id: row[:message_id],
924
- channel: row[:channel],
925
- data: data,
926
- metadata: metadata,
927
- published_at: row[:published_at]
928
- }
929
- end
930
1006
  end
931
1007
  end
932
1008
  end