shikibu 0.3.0 → 0.4.1

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 +82 -0
  3. data/lib/shikibu/activity.rb +84 -48
  4. data/lib/shikibu/actors.rb +129 -0
  5. data/lib/shikibu/app.rb +37 -23
  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/notify/pg_notify.rb +28 -3
  15. data/lib/shikibu/replay.rb +242 -107
  16. data/lib/shikibu/storage/actor_ops.rb +331 -0
  17. data/lib/shikibu/storage/channel_ops.rb +421 -0
  18. data/lib/shikibu/storage/cursor_ops.rb +37 -0
  19. data/lib/shikibu/storage/sequel_storage.rb +400 -324
  20. data/lib/shikibu/storage/sqlite_ops.rb +58 -0
  21. data/lib/shikibu/supervisor.rb +279 -0
  22. data/lib/shikibu/tasks.rb +193 -0
  23. data/lib/shikibu/version.rb +1 -1
  24. data/lib/shikibu/worker.rb +155 -73
  25. data/lib/shikibu/workflow.rb +106 -48
  26. data/lib/shikibu.rb +4 -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 +121 -2
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ module Storage
5
+ # SQLite specifics: WAL for file databases and the restart of an activity
6
+ # attempt that hits a write conflict.
7
+ module SqliteOps
8
+ SQLITE_BUSY_TIMEOUT_MS = 5000
9
+ MAX_WRITE_CONFLICT_RESTARTS = 10
10
+ WRITE_CONFLICT_BACKOFF_SECONDS = 0.01
11
+
12
+ # One activity attempt in its own transaction. On SQLite a transaction
13
+ # that read before its first write fails at once (SQLITE_BUSY, or
14
+ # SQLITE_BUSY_SNAPSHOT under WAL) when another connection wrote in
15
+ # between; the attempt is rolled back and run again in a new
16
+ # transaction, up to MAX_WRITE_CONFLICT_RESTARTS times. A restart is not
17
+ # a retry. Nested in another activity's transaction the error goes up to
18
+ # the outer attempt, which restarts as a whole.
19
+ def attempt_transaction(&)
20
+ return transaction(&) if @db.database_type != :sqlite || in_transaction?
21
+
22
+ restarts = 0
23
+ begin
24
+ transaction(&)
25
+ rescue StandardError => e
26
+ raise unless write_conflict?(e) && restarts < MAX_WRITE_CONFLICT_RESTARTS
27
+
28
+ restarts += 1
29
+ Kernel.sleep(WRITE_CONFLICT_BACKOFF_SECONDS * restarts)
30
+ retry
31
+ end
32
+ end
33
+
34
+ # A write conflict of an activity nested in another activity's
35
+ # transaction: the outer attempt restarts as a whole, so the inner one
36
+ # neither retries nor records it.
37
+ def nested_write_conflict?(error)
38
+ @db.database_type == :sqlite && in_transaction? && write_conflict?(error)
39
+ end
40
+
41
+ private
42
+
43
+ # File databases run in WAL (readers do not block the writer, and a
44
+ # reader does not hold up a write on another connection); an activity
45
+ # attempt that read before it wrote restarts on a write conflict (see
46
+ # #attempt_transaction). An in-memory database has no journal to switch.
47
+ def configure_sqlite_connection(conn)
48
+ conn.busy_handler_timeout = SQLITE_BUSY_TIMEOUT_MS
49
+ conn.execute('PRAGMA journal_mode=WAL') unless [':memory:', ''].include?(conn.filename)
50
+ end
51
+
52
+ # A SQLite busy error (also as the cause Sequel wraps it in)
53
+ def write_conflict?(error)
54
+ error.is_a?(SQLite3::BusyException) || error.cause.is_a?(SQLite3::BusyException)
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,279 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ # Erlang-style child supervision as a library workflow.
5
+ #
6
+ # A supervisor is an ordinary actor (workflow) that starts a fixed set of
7
+ # child actors, watches their statuses, and restarts them according to a
8
+ # strategy. Parity with romancy/edda supervisors — see edda/supervisor.py
9
+ # for the full design notes. Key points:
10
+ #
11
+ # - Restart = new instance, deterministic generation id "{sup}:{name}:gN"
12
+ # - Poll is authoritative (no monitor/DOWN dependency — recur deletes
13
+ # channel subscriptions between iterations, so sleep bounds the poll
14
+ # interval instead)
15
+ # - 'recurred' counts as alive
16
+ # - Restarting a live child cancels it conditionally (stop_child): one
17
+ # that ended on its own meanwhile is judged by its actual status, and
18
+ # one that is already winding down (compensating) is left for the next sync
19
+ # - History stays bounded because each iteration ends in recur
20
+ #
21
+ # Usage:
22
+ #
23
+ # sup = Shikibu::Supervisor.define(
24
+ # "pipeline-sup",
25
+ # strategy: Shikibu::Supervisor::ONE_FOR_ONE,
26
+ # max_restarts: 5,
27
+ # within_seconds: 60,
28
+ # children: [
29
+ # Shikibu::Supervisor::ChildSpec.new(
30
+ # name: "worker", workflow: "my_worker",
31
+ # input: { x: 1 }, restart: Shikibu::Supervisor::TRANSIENT
32
+ # ),
33
+ # ]
34
+ # )
35
+ # instance_id = sup.start(app)
36
+ #
37
+ module Supervisor
38
+ PERMANENT = 0 # always restart, even on normal completion
39
+ TRANSIENT = 1 # restart only on abnormal termination (failed/cancelled)
40
+ TEMPORARY = 2 # never restart
41
+
42
+ ONE_FOR_ONE = 0 # restart only the dead child
43
+ ONE_FOR_ALL = 1 # restart all non-terminal children
44
+ REST_FOR_ONE = 2 # restart the dead child and all started after it
45
+
46
+ ChildSpec = Struct.new(:name, :workflow, :input, :restart, keyword_init: true) do
47
+ def initialize(name:, workflow:, input: {}, restart: TRANSIENT)
48
+ super
49
+ end
50
+ end
51
+
52
+ DEAD = %w[completed failed cancelled].freeze
53
+
54
+ def self.needs_restart?(mode, status)
55
+ case mode
56
+ when PERMANENT then true
57
+ when TRANSIENT then %w[failed cancelled].include?(status)
58
+ else false
59
+ end
60
+ end
61
+
62
+ # Step 1: classify children. Never-spawned children are spawn-pending
63
+ # (not dead, no cascade trigger, not counted toward intensity).
64
+ # Mutates terminal/final_status on the child hashes; returns
65
+ # [statuses, restart_flags, dead_idx].
66
+ def self.classify(storage, state_children)
67
+ statuses = []
68
+ restart = []
69
+ dead_idx = -1
70
+ state_children.each_with_index do |c, i|
71
+ if c['terminal']
72
+ statuses[i] = 'terminal'
73
+ restart[i] = false
74
+ next
75
+ end
76
+ if c['instance_id'].to_s.empty?
77
+ statuses[i] = ''
78
+ restart[i] = true # initial spawn
79
+ next
80
+ end
81
+ inst = storage.get_instance(c['instance_id'])
82
+ status = inst ? inst[:status].to_s : 'failed'
83
+ statuses[i] = status
84
+ unless DEAD.include?(status)
85
+ restart[i] = false
86
+ next
87
+ end
88
+ if needs_restart?(c['spec']['restart'], status)
89
+ restart[i] = true
90
+ dead_idx = i if dead_idx == -1
91
+ else
92
+ c['terminal'] = true
93
+ c['final_status'] = status
94
+ restart[i] = false
95
+ end
96
+ end
97
+ [statuses, restart, dead_idx]
98
+ end
99
+
100
+ # Step 2: expand the restart set per strategy. A temporary sibling
101
+ # caught in the cascade is stopped, never restarted (SEMANTICS §7; OTP
102
+ # does the same). Returns the indexes of the children to stop.
103
+ def self.expand_restart_set(strategy, state_children, restart, dead_idx)
104
+ return [] if dead_idx.negative?
105
+
106
+ cascade = case strategy
107
+ when ONE_FOR_ALL then 0...state_children.length
108
+ when REST_FOR_ONE then dead_idx...state_children.length
109
+ else []
110
+ end
111
+ stop = []
112
+ cascade.each do |i|
113
+ c = state_children[i]
114
+ next if c['terminal'] || restart[i]
115
+
116
+ if c['spec']['restart'] == TEMPORARY
117
+ stop << i unless c['instance_id'].to_s.empty?
118
+ else
119
+ restart[i] = true
120
+ end
121
+ end
122
+ stop
123
+ end
124
+
125
+ # Step 2b: stop the cascaded temporary siblings and retire them with
126
+ # the status they ended in.
127
+ def self.stop_children(storage, state_children, stop)
128
+ stop.each do |i|
129
+ c = state_children[i]
130
+ status, stopped = stop_child(storage, c['instance_id'])
131
+ next unless stopped
132
+
133
+ c['terminal'] = true
134
+ c['final_status'] = status
135
+ end
136
+ end
137
+
138
+ # Cancel a live child the supervisor replaces or stops (dropping its
139
+ # timers/subscriptions) and answer [status, stopped]. The cancel is
140
+ # conditional: a child no longer cancellable ended on its own between
141
+ # the sync's read and the cancel, and its actual status, not an assumed
142
+ # cancellation, is what its restart mode applies to. One already winding
143
+ # down (compensating) is not stopped; the next sync sees its outcome.
144
+ # Any other failure raises and aborts the sync.
145
+ def self.stop_child(storage, instance_id)
146
+ return [Status::CANCELLED, true] if storage.cancel_instance(instance_id)
147
+
148
+ inst = storage.get_instance(instance_id)
149
+ return [Status::FAILED, true] unless inst # row missing: treat as crashed
150
+
151
+ status = inst[:status].to_s
152
+ [status, DEAD.include?(status)]
153
+ end
154
+
155
+ # Step 3: restart flagged children — cancel if alive, spawn next
156
+ # generation. Returns how many replacements (initial spawns excluded).
157
+ def self.respawn(storage, sup_instance_id, state_children, statuses, restart)
158
+ restarted = 0
159
+ state_children.each_with_index do |c, i|
160
+ next unless restart[i]
161
+
162
+ initial = c['instance_id'].to_s.empty?
163
+ if !initial && !DEAD.include?(statuses[i])
164
+ status, stopped = stop_child(storage, c['instance_id'])
165
+ next unless stopped
166
+
167
+ unless needs_restart?(c['spec']['restart'], status)
168
+ # It ended on its own before the cancel landed (a transient
169
+ # child completing normally): its restart mode decides
170
+ c['terminal'] = true
171
+ c['final_status'] = status
172
+ next
173
+ end
174
+ end
175
+ gen = c['generation'].to_i + 1
176
+ c['instance_id'] = "#{sup_instance_id}:#{c['spec']['name']}:g#{gen}"
177
+ c['generation'] = gen
178
+ spawn_child(storage, c, parent_instance_id: sup_instance_id)
179
+ restarted += 1 unless initial
180
+ end
181
+ restarted
182
+ end
183
+
184
+ def self.spawn_child(storage, child, parent_instance_id: nil)
185
+ child_class = Shikibu.workflow_registry[child['spec']['workflow']]
186
+ # The instance row references its workflow definition; an unknown
187
+ # class has none to reference.
188
+ raise WorkflowNotRegisteredError, child['spec']['workflow'] unless child_class
189
+
190
+ storage.save_workflow_definition(
191
+ workflow_name: child['spec']['workflow'],
192
+ source_hash: child_class.source_hash,
193
+ source_code: child_class.source_code
194
+ )
195
+ storage.create_instance(
196
+ instance_id: child['instance_id'],
197
+ workflow_name: child['spec']['workflow'],
198
+ source_hash: child_class.source_hash,
199
+ owner_service: 'supervisor',
200
+ input_data: child['spec']['input'],
201
+ status: 'running',
202
+ parent_instance_id: parent_instance_id
203
+ )
204
+ end
205
+
206
+ # One authoritative pass over the children, designed to run inside a
207
+ # single activity (atomic + cached on replay).
208
+ def self.sync_pass(storage, sup_instance_id, state_children, strategy)
209
+ state_children = state_children.map(&:dup)
210
+ statuses, restart, dead_idx = classify(storage, state_children)
211
+ stop_children(storage, state_children, expand_restart_set(strategy, state_children, restart, dead_idx))
212
+ restarted = respawn(storage, sup_instance_id, state_children, statuses, restart)
213
+ {
214
+ 'children' => state_children,
215
+ 'restarted_count' => restarted,
216
+ 'alive_count' => state_children.count { |c| !c['terminal'] },
217
+ 'now' => Time.now.to_f
218
+ }
219
+ end
220
+
221
+ def self.define(name, strategy: ONE_FOR_ONE, max_restarts: 0, within_seconds: 60, poll_seconds: 30, children: [])
222
+ Class.new(Shikibu::Workflow) do
223
+ workflow_name name
224
+
225
+ define_method(:execute) do |state: nil|
226
+ # Resumed instances see deeply-symbolized input keys (shikibu
227
+ # parses stored input with symbol keys); normalize to strings.
228
+ state = JSON.parse(JSON.generate(state)) if state.is_a?(Hash)
229
+ if state.nil? || state['children'].nil? || state['children'].empty?
230
+ state = Shikibu::Supervisor.initial_state(children)
231
+ end
232
+
233
+ out = activity(:sync) do
234
+ Shikibu::Supervisor.sync_pass(ctx.storage, ctx.instance_id, state['children'], strategy)
235
+ end
236
+ out = JSON.parse(JSON.generate(out)) # normalize key types across replay
237
+ state['children'] = out['children']
238
+
239
+ Shikibu::Supervisor.check_intensity(state, out, max_restarts, within_seconds)
240
+
241
+ if out['alive_count'].zero?
242
+ next {
243
+ 'children' => state['children'],
244
+ 'total_restarts' => state['restarts'].length,
245
+ 'outcome' => 'completed'
246
+ }
247
+ end
248
+
249
+ sleep poll_seconds
250
+ recur(state: state)
251
+ end
252
+ end.tap(&:register!)
253
+ end
254
+
255
+ def self.initial_state(children)
256
+ {
257
+ 'children' => children.map do |c|
258
+ {
259
+ 'spec' => { 'name' => c.name, 'workflow' => c.workflow,
260
+ 'input' => c.input, 'restart' => c.restart },
261
+ 'instance_id' => '', 'generation' => 0
262
+ }
263
+ end,
264
+ 'restarts' => []
265
+ }
266
+ end
267
+
268
+ def self.check_intensity(state, out, max_restarts, within_seconds)
269
+ return unless out['restarted_count'].positive?
270
+
271
+ cutoff = out['now'] - within_seconds
272
+ state['restarts'] = state['restarts'].select { |t| t >= cutoff }
273
+ out['restarted_count'].times { state['restarts'] << out['now'] }
274
+ return unless max_restarts.positive? && state['restarts'].length > max_restarts
275
+
276
+ raise 'supervisor: restart intensity exceeded'
277
+ end
278
+ end
279
+ end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ # Task primitive (Vercel Board-style): durable, claimable units of work
5
+ # posted to a channel. Workers compete for tasks via claim_task — the
6
+ # task row is the source of truth; the posted wake notice is
7
+ # best-effort only.
8
+ #
9
+ # Every call is a deterministic step (SEMANTICS §2): from workflow code
10
+ # its outcome is recorded once and replayed; inside an activity body it
11
+ # runs directly.
12
+ #
13
+ # Typical worker loop (subscribe first, so a task posted after an empty
14
+ # claim still wakes the receive):
15
+ # notices = Shikibu::Tasks.tasks_channel('tasks:build') # "tasks:build:tasks"
16
+ # Shikibu::Channels.subscribe(ctx, notices, mode: :broadcast)
17
+ # loop do
18
+ # task = Shikibu::Tasks.claim_task(ctx, 'tasks:build')
19
+ # if task.nil?
20
+ # ctx.receive(notices) # block for wake notice
21
+ # next
22
+ # end
23
+ # result = do_work(task[:data])
24
+ # Shikibu::Tasks.complete_task(ctx, task[:id], result)
25
+ # end
26
+ module Tasks
27
+ module_function
28
+
29
+ TERMINAL_STATES = %w[done failed].freeze
30
+
31
+ # Task-event stream name: all lifecycle notices (posted/claimed/
32
+ # done/failed) are published on this broadcast channel — workers and
33
+ # waiters subscribe here.
34
+ def tasks_channel(channel)
35
+ "#{channel}:tasks"
36
+ end
37
+
38
+ # Create a task on channel and publish a "task_posted" notice on
39
+ # tasks_channel(channel). Returns the task ID.
40
+ def post_task(ctx, channel, data)
41
+ Shikibu.deterministic_step(ctx, "post_task:#{channel}") do
42
+ task_id = "task-#{SecureRandom.uuid}"
43
+ payload = data.is_a?(String) ? data : JSON.generate(data)
44
+ ctx.storage.post_task(task_id: task_id, channel: channel, data: payload)
45
+ task_id
46
+ end
47
+ end
48
+
49
+ # Atomically claim the oldest open task on channel for this instance.
50
+ # Returns the task row (hash) or nil.
51
+ def claim_task(ctx, channel)
52
+ Shikibu.deterministic_step(ctx, "claim_task:#{channel}") do
53
+ ctx.storage.claim_task(channel, ctx.instance_id)
54
+ end
55
+ end
56
+
57
+ # Mark a claimed task done. Only the claimant may complete —
58
+ # raises TaskConflictError otherwise, TaskNotFoundError for an unknown ID.
59
+ def complete_task(ctx, task_id, result = nil)
60
+ payload = result.is_a?(String) || result.nil? ? result : JSON.generate(result)
61
+ Shikibu.deterministic_step(ctx, 'complete_task') do
62
+ ctx.storage.complete_task(task_id: task_id, claimant: ctx.instance_id,
63
+ result: payload, failed: false)
64
+ end
65
+ end
66
+
67
+ # Mark a claimed task failed. Only the claimant may fail it
68
+ # (TaskConflictError); TaskNotFoundError for an unknown ID.
69
+ def fail_task(ctx, task_id, result = nil)
70
+ payload = result.is_a?(String) || result.nil? ? result : JSON.generate(result)
71
+ Shikibu.deterministic_step(ctx, 'fail_task') do
72
+ ctx.storage.complete_task(task_id: task_id, claimant: ctx.instance_id,
73
+ result: payload, failed: true)
74
+ end
75
+ end
76
+
77
+ # Return tasks on channel filtered by state (nil = all).
78
+ def list_tasks(ctx, channel, state = nil)
79
+ Shikibu.deterministic_step(ctx, "list_tasks:#{channel}") do
80
+ ctx.storage.list_tasks(channel, state)
81
+ end
82
+ end
83
+
84
+ # Return messages on channel published after the message_id cursor
85
+ # (nil or "" reads all, oldest first). Use the last message's :message_id
86
+ # as the next cursor for incremental polling; a cursor message that is
87
+ # gone (consumed, cleaned up, other channel) raises CursorNotFoundError
88
+ # — use read_channel_after then. A sealed channel requires a channel_sub
89
+ # capability token, as receive does; another instance's direct channel
90
+ # is refused whatever the seal.
91
+ def read_channel_since(ctx, channel, message_id = nil, capability_token: nil)
92
+ Shikibu.deterministic_step(ctx, "read_channel_since:#{channel}") do
93
+ Channels.enforce_direct_privacy(ctx, channel)
94
+ Channels.enforce_channel_capability(ctx, 'channel_sub', channel, capability_token)
95
+ ctx.storage.channel_messages_since(channel, message_id)
96
+ end
97
+ end
98
+
99
+ # Return messages on channel whose numeric :id is above after_id (0 reads
100
+ # all, oldest first). Use the last message's :id as the next cursor: it
101
+ # keeps working after that message is deleted. Sealing and recording as
102
+ # read_channel_since.
103
+ def read_channel_after(ctx, channel, after_id, capability_token: nil)
104
+ Shikibu.deterministic_step(ctx, "read_channel_after:#{channel}") do
105
+ unless after_id.is_a?(Integer)
106
+ raise InvalidArgumentError, "after_id must be an Integer, got #{after_id.inspect}"
107
+ end
108
+
109
+ Channels.enforce_direct_privacy(ctx, channel)
110
+ Channels.enforce_channel_capability(ctx, 'channel_sub', channel, capability_token)
111
+ ctx.storage.channel_messages_after(channel, after_id)
112
+ end
113
+ end
114
+
115
+ # Block until the task reaches a terminal state (done or failed).
116
+ # Subscribes broadcast to the channel's task-event stream and
117
+ # re-checks the task row on every wake — the workflow durably
118
+ # suspends between notices. The deadline is computed once and
119
+ # recorded; a recorded receive timeout ends the wait.
120
+ # Raises TaskNotFoundError for unknown IDs, MessageTimeoutError on
121
+ # timeout.
122
+ def wait_task(ctx, task_id, timeout: nil)
123
+ task = poll_task(ctx, task_id)
124
+ raise TaskNotFoundError, task_id if task.nil?
125
+ return task if TERMINAL_STATES.include?(task[:state])
126
+
127
+ notify_ch = tasks_channel(task[:channel])
128
+ deadline = wait_deadline(ctx, timeout)
129
+ # Subscribe before polling: a later state change then wakes the receive
130
+ Channels.subscribe(ctx, notify_ch, mode: :broadcast)
131
+ loop do
132
+ task = poll_task(ctx, task_id)
133
+ raise TaskNotFoundError, task_id if task.nil?
134
+ return task if TERMINAL_STATES.include?(task[:state])
135
+
136
+ begin
137
+ Channels.receive(ctx, notify_ch, timeout: remaining_seconds(deadline))
138
+ rescue MessageTimeoutError
139
+ task = poll_task(ctx, task_id)
140
+ return task if task && TERMINAL_STATES.include?(task[:state])
141
+
142
+ raise MessageTimeoutError.new(notify_ch, timeout)
143
+ end
144
+ end
145
+ end
146
+
147
+ # Block until any task on channel reaches a terminal state (earliest
148
+ # done, else earliest failed). MessageTimeoutError on timeout.
149
+ def wait_any_task(ctx, channel, timeout: nil)
150
+ notify_ch = tasks_channel(channel)
151
+ deadline = wait_deadline(ctx, timeout)
152
+ Channels.subscribe(ctx, notify_ch, mode: :broadcast)
153
+ loop do
154
+ task = poll_terminal_task(ctx, channel)
155
+ return task unless task.nil?
156
+
157
+ begin
158
+ Channels.receive(ctx, notify_ch, timeout: remaining_seconds(deadline))
159
+ rescue MessageTimeoutError
160
+ task = poll_terminal_task(ctx, channel)
161
+ return task unless task.nil?
162
+
163
+ raise MessageTimeoutError.new(notify_ch, timeout)
164
+ end
165
+ end
166
+ end
167
+
168
+ # Recorded status poll of one task (nil if unknown)
169
+ def poll_task(ctx, task_id)
170
+ Shikibu.deterministic_step(ctx, 'get_task') { ctx.storage.get_task(task_id) }
171
+ end
172
+
173
+ # Recorded poll: earliest done task on channel, else earliest failed
174
+ def poll_terminal_task(ctx, channel)
175
+ Shikibu.deterministic_step(ctx, "poll_tasks:#{channel}") do
176
+ ctx.storage.list_tasks(channel, 'done').first || ctx.storage.list_tasks(channel, 'failed').first
177
+ end
178
+ end
179
+
180
+ # Absolute wait deadline, computed once and recorded (nil = no timeout)
181
+ def wait_deadline(ctx, timeout)
182
+ return nil unless timeout
183
+
184
+ Time.iso8601(Shikibu.deterministic_step(ctx, 'wait_deadline') { (Time.now.utc + timeout).iso8601(6) })
185
+ end
186
+
187
+ # Receive timeout: the time left until the recorded deadline. Only a
188
+ # fresh receive uses it; a replayed receive returns its recording.
189
+ def remaining_seconds(deadline)
190
+ deadline && [deadline - Time.now, 0].max
191
+ end
192
+ end
193
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Shikibu
4
- VERSION = '0.3.0'
4
+ VERSION = '0.4.1'
5
5
  end