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,351 @@
1
+ # Actor OS Semantics — cross-language constitution
2
+
3
+ This document defines the semantics every implementation of the actor-OS
4
+ kernel (romancy/Go, edda/Python, shikibu/Ruby, and future ports) MUST
5
+ preserve. The TLA+ models in `spec/` are the formal companion: they pin
6
+ down the concurrency protocols. The Go test files next to them are
7
+ exhaustive model checkers that need no TLC installation:
8
+
9
+ ```
10
+ cd spec && go test ./...
11
+ ```
12
+
13
+ Schema changes land in this repository first; implementations pin a commit
14
+ of it (git submodule or vendored copy) and migrate in lockstep.
15
+
16
+ ## 1. Instances, locks, and epochs
17
+
18
+ - A workflow instance runs on at most one worker at a time. Mutual
19
+ exclusion is a database claim, not an external lock service.
20
+ - `TryAcquireLock` is a single conditional UPDATE; the row counts as
21
+ acquired iff `RowsAffected == 1`. No check-then-act. `RowsAffected`
22
+ must count matched rows, not changed rows (MySQL: `clientFoundRows` /
23
+ `CLIENT_FOUND_ROWS`): a same-holder re-acquire or heartbeat in the same
24
+ second as the previous write changes no column value and would report
25
+ 0. Model: `spec/InstanceClaimVerdict.tla`.
26
+ - Locks are leases (`lock_timeout_seconds`, default 300), extended by
27
+ heartbeat while running. Writes that mutate instance state
28
+ (status/output/history append) are **fenced**: they carry the holder
29
+ identity in their WHERE clause and fail for non-holders.
30
+ - Epoch fencing: every claim gets a fresh, unique token in `locked_by`
31
+ (romancy `NewLockIdentity`: `workerID#<64 random bits>`), and fenced
32
+ writes compare it for equality. Uniqueness is what matters, not order:
33
+ a worker that loses its lease and re-acquires gets a new token, so the
34
+ old run's writes fail. Fencing on the worker id alone does not achieve
35
+ this. A stale holder detecting `ErrLockNotHeld` must abort its run
36
+ without further writes.
37
+ - A crashed worker's instances are recovered by the stale-lock sweep,
38
+ which re-claims expired leases and resumes them. Re-execution is safe
39
+ because workflow logic is deterministic replay over recorded history.
40
+ - Model: `spec/InstanceClaim.tla`, `spec/EpochFencing.tla`,
41
+ `spec/EpochFencingRuns.tla` (per-run credentials).
42
+ - Terminal statuses are exactly `completed`, `failed` and `cancelled`,
43
+ and they are sticky: no timer, channel, completion, cancel or resume
44
+ path moves a row off them. `recurred` is not terminal (§5).
45
+ - `cancel` is accepted for `running`, `waiting_for_*` and `recurred`
46
+ instances only. A `compensating` instance is already winding down;
47
+ cancelling it would stop its compensations half-way, so cancel answers
48
+ "not cancellable" and leaves it alone.
49
+
50
+ ## 2. Deterministic replay
51
+
52
+ - Workflow code must be deterministic: all side effects live inside
53
+ activities. Activity results are recorded in history exactly once
54
+ (`{name}:{counter}` IDs) and replayed from cache.
55
+ - Activity failures are history too. When an activity gives up (a
56
+ terminal error, or its retry policy is exhausted) the failure is
57
+ recorded as `ActivityFailed` at the activity id, for transactional
58
+ activities as well: the failed attempt's transaction is rolled back
59
+ first, then the failure is appended in its own fenced write. A replay
60
+ returns the recorded failure and does not run the body again.
61
+ - Each attempt of a transactional activity runs in its own transaction;
62
+ a failed attempt is rolled back before the next one starts, so none of
63
+ its writes, outbox events or post-commit callbacks survive.
64
+ - Channel receives, timer sleeps, and event waits are suspension points
65
+ whose outcomes are recorded; replay consumes the recordings.
66
+ - Anything nondeterministic needed by workflow logic (status reads of
67
+ other instances, time, randomness) must enter through an activity or a
68
+ recorded suspension outcome.
69
+
70
+ ### 2a. Kernel primitives are recorded steps
71
+
72
+ - A kernel primitive called from workflow code (names, monitors,
73
+ capabilities, tasks, channel reads, publish/send_to) runs once and
74
+ records its outcome in history; a replay returns the record. A step
75
+ with a side effect proves the lock, applies the effect and records the
76
+ outcome in one transaction, so a run that lost its lease applies
77
+ nothing.
78
+ - Inside an activity body a primitive runs directly: the activity is the
79
+ recorded unit, and the primitive consumes no step id.
80
+ - A read step can run more than once when the worker dies before its
81
+ record commits; later steps only ever observe the recorded outcome.
82
+ - A step records a returned value or a kernel-defined error. The codes:
83
+ `task_conflict`, `task_not_found`, `actor_name_taken`, `fs_conflict`,
84
+ `sandboxed`, `channel_forbidden`, `not_owner`, `cursor_not_found`,
85
+ `invalid_argument` (argument validation, unserializable payloads, bad
86
+ paths or kinds: anything detected before storage is touched). A replay
87
+ restores the code as the port's error class.
88
+ - Any other error (driver and storage errors, unexpected exceptions) is
89
+ not recorded: it **aborts the run**. The primitive raises a run-abort
90
+ error, every later primitive and activity in the same run fails with
91
+ the same error, and the engine ends the run without completing,
92
+ failing or compensating the instance. It releases the lock and leaves
93
+ the instance `running`, so a later run replays and executes the
94
+ primitive again. In Python the abort error derives from
95
+ `BaseException`, in Ruby from `Exception`, so ordinary handlers do not
96
+ swallow it.
97
+ - Lock loss and cancellation of the run's context (shutdown) end a run
98
+ the same way: no compensation, no recorded failure, no completion.
99
+ - A blocking receive refused on a sealed channel records the refusal
100
+ (code `channel_forbidden`) at the receive's id, so a replay returns the
101
+ same error even after the grants changed.
102
+
103
+ ## 3. Channels
104
+
105
+ - Three modes: `broadcast` (every subscriber receives every message),
106
+ `competing` (each message is claimed by exactly one subscriber),
107
+ `direct` (point-to-point, channel name suffixed with the target
108
+ instance id).
109
+ - Competing delivery is a claim race resolved by a conditional UPDATE —
110
+ exactly one claimant wins; losing claimants must not observe the
111
+ message as theirs. Model: `spec/CompetingMessageClaim.tla`.
112
+ - Claiming, recording the message in the consumer's history and deleting
113
+ it are one transaction that re-checks the claim. As separate statements,
114
+ a stale-claim takeover between claim and record lets two consumers
115
+ record the same message. A push delivery writes into a subscriber's
116
+ wait slot only while that subscriber is waiting on the channel;
117
+ otherwise nothing ever reads the record and the message is lost.
118
+ Model: `spec/CompetingMessageClaimSplit.tla`.
119
+ - Receive/registering a wait and releasing the instance lock is one
120
+ atomic storage operation; a message pending at registration time keeps
121
+ the instance runnable instead (missed-wakeup closure).
122
+ Model: `spec/WaitRegistration.tla`.
123
+ - The registration is fenced: it changes nothing unless the caller still
124
+ holds the lock. The sweep that returns a waiting instance with a
125
+ pending message to running clears its wait registration (activity id,
126
+ timeout) in the same statement, and timeout or delivery resumes move
127
+ only `waiting` to `running`. A wait registration therefore exists only
128
+ while the instance is waiting, and a completed instance is never
129
+ resumed. Model: `spec/WaitRegistrationSub.tla`.
130
+ - Transactional publishing: messages inserted inside an activity
131
+ transaction are only delivered to waiting subscribers after commit;
132
+ rollback undoes both.
133
+ - Direct channels are private. Subscribing to, receiving from or reading
134
+ (cursor reads, try-receive) a channel `L:X`, where `X` is the id of an
135
+ existing instance other than the caller, fails with
136
+ `channel_forbidden` whatever the seal state. Every `:` is a candidate
137
+ split point, since instance ids may contain `:`. Sending to `L:X`
138
+ (send_to, a publish to the physical name, a targeted CloudEvent) stays
139
+ allowed.
140
+ - Cursor reads are read steps and need a `channel_sub` token on a sealed
141
+ channel:
142
+ - `read_channel_since(channel, message_id)` returns the messages after
143
+ `message_id`, a message id read earlier from the same channel. When
144
+ no message with that id exists on the channel any more (consumed,
145
+ cleaned up, or never there) the read fails with `cursor_not_found`
146
+ instead of returning the whole channel. An empty id reads from the
147
+ beginning.
148
+ - `read_channel_after(channel, after_id)` takes the numeric row id of
149
+ the last message read and returns the messages with a larger id, in
150
+ id order. It keeps working after the cursor message is deleted; `0`
151
+ reads from the beginning. Returned messages carry both ids.
152
+
153
+ ### 3a. Sealed channels (capability enforcement)
154
+
155
+ - Capability kinds: `actor`, `channel_pub`, `channel_sub`, `fs_write`.
156
+ Tokens are `cap:{kind}:{target}:{secret}`; only the SHA-256 of the
157
+ secret is stored.
158
+ - A channel is **open** while no grant of the matching kind exists for
159
+ it; the first grant **seals** it. Sealed channels require a valid
160
+ `channel_pub` token for publish/send_to and a `channel_sub` token for
161
+ receive. Revoking the last grant re-opens the channel.
162
+ - Expiry does not unseal. A channel stays sealed while any grant of the
163
+ kind exists for it, expired or not; an expired token no longer
164
+ validates. The expiry sweep deletes an expired grant only while another
165
+ grant for the same `(kind, target)` remains that is unexpired or newer
166
+ (`created_at`, then `id`), so the newest expired grant stays.
167
+ - From workflow code, revoking a capability succeeds only for the
168
+ instance that issued it (`granted_by`). Any other instance gets
169
+ `not_owner`, recorded like other step errors. An unknown capability id
170
+ is a successful no-op. Storage-level and admin APIs keep their
171
+ unconditional forms.
172
+ - Capability key. A port can be given a key (an app option, else the
173
+ environment variable `DURAX_CAPABILITY_KEY`, whose UTF-8 bytes are the
174
+ key). With a key, a new capability's secret is
175
+ `hex(HMAC-SHA256(key, capability_id))` (lowercase, 64 characters), and
176
+ the recorded step holds only `{"id", "kind", "target", "derived": true}`;
177
+ a replay derives the token again. Without a key the token is stored in
178
+ plain text in the recorded step. Every worker sharing a database uses
179
+ the same key, and the key must not change while instances that issued
180
+ capabilities are alive.
181
+ - CloudEvents ingress respects seals. When the channel an incoming event
182
+ is published to (its `type`, or `type:{instance}` for a targeted event)
183
+ is sealed for `channel_pub`, the event must carry a valid token in the
184
+ extension attribute `capabilitytoken` (binary mode: header
185
+ `ce-capabilitytoken`). Otherwise the endpoint answers HTTP 403 with
186
+ `{"error", "error_type": "Forbidden", "retryable": "false"}`, publishes
187
+ nothing and starts no workflow. The attribute is stripped from the
188
+ extensions stored with the message.
189
+ - Enforcement in receive runs after the replay-cache lookup so replays
190
+ of a completed receive never re-check (revocation must not break
191
+ replay determinism).
192
+ - Capability checks on direct channels use the logical channel name,
193
+ not the instance-suffixed one.
194
+
195
+ ### 3b. Sandboxed actors (Phase B)
196
+
197
+ - `workflow_instances.sandboxed` is integer boolean state (`0` or `1`).
198
+ An unsandboxed parent may start a child with `sandboxed: true`.
199
+ - A sandboxed instance MUST NOT mint capabilities: implementations reject
200
+ `issue_capability` when the caller's own instance row has `sandboxed=1`.
201
+ - Sandbox state is inherited downward: when instance creation names a
202
+ parent (spawn/supervision), a sandboxed parent forces the child row to
203
+ `sandboxed=1`. A recur continues the same instance (§5) and keeps its
204
+ flag; rows that an older version created as a continuation
205
+ (`continued_from`) inherited it the same way. There is no operation
206
+ that clears the flag.
207
+ - Delegation needs no additional mechanism: a parent passes existing
208
+ capability tokens to the child through the child input.
209
+ - Phase B enforcement is application-layer only. Code running in the
210
+ worker process can still bypass it by using storage directly; hard
211
+ database enforcement (for example PostgreSQL row-level security) is
212
+ Phase C scope and is not implied by this flag.
213
+
214
+ ## 4. Tasks (claimable work items)
215
+
216
+ - `actor_tasks` is the language-neutral work queue: post (with optional
217
+ input data), claim (oldest open task per channel, conditional UPDATE —
218
+ exactly one winner), complete/fail with result.
219
+ Model: `spec/TaskClaim.tla`.
220
+ - Claiming stamps `claimed_at` and increments `attempts`. The claimant
221
+ learns which task it claimed from the claim itself (pick an id, claim
222
+ that id, read that id), never by re-querying its newest claimed task.
223
+ Model: `spec/TaskClaimReadBack.tla`.
224
+ - Completion is fenced on the attempt as well as on `claimed_by`
225
+ (`AND attempts = <attempt the claim returned>`): the claimant is the
226
+ instance id, and one instance can hold two attempts of the same task.
227
+ Model: `spec/TaskReclaimAttempts.tla`.
228
+ - **Orphan reclaim**: a claim whose `claimed_at` is older than the lock
229
+ lease (300s) is presumed dead; the leader sweep returns such tasks to
230
+ `open` so another worker can retry. There is exactly one reclaimer
231
+ (the leader) so reclaim itself needs no additional protocol.
232
+ - `wait_task`/`wait_any_task` are receives on the `{channel}:tasks`
233
+ lifecycle event stream; poll observations are authoritative, the
234
+ stream is only a wake-up.
235
+
236
+ ## 5. Recur (bounded-history iteration)
237
+
238
+ - `recur(new_input)` archives the instance's history and continues the
239
+ workflow as a tail call on the **same instance id**, preventing
240
+ unbounded history growth in long-running loops.
241
+ - One transaction, after proving the run still holds the lock (a run
242
+ that lost its lease changes nothing):
243
+ 1. move the instance's history rows to the archive (inserts into
244
+ archive tables name their columns);
245
+ 2. delete its channel subscriptions (with their wait registrations),
246
+ timer subscriptions and group memberships, but keep its
247
+ `channel_delivery_cursors`, so a re-subscribed broadcast channel
248
+ continues after the last message delivered before the recur;
249
+ 3. delete its registered compensations: each iteration is a finished
250
+ unit, and a failure in a later one must not undo an earlier one;
251
+ 4. set `input_data` to the new input;
252
+ 5. set status `recurred`.
253
+ - A port may run the next iteration at once. In any case a sweep picks up
254
+ `recurred` instances whose lock is free or expired, sets them
255
+ `running` and runs them from empty history with the new input, so a
256
+ crash after the commit loses nothing.
257
+ - Everything bound to the instance id survives an iteration: actor
258
+ names, monitors (as target and as watcher), capabilities it issued,
259
+ tasks, `/actor/{id}/` files and the sandbox flag. `recurred` is alive:
260
+ no DOWN is sent and no name is freed for it.
261
+ - `continued_from` is no longer written. Rows written by an older
262
+ version that continued on a new id keep theirs.
263
+
264
+ ## 6. Actors, registry, monitors
265
+
266
+ - `actor_registry` maps logical actor names to instances; registration
267
+ is idempotent per name, and the mapping is how senders address stable
268
+ actors across restarts.
269
+ - From workflow code, unregistering a name succeeds only for the instance
270
+ that holds it; any other instance gets `not_owner` (recorded). An
271
+ unbound name is a successful no-op.
272
+ - The name of an instance that reached a terminal status is freed
273
+ whether or not anyone monitors it.
274
+ - `Monitor`/`Unmonitor` produce DOWN notifications to watchers when the
275
+ target terminates. DOWN is a wake-up signal, never the authority:
276
+ watchers must confirm against the actual instance status row. The
277
+ sweep sends a DOWN only for a monitor row it deleted, so each monitor
278
+ gets at most one.
279
+
280
+ ## 7. Supervision
281
+
282
+ - A supervisor is an ordinary actor running a library-provided loop over
283
+ a static child set: spawn, observe, restart per strategy.
284
+ - Restart means a NEW instance of the same workflow with the same input;
285
+ child ids are deterministic — `{supervisor}:{child_name}:g{gen}` — so
286
+ a replayed spawn is idempotent. A supervisor that recurs keeps its id,
287
+ so its child ids stay stable; a child that recurs stays the same child
288
+ and is not restarted while alive.
289
+ - Strategies: `one_for_one` (restart only the dead child), `one_for_all`
290
+ (restart all non-terminal children), `rest_for_one` (restart the dead
291
+ child and all started after it). Restart modes: `permanent` (always),
292
+ `transient` (only on abnormal termination), `temporary` (never).
293
+ - Restart intensity (`max_restarts` within `within_seconds`) escalates
294
+ by crashing the supervisor itself; initial spawns never count.
295
+ - The poll is authoritative — instance rows decide who is dead; sleep
296
+ (or DOWN messages, where they survive iteration) only bounds latency.
297
+ - Restarting a live child cancels it with a conditional update
298
+ (non-terminal → `cancelled`). If the cancel matches no row the child
299
+ reached a terminal status first: the supervisor applies the child's
300
+ restart mode to that status instead of respawning it unconditionally.
301
+ Terminal statuses are sticky (§1). With both, a
302
+ transient child that completed is never respawned by a sibling's
303
+ restart; with a best-effort cancel whose result is ignored it can be.
304
+ Model: `spec/SupervisorRestartCAS.tla`. The generation-encoded id
305
+ still makes a replayed spawn idempotent.
306
+
307
+ ## 8. Shared filesystem
308
+
309
+ - Two namespaces: `/actor/{id}/...` (private; only the owning instance
310
+ may read/write — ownership derived from the path) and `/shared/...`
311
+ (read-open, write requires an `fs_write` capability).
312
+ - Listing (`fs_list`) follows read permission; listing `/` must not
313
+ enumerate other actors' private spaces.
314
+ - Writes are conditional PUTs with conflict detection
315
+ (`spec/ActorFS.tla`); large payloads belong in the CAS blob store,
316
+ referenced as `blob:sha256:{hex}`.
317
+
318
+ ## 9. Database dialects
319
+
320
+ - Every session uses UTC as its time zone: timestamp columns hold UTC
321
+ wall clocks, and the database's `NOW()` must agree with the timestamps
322
+ the ports write.
323
+ - Every MySQL session runs at `READ COMMITTED`, PostgreSQL's default.
324
+ The protocols here are not designed for REPEATABLE READ's stale
325
+ snapshots and next-key/gap locks. `RowsAffected` counts matched rows
326
+ (§1).
327
+ - A deadline (timer, receive timeout) never passes early. SQLite stores
328
+ timestamps as text to the second and MySQL in `TIMESTAMP(0)` columns,
329
+ so a deadline with a fraction loses it. Either round the deadline up to
330
+ a whole second before storing it (romancy's timers, which expire at
331
+ `deadline <= now`), or expire it only once the stored second is past
332
+ (`deadline < now`, romancy's receive timeouts).
333
+ - An insert that may hit an existing row is a no-op on conflict
334
+ (`ON CONFLICT DO NOTHING`; on MySQL, handle the duplicate-key error).
335
+ Never MySQL's `INSERT IGNORE`: it also turns truncation and foreign-key
336
+ errors into warnings.
337
+ - MySQL compares identifiers (instance ids, channel names, actor names,
338
+ paths, capability targets) under the database's collation. With the
339
+ default `utf8mb4_0900_ai_ci` that ignores case and accents, which
340
+ PostgreSQL and SQLite do not. Create the database with a binary
341
+ collation (`utf8mb4_0900_bin`) for byte-exact comparison. Do not change
342
+ the collation of single columns: a capability target and the channel
343
+ or path it guards must compare the same way.
344
+ - SQLite file databases run in WAL mode. There a transaction that reads
345
+ before its first write fails at once with `SQLITE_BUSY` or
346
+ `SQLITE_BUSY_SNAPSHOT` when another connection wrote in between
347
+ (`busy_timeout` does not help). An activity attempt that fails this way
348
+ is rolled back and run again in a new transaction; the restart is not a
349
+ retry (at most 10 restarts). An activity nested in another activity's
350
+ transaction does not restart on its own; the error goes to the outer
351
+ attempt.
@@ -0,0 +1,5 @@
1
+ -- migrate:up
2
+ ALTER TABLE outbox_events ADD COLUMN claimed_at TIMESTAMP NULL;
3
+
4
+ -- migrate:down
5
+ ALTER TABLE outbox_events DROP COLUMN claimed_at;
@@ -0,0 +1,24 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_names (
3
+ name VARCHAR(255) PRIMARY KEY,
4
+ instance_id VARCHAR(255) NOT NULL,
5
+ framework VARCHAR(50),
6
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
7
+ FOREIGN KEY (instance_id) REFERENCES workflow_instances(instance_id) ON DELETE CASCADE
8
+ );
9
+ CREATE INDEX idx_actor_names_instance ON actor_names(instance_id);
10
+
11
+ CREATE TABLE IF NOT EXISTS actor_monitors (
12
+ id BIGINT PRIMARY KEY AUTO_INCREMENT,
13
+ watcher_instance_id VARCHAR(255) NOT NULL,
14
+ target_instance_id VARCHAR(255) NOT NULL,
15
+ channel VARCHAR(255) NOT NULL,
16
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
17
+ CONSTRAINT unique_watcher_target UNIQUE (watcher_instance_id, target_instance_id)
18
+ );
19
+ CREATE INDEX idx_actor_monitors_target ON actor_monitors(target_instance_id);
20
+ CREATE INDEX idx_actor_monitors_watcher ON actor_monitors(watcher_instance_id);
21
+
22
+ -- migrate:down
23
+ DROP TABLE IF EXISTS actor_monitors;
24
+ DROP TABLE IF EXISTS actor_names;
@@ -0,0 +1,15 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_capabilities (
3
+ id VARCHAR(64) PRIMARY KEY,
4
+ kind VARCHAR(32) NOT NULL,
5
+ target VARCHAR(255) NOT NULL,
6
+ secret_hash VARCHAR(128) NOT NULL,
7
+ granted_by VARCHAR(64),
8
+ expires_at TIMESTAMP NULL,
9
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
10
+ );
11
+ CREATE UNIQUE INDEX idx_actor_caps_token ON actor_capabilities(kind, target, secret_hash);
12
+ CREATE INDEX idx_actor_caps_target ON actor_capabilities(kind, target);
13
+
14
+ -- migrate:down
15
+ DROP TABLE IF EXISTS actor_capabilities;
@@ -0,0 +1,11 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS payload_blobs (
3
+ hash VARCHAR(64) PRIMARY KEY,
4
+ data LONGBLOB NOT NULL,
5
+ size_bytes BIGINT NOT NULL,
6
+ created_by VARCHAR(64),
7
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
8
+ );
9
+
10
+ -- migrate:down
11
+ DROP TABLE IF EXISTS payload_blobs;
@@ -0,0 +1,13 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_fs (
3
+ path VARCHAR(512) PRIMARY KEY,
4
+ owner VARCHAR(64),
5
+ data LONGBLOB NOT NULL,
6
+ version BIGINT NOT NULL DEFAULT 1,
7
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
8
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
9
+ );
10
+ CREATE INDEX idx_actor_fs_owner ON actor_fs(owner);
11
+
12
+ -- migrate:down
13
+ DROP TABLE IF EXISTS actor_fs;
@@ -0,0 +1,15 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_tasks (
3
+ id VARCHAR(64) PRIMARY KEY,
4
+ channel VARCHAR(255) NOT NULL,
5
+ data TEXT,
6
+ state VARCHAR(16) NOT NULL DEFAULT 'open',
7
+ claimed_by VARCHAR(64),
8
+ result TEXT,
9
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
10
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
11
+ );
12
+ CREATE INDEX idx_actor_tasks_channel_state ON actor_tasks(channel, state);
13
+
14
+ -- migrate:down
15
+ DROP TABLE IF EXISTS actor_tasks;
@@ -0,0 +1,7 @@
1
+ -- migrate:up
2
+ ALTER TABLE actor_tasks ADD COLUMN claimed_at TIMESTAMP NULL;
3
+ ALTER TABLE actor_tasks ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;
4
+
5
+ -- migrate:down
6
+ ALTER TABLE actor_tasks DROP COLUMN claimed_at;
7
+ ALTER TABLE actor_tasks DROP COLUMN attempts;
@@ -0,0 +1,5 @@
1
+ -- migrate:up
2
+ ALTER TABLE workflow_instances ADD COLUMN sandboxed INTEGER NOT NULL DEFAULT 0;
3
+
4
+ -- migrate:down
5
+ ALTER TABLE workflow_instances DROP COLUMN sandboxed;
@@ -0,0 +1,15 @@
1
+ -- migrate:up
2
+ -- Columns that hold an instance ID get the width of
3
+ -- workflow_instances.instance_id. At VARCHAR(64) a longer ID was refused
4
+ -- (strict mode) or truncated, and the owner and claimant checks then
5
+ -- refused the instance that owns the row.
6
+ ALTER TABLE actor_capabilities MODIFY COLUMN granted_by VARCHAR(255);
7
+ ALTER TABLE actor_fs MODIFY COLUMN owner VARCHAR(255);
8
+ ALTER TABLE actor_tasks MODIFY COLUMN claimed_by VARCHAR(255);
9
+ ALTER TABLE payload_blobs MODIFY COLUMN created_by VARCHAR(255);
10
+
11
+ -- migrate:down
12
+ ALTER TABLE payload_blobs MODIFY COLUMN created_by VARCHAR(64);
13
+ ALTER TABLE actor_tasks MODIFY COLUMN claimed_by VARCHAR(64);
14
+ ALTER TABLE actor_fs MODIFY COLUMN owner VARCHAR(64);
15
+ ALTER TABLE actor_capabilities MODIFY COLUMN granted_by VARCHAR(64);
@@ -0,0 +1,5 @@
1
+ -- migrate:up
2
+ ALTER TABLE outbox_events ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMP;
3
+
4
+ -- migrate:down
5
+ ALTER TABLE outbox_events DROP COLUMN IF EXISTS claimed_at;
@@ -0,0 +1,23 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_names (
3
+ name TEXT PRIMARY KEY,
4
+ instance_id TEXT NOT NULL REFERENCES workflow_instances(instance_id) ON DELETE CASCADE,
5
+ framework TEXT,
6
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
7
+ );
8
+ CREATE INDEX IF NOT EXISTS idx_actor_names_instance ON actor_names(instance_id);
9
+
10
+ CREATE TABLE IF NOT EXISTS actor_monitors (
11
+ id SERIAL PRIMARY KEY,
12
+ watcher_instance_id TEXT NOT NULL,
13
+ target_instance_id TEXT NOT NULL,
14
+ channel TEXT NOT NULL,
15
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
16
+ CONSTRAINT unique_watcher_target UNIQUE (watcher_instance_id, target_instance_id)
17
+ );
18
+ CREATE INDEX IF NOT EXISTS idx_actor_monitors_target ON actor_monitors(target_instance_id);
19
+ CREATE INDEX IF NOT EXISTS idx_actor_monitors_watcher ON actor_monitors(watcher_instance_id);
20
+
21
+ -- migrate:down
22
+ DROP TABLE IF EXISTS actor_monitors;
23
+ DROP TABLE IF EXISTS actor_names;
@@ -0,0 +1,15 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_capabilities (
3
+ id TEXT PRIMARY KEY,
4
+ kind TEXT NOT NULL,
5
+ target TEXT NOT NULL,
6
+ secret_hash TEXT NOT NULL,
7
+ granted_by TEXT,
8
+ expires_at TIMESTAMP,
9
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
10
+ );
11
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_actor_caps_token ON actor_capabilities(kind, target, secret_hash);
12
+ CREATE INDEX IF NOT EXISTS idx_actor_caps_target ON actor_capabilities(kind, target);
13
+
14
+ -- migrate:down
15
+ DROP TABLE IF EXISTS actor_capabilities;
@@ -0,0 +1,11 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS payload_blobs (
3
+ hash TEXT PRIMARY KEY,
4
+ data BYTEA NOT NULL,
5
+ size_bytes BIGINT NOT NULL,
6
+ created_by TEXT,
7
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
8
+ );
9
+
10
+ -- migrate:down
11
+ DROP TABLE IF EXISTS payload_blobs;
@@ -0,0 +1,13 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_fs (
3
+ path TEXT PRIMARY KEY,
4
+ owner TEXT,
5
+ data BYTEA NOT NULL,
6
+ version BIGINT NOT NULL DEFAULT 1,
7
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
8
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
9
+ );
10
+ CREATE INDEX IF NOT EXISTS idx_actor_fs_owner ON actor_fs(owner);
11
+
12
+ -- migrate:down
13
+ DROP TABLE IF EXISTS actor_fs;
@@ -0,0 +1,15 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_tasks (
3
+ id TEXT PRIMARY KEY,
4
+ channel TEXT NOT NULL,
5
+ data TEXT,
6
+ state TEXT NOT NULL DEFAULT 'open',
7
+ claimed_by TEXT,
8
+ result TEXT,
9
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
10
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
11
+ );
12
+ CREATE INDEX IF NOT EXISTS idx_actor_tasks_channel_state ON actor_tasks(channel, state);
13
+
14
+ -- migrate:down
15
+ DROP TABLE IF EXISTS actor_tasks;
@@ -0,0 +1,7 @@
1
+ -- migrate:up
2
+ ALTER TABLE actor_tasks ADD COLUMN claimed_at TIMESTAMPTZ;
3
+ ALTER TABLE actor_tasks ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;
4
+
5
+ -- migrate:down
6
+ ALTER TABLE actor_tasks DROP COLUMN claimed_at;
7
+ ALTER TABLE actor_tasks DROP COLUMN attempts;
@@ -0,0 +1,5 @@
1
+ -- migrate:up
2
+ ALTER TABLE workflow_instances ADD COLUMN sandboxed INTEGER NOT NULL DEFAULT 0;
3
+
4
+ -- migrate:down
5
+ ALTER TABLE workflow_instances DROP COLUMN sandboxed;
@@ -0,0 +1,7 @@
1
+ -- migrate:up
2
+ -- MySQL only: these columns are TEXT here, with no width to widen. The
3
+ -- version exists in every dialect so the migration sets stay identical.
4
+ SELECT 1;
5
+
6
+ -- migrate:down
7
+ SELECT 1;
@@ -0,0 +1,5 @@
1
+ -- migrate:up
2
+ ALTER TABLE outbox_events ADD COLUMN claimed_at TEXT;
3
+
4
+ -- migrate:down
5
+ ALTER TABLE outbox_events DROP COLUMN claimed_at;
@@ -0,0 +1,23 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_names (
3
+ name TEXT PRIMARY KEY,
4
+ instance_id TEXT NOT NULL REFERENCES workflow_instances(instance_id) ON DELETE CASCADE,
5
+ framework TEXT,
6
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
7
+ );
8
+ CREATE INDEX IF NOT EXISTS idx_actor_names_instance ON actor_names(instance_id);
9
+
10
+ CREATE TABLE IF NOT EXISTS actor_monitors (
11
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
12
+ watcher_instance_id TEXT NOT NULL,
13
+ target_instance_id TEXT NOT NULL,
14
+ channel TEXT NOT NULL,
15
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
16
+ UNIQUE (watcher_instance_id, target_instance_id)
17
+ );
18
+ CREATE INDEX IF NOT EXISTS idx_actor_monitors_target ON actor_monitors(target_instance_id);
19
+ CREATE INDEX IF NOT EXISTS idx_actor_monitors_watcher ON actor_monitors(watcher_instance_id);
20
+
21
+ -- migrate:down
22
+ DROP TABLE IF EXISTS actor_monitors;
23
+ DROP TABLE IF EXISTS actor_names;
@@ -0,0 +1,15 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS actor_capabilities (
3
+ id TEXT PRIMARY KEY,
4
+ kind TEXT NOT NULL,
5
+ target TEXT NOT NULL,
6
+ secret_hash TEXT NOT NULL,
7
+ granted_by TEXT,
8
+ expires_at TEXT,
9
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
10
+ );
11
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_actor_caps_token ON actor_capabilities(kind, target, secret_hash);
12
+ CREATE INDEX IF NOT EXISTS idx_actor_caps_target ON actor_capabilities(kind, target);
13
+
14
+ -- migrate:down
15
+ DROP TABLE IF EXISTS actor_capabilities;
@@ -0,0 +1,11 @@
1
+ -- migrate:up
2
+ CREATE TABLE IF NOT EXISTS payload_blobs (
3
+ hash TEXT PRIMARY KEY,
4
+ data BLOB NOT NULL,
5
+ size_bytes INTEGER NOT NULL,
6
+ created_by TEXT,
7
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
8
+ );
9
+
10
+ -- migrate:down
11
+ DROP TABLE IF EXISTS payload_blobs;