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,387 @@
1
+ // Package spec model-checks the workflow-instance claim protocol described
2
+ // in InstanceClaim.tla by exhaustive state-space exploration in Go. The
3
+ // transition relation mirrors the spec action for action, so the tests
4
+ // establish the same results TLC would report:
5
+ //
6
+ // - the pre-fix design (non-atomic claim, unfenced writes) violates both
7
+ // safety invariants;
8
+ // - the current design (atomic conditional claim, fenced writes,
9
+ // heartbeat) has no reachable violation, no deadlock, and can always
10
+ // still finish the instance.
11
+ //
12
+ // Run TLC on the spec proper when a Java toolchain is available:
13
+ //
14
+ // java -jar tla2tools.jar -config InstanceClaim_new.cfg InstanceClaim.tla
15
+ package spec
16
+
17
+ import (
18
+ "strings"
19
+ "testing"
20
+ )
21
+
22
+ const nWorkers = 2
23
+ const null = -1
24
+
25
+ // claimState mirrors the spec variables.
26
+ type claimState struct {
27
+ holder int // Workers index, or null
28
+ expired bool
29
+ believes [nWorkers]bool
30
+ pc [nWorkers]string // idle, read, running, aborted, done
31
+ sawFree [nWorkers]bool
32
+ legit [nWorkers]bool
33
+ wrote [nWorkers]bool
34
+ staleWrite bool
35
+ }
36
+
37
+ type protocol struct {
38
+ atomic bool // conditional-UPDATE claim
39
+ fenced bool // writes conditioned on holder
40
+ }
41
+
42
+ func freeFor(s claimState, w int) bool {
43
+ return s.holder == null || s.expired || s.holder == w
44
+ }
45
+
46
+ // successors returns the states reachable in one step, one entry per fired
47
+ // action. It mirrors Next in InstanceClaim.tla.
48
+ func successors(s claimState, p protocol) []claimState {
49
+ var out []claimState
50
+ add := func(n claimState) { out = append(out, n) }
51
+
52
+ for w := 0; w < nWorkers; w++ {
53
+ // ---- claim ----
54
+ if p.atomic {
55
+ // TryAcquire(w)
56
+ if s.pc[w] == "idle" {
57
+ n := s
58
+ if freeFor(s, w) {
59
+ n.holder = w
60
+ n.expired = false
61
+ n.believes[w] = true
62
+ n.legit[w] = true
63
+ n.pc[w] = "running"
64
+ }
65
+ add(n)
66
+ }
67
+ } else {
68
+ // ReadLock(w)
69
+ if s.pc[w] == "idle" {
70
+ n := s
71
+ n.pc[w] = "read"
72
+ n.sawFree[w] = freeFor(s, w)
73
+ add(n)
74
+ }
75
+ // Claim(w): acts on the possibly stale read; legit records what
76
+ // a conditional claim would have seen at this instant.
77
+ if s.pc[w] == "read" {
78
+ n := s
79
+ n.sawFree[w] = false
80
+ if s.sawFree[w] {
81
+ n.legit[w] = freeFor(s, w)
82
+ n.holder = w
83
+ n.expired = false
84
+ n.believes[w] = true
85
+ n.pc[w] = "running"
86
+ } else {
87
+ n.pc[w] = "idle"
88
+ }
89
+ add(n)
90
+ }
91
+ }
92
+
93
+ // ---- run ----
94
+ // Renew(w): heartbeat extends a held lease.
95
+ if s.pc[w] == "running" && s.holder == w {
96
+ n := s
97
+ n.expired = false
98
+ add(n)
99
+ }
100
+ // Write(w)
101
+ if s.pc[w] == "running" && s.believes[w] {
102
+ if p.fenced {
103
+ if s.holder == w {
104
+ n := s
105
+ n.wrote[w] = true
106
+ add(n)
107
+ }
108
+ } else {
109
+ n := s
110
+ n.wrote[w] = true
111
+ if s.holder != w {
112
+ n.staleWrite = true
113
+ }
114
+ add(n)
115
+ }
116
+ }
117
+ // Abort(w): heartbeat/ErrLockNotHeld ends a run that lost the row.
118
+ if s.pc[w] == "running" && s.holder != w {
119
+ n := s
120
+ n.believes[w] = false
121
+ n.pc[w] = "aborted"
122
+ add(n)
123
+ }
124
+ // Finish(w): release is conditional on still holding.
125
+ if s.pc[w] == "running" {
126
+ n := s
127
+ n.believes[w] = false
128
+ n.pc[w] = "done"
129
+ if s.holder == w {
130
+ n.holder = null
131
+ n.expired = false
132
+ }
133
+ add(n)
134
+ }
135
+ }
136
+
137
+ // ExpireLease: abstract tick; may fire while the holder still runs.
138
+ if s.holder != null && !s.expired {
139
+ n := s
140
+ n.expired = true
141
+ add(n)
142
+ }
143
+
144
+ return out
145
+ }
146
+
147
+ func (s claimState) key() string {
148
+ var b strings.Builder
149
+ b.WriteString(itoa(s.holder))
150
+ b.WriteByte('|')
151
+ writeBool(&b, s.expired)
152
+ for w := 0; w < nWorkers; w++ {
153
+ b.WriteByte('|')
154
+ b.WriteString(s.pc[w])
155
+ writeBool(&b, s.believes[w])
156
+ writeBool(&b, s.sawFree[w])
157
+ writeBool(&b, s.legit[w])
158
+ writeBool(&b, s.wrote[w])
159
+ }
160
+ b.WriteByte('|')
161
+ writeBool(&b, s.staleWrite)
162
+ return b.String()
163
+ }
164
+
165
+ func writeBool(b *strings.Builder, v bool) {
166
+ if v {
167
+ b.WriteByte('1')
168
+ } else {
169
+ b.WriteByte('0')
170
+ }
171
+ }
172
+
173
+ func itoa(i int) string {
174
+ if i == null {
175
+ return "N"
176
+ }
177
+ return string(rune('a' + i))
178
+ }
179
+
180
+ func initState() claimState {
181
+ return claimState{
182
+ holder: null,
183
+ pc: [nWorkers]string{"idle", "idle"},
184
+ legit: [nWorkers]bool{true, true},
185
+ }
186
+ }
187
+
188
+ // explore runs BFS over the reachable state space. It calls check on every
189
+ // state; a false return aborts the search and reports the violating state
190
+ // plus the action trace that produced it.
191
+ func explore(p protocol, check func(claimState) bool) (states int, bad claimState, trace []string, ok bool) {
192
+ start := initState()
193
+ seen := map[string]bool{start.key(): true}
194
+ parent := map[string]claimState{}
195
+ parentAct := map[string]string{}
196
+ queue := []claimState{start}
197
+ ok = true
198
+
199
+ for len(queue) > 0 && ok {
200
+ s := queue[0]
201
+ queue = queue[1:]
202
+ states++
203
+ if !check(s) {
204
+ bad, ok = s, false
205
+ break
206
+ }
207
+ for _, n := range successors(s, p) {
208
+ k := n.key()
209
+ if seen[k] {
210
+ continue
211
+ }
212
+ seen[k] = true
213
+ parent[k] = s
214
+ parentAct[k] = actionLabel(s, n)
215
+ queue = append(queue, n)
216
+ }
217
+ }
218
+
219
+ if !ok {
220
+ for cur := bad; ; {
221
+ k := cur.key()
222
+ act, has := parentAct[k]
223
+ if !has {
224
+ break
225
+ }
226
+ trace = append([]string{describe(cur, act)}, trace...)
227
+ cur = parent[k]
228
+ }
229
+ }
230
+ return
231
+ }
232
+
233
+ // actionLabel describes which spec action turned s into n.
234
+ func actionLabel(s, n claimState) string {
235
+ switch {
236
+ case s.holder != n.holder && n.holder != null && n.pc != s.pc:
237
+ return "claim"
238
+ case s.holder != n.holder && n.holder == null:
239
+ return "finish(release)"
240
+ case !s.expired && n.expired:
241
+ return "expire"
242
+ case s.pc != n.pc:
243
+ for w := 0; w < nWorkers; w++ {
244
+ if s.pc[w] != n.pc[w] {
245
+ return "pc:" + s.pc[w] + "->" + n.pc[w]
246
+ }
247
+ }
248
+ return "step"
249
+ default:
250
+ return "write/renew"
251
+ }
252
+ }
253
+
254
+ func describe(s claimState, act string) string {
255
+ return act + " => holder=" + itoa(s.holder) +
256
+ " expired=" + tf(s.expired) +
257
+ " pc=" + s.pc[0] + "," + s.pc[1] +
258
+ " wrote=" + tf(s.wrote[0]) + "," + tf(s.wrote[1]) +
259
+ " legit=" + tf(s.legit[0]) + "," + tf(s.legit[1]) +
260
+ " staleWrite=" + tf(s.staleWrite)
261
+ }
262
+
263
+ func tf(b bool) string {
264
+ if b {
265
+ return "t"
266
+ }
267
+ return "f"
268
+ }
269
+
270
+ // safety combines both spec invariants.
271
+ func safety(s claimState) bool {
272
+ if s.staleWrite {
273
+ return false // NoStaleWrite
274
+ }
275
+ for w := 0; w < nWorkers; w++ {
276
+ if s.wrote[w] && !s.legit[w] {
277
+ return false // LegitimateWriters
278
+ }
279
+ }
280
+ return true
281
+ }
282
+
283
+ // TestClaimOldDesignViolates reproduces the bug that motivated the fix:
284
+ // under the non-atomic claim and unfenced writes, TLC's counterpart finds a
285
+ // state where a worker's write lands while it does not hold the row.
286
+ func TestClaimOldDesignViolates(t *testing.T) {
287
+ states, bad, trace, ok := explore(protocol{atomic: false, fenced: false}, safety)
288
+ if ok {
289
+ t.Fatalf("old design: expected a safety violation in %d states, found none", states)
290
+ }
291
+ t.Logf("old design: violation after %d states, trace (%d steps):", states, len(trace))
292
+ for _, step := range trace {
293
+ t.Logf(" %s", step)
294
+ }
295
+ _ = bad
296
+ }
297
+
298
+ // TestClaimNewDesignSafe exhausts the state space of the fixed protocol:
299
+ // no stale write and no illegitimate write is reachable.
300
+ func TestClaimNewDesignSafe(t *testing.T) {
301
+ states, _, trace, ok := explore(protocol{atomic: true, fenced: true}, safety)
302
+ if !ok {
303
+ t.Fatalf("new design: safety violated; trace:")
304
+ for _, step := range trace {
305
+ t.Logf(" %s", step)
306
+ }
307
+ }
308
+ t.Logf("new design: %d states explored, safety holds", states)
309
+ }
310
+
311
+ // TestClaimNewDesignLiveness checks the bounded analogue of the spec's
312
+ // / Liveness property: from every reachable state the instance can still be
313
+ // / finished by some worker (no reachable dead end), and the system never
314
+ // / deadlocks.
315
+ func TestClaimNewDesignLiveness(t *testing.T) {
316
+ p := protocol{atomic: true, fenced: true}
317
+ start := initState()
318
+ seen := map[string]bool{start.key(): true}
319
+ queue := []claimState{start}
320
+
321
+ var states int
322
+ for len(queue) > 0 {
323
+ s := queue[0]
324
+ queue = queue[1:]
325
+ states++
326
+
327
+ succ := successors(s, p)
328
+ if len(succ) == 0 {
329
+ // No enabled action. That is only acceptable in a terminal
330
+ // state where the instance actually finished.
331
+ allTerminal, someDone := true, false
332
+ for w := 0; w < nWorkers; w++ {
333
+ if s.pc[w] != "done" && s.pc[w] != "aborted" {
334
+ allTerminal = false
335
+ }
336
+ if s.pc[w] == "done" {
337
+ someDone = true
338
+ }
339
+ }
340
+ if !allTerminal || !someDone {
341
+ t.Fatalf("stuck state reached: holder=%d pc=%v", s.holder, s.pc)
342
+ }
343
+ }
344
+ if !reachableDone(s, p) {
345
+ t.Fatalf("some worker cannot reach done from: holder=%d expired=%v pc=%v",
346
+ s.holder, s.expired, s.pc)
347
+ }
348
+
349
+ for _, n := range succ {
350
+ k := n.key()
351
+ if !seen[k] {
352
+ seen[k] = true
353
+ queue = append(queue, n)
354
+ }
355
+ }
356
+ }
357
+ t.Logf("new design: %d states, finish reachable from all of them", states)
358
+ }
359
+
360
+ // reachableDone reports whether some state with a worker in "done" is
361
+ // reachable from s.
362
+ func reachableDone(s claimState, p protocol) bool {
363
+ for w := 0; w < nWorkers; w++ {
364
+ if s.pc[w] == "done" {
365
+ return true
366
+ }
367
+ }
368
+ seen := map[string]bool{s.key(): true}
369
+ queue := []claimState{s}
370
+ for len(queue) > 0 {
371
+ cur := queue[0]
372
+ queue = queue[1:]
373
+ for _, n := range successors(cur, p) {
374
+ for w := 0; w < nWorkers; w++ {
375
+ if n.pc[w] == "done" {
376
+ return true
377
+ }
378
+ }
379
+ k := n.key()
380
+ if !seen[k] {
381
+ seen[k] = true
382
+ queue = append(queue, n)
383
+ }
384
+ }
385
+ }
386
+ return false
387
+ }
@@ -0,0 +1,194 @@
1
+ // competing_claim_test.go model-checks the competing-channel claim protocol
2
+ // described in CompetingMessageClaim.tla by exhaustive state-space
3
+ // exploration in Go. The transition relation mirrors the spec action for
4
+ // action:
5
+ //
6
+ // - the pre-fix design (a claim can never be taken over) reaches a state
7
+ // where a dead consumer's claim hides the message from everyone alive;
8
+ // - the current design (takeover on stale claim or terminal owner, plus
9
+ // consume-delete) never leaves the message stranded and never lets two
10
+ // consumers both record it.
11
+ //
12
+ // Run TLC on the spec proper when a Java toolchain is available:
13
+ //
14
+ // java -jar tla2tools.jar -deadlock -config CompetingMessageClaim_new.cfg CompetingMessageClaim.tla
15
+ package spec
16
+
17
+ import (
18
+ "fmt"
19
+ "testing"
20
+ )
21
+
22
+ // mcState mirrors the spec variables of CompetingMessageClaim.tla for two
23
+ // consumers c1, c2.
24
+ type mcState struct {
25
+ msg string // unclaimed, claimed, consumed
26
+ owner string // "", c1, c2
27
+ fresh bool
28
+ alive [2]bool
29
+ killed [2]bool // consumedBy set: recorded receive history
30
+ }
31
+
32
+ func (s mcState) key() string {
33
+ return fmt.Sprintf("%s|%s|%v|%v%v|%v%v",
34
+ s.msg, s.owner, s.fresh, s.alive[0], s.alive[1], s.killed[0], s.killed[1])
35
+ }
36
+
37
+ var mcConsumers = [2]string{"c1", "c2"}
38
+
39
+ func mcSuccessors(s mcState, takeover bool) []mcState {
40
+ var out []mcState
41
+ add := func(n mcState) { out = append(out, n) }
42
+
43
+ for i, c := range mcConsumers {
44
+ if !s.alive[i] {
45
+ continue
46
+ }
47
+ // Claim: unclaimed, or voidable claim (self / stale / dead owner).
48
+ if s.msg != "consumed" {
49
+ claimable := s.msg == "unclaimed" ||
50
+ (takeover && s.msg == "claimed" &&
51
+ (s.owner == c || !s.fresh || !s.alive[mcOwnerIdx(s)]))
52
+ if claimable {
53
+ n := s
54
+ n.msg = "claimed"
55
+ n.owner = c
56
+ n.fresh = true
57
+ add(n)
58
+ }
59
+ }
60
+ // Consume: record history + delete, own claim only.
61
+ if s.msg == "claimed" && s.owner == c {
62
+ n := s
63
+ n.msg = "consumed"
64
+ n.killed[i] = true
65
+ add(n)
66
+ }
67
+ // Die: crash or terminal status, claim may be held.
68
+ {
69
+ n := s
70
+ n.alive[i] = false
71
+ add(n)
72
+ }
73
+ }
74
+ // Expire: held claim ages past the staleness threshold.
75
+ if s.msg == "claimed" && s.fresh {
76
+ n := s
77
+ n.fresh = false
78
+ add(n)
79
+ }
80
+ return out
81
+ }
82
+
83
+ func mcOwnerIdx(s mcState) int {
84
+ if s.owner == "c2" {
85
+ return 1
86
+ }
87
+ return 0
88
+ }
89
+
90
+ // mcStranded reports a live-blocked state: the message is unconsumed and
91
+ // no live consumer can ever take another step that could lead to consuming
92
+ // it. We detect it as a reachable state with a live consumer where the only
93
+ // outgoing actions lead nowhere new — simpler: a state is stranded when the
94
+ // message is claimed by a dead consumer whose claim is fresh (un-takeover
95
+ // protocol) or when every consumer is dead without consumption.
96
+ func mcStranded(s mcState, takeover bool) bool {
97
+ if s.msg == "consumed" {
98
+ return false
99
+ }
100
+ // Any live consumer that could still claim?
101
+ for i, c := range mcConsumers {
102
+ if !s.alive[i] {
103
+ continue
104
+ }
105
+ if s.msg == "unclaimed" {
106
+ return false
107
+ }
108
+ if takeover && s.msg == "claimed" &&
109
+ (s.owner == c || !s.fresh || !s.alive[mcOwnerIdx(s)]) {
110
+ return false
111
+ }
112
+ if s.msg == "claimed" && s.owner == c {
113
+ return false // could still consume
114
+ }
115
+ }
116
+ return true
117
+ }
118
+
119
+ func mcExplore(takeover bool) (states int, strandedStates int, multiConsume bool) {
120
+ start := mcState{msg: "unclaimed", alive: [2]bool{true, true}}
121
+ seen := map[string]bool{start.key(): true}
122
+ queue := []mcState{start}
123
+ for len(queue) > 0 {
124
+ s := queue[0]
125
+ queue = queue[1:]
126
+ states++
127
+ if s.killed[0] && s.killed[1] {
128
+ multiConsume = true
129
+ }
130
+ if mcStranded(s, takeover) {
131
+ strandedStates++
132
+ }
133
+ for _, n := range mcSuccessors(s, takeover) {
134
+ if k := n.key(); !seen[k] {
135
+ seen[k] = true
136
+ queue = append(queue, n)
137
+ }
138
+ }
139
+ }
140
+ return
141
+ }
142
+
143
+ // TestCompetingClaim_OldProtocolStrands: without takeover, a consumer that
144
+ // claims and dies leaves the message claimed forever — unreachable for the
145
+ // survivors (the orphan-claim bug).
146
+ func TestCompetingClaim_OldProtocolStrands(t *testing.T) {
147
+ states, stranded, multi := mcExplore(false)
148
+ if !multi {
149
+ t.Log("no double-consume path (claim itself is exclusive)")
150
+ }
151
+ if stranded == 0 {
152
+ t.Fatal("expected reachable stranded states without takeover")
153
+ }
154
+ t.Logf("old protocol: %d states, %d stranded (orphaned claim)", states, stranded)
155
+ }
156
+
157
+ // TestCompetingClaim_NewProtocolHeals: stale/terminal takeover means no
158
+ // reachable state leaves the message unconsumable while a consumer lives —
159
+ // and two consumers can never both record it.
160
+ func TestCompetingClaim_NewProtocolHeals(t *testing.T) {
161
+ states, stranded, multi := mcExplore(true)
162
+ if multi {
163
+ t.Fatal("two consumers both recorded the message")
164
+ }
165
+ // Stranded states remain possible only when *every* consumer is dead —
166
+ // nothing alive can ever consume. Count them separately.
167
+ if stranded > 0 {
168
+ t.Logf("new protocol: %d stranded states (all-dead only, unavoidable)", stranded)
169
+ }
170
+ t.Logf("new protocol: %d states explored, no violation", states)
171
+ }
172
+
173
+ // TestCompetingClaim_NoDoubleConsumeAcrossDeath: the consume event itself is
174
+ // exclusive even with takeover: a second consumer can only consume after a
175
+ // takeover, and takeover requires the first claim to be void.
176
+ func TestCompetingClaim_NoDoubleConsumeAcrossDeath(t *testing.T) {
177
+ // Directed check: enumerate states where consumedBy has both consumers.
178
+ start := mcState{msg: "unclaimed", alive: [2]bool{true, true}}
179
+ seen := map[string]bool{start.key(): true}
180
+ queue := []mcState{start}
181
+ for len(queue) > 0 {
182
+ s := queue[0]
183
+ queue = queue[1:]
184
+ if s.killed[0] && s.killed[1] {
185
+ t.Fatalf("double consume reachable: %+v", s)
186
+ }
187
+ for _, n := range mcSuccessors(s, true) {
188
+ if k := n.key(); !seen[k] {
189
+ seen[k] = true
190
+ queue = append(queue, n)
191
+ }
192
+ }
193
+ }
194
+ }
@@ -0,0 +1,128 @@
1
+ package spec
2
+
3
+ // Exhaustive model checker for EpochFencing.tla (2 workers, MaxEpoch=4).
4
+ // Same results TLC would report:
5
+ //
6
+ // java -jar tla2tools.jar -config EpochFencing_new.cfg EpochFencing.tla
7
+ //
8
+ // new (Fenced=TRUE): no write ever commits under a stale epoch.
9
+ // old (Fenced=FALSE): a stale-epoch write — including one issued by the
10
+ // same worker between lease loss and reacquisition — is reachable.
11
+
12
+ import (
13
+ "fmt"
14
+ "testing"
15
+ )
16
+
17
+ type efState struct {
18
+ epoch int
19
+ holder string // "", w1, w2
20
+ held [2]int
21
+ wrote [2]bool
22
+ staleWrite bool
23
+ }
24
+
25
+ func (s efState) key() string {
26
+ return fmt.Sprintf("%d|%s|%d%d|%v%v|%v",
27
+ s.epoch, s.holder, s.held[0], s.held[1],
28
+ s.wrote[0], s.wrote[1], s.staleWrite)
29
+ }
30
+
31
+ var efWorkers = [2]string{"w1", "w2"}
32
+ const efMaxEpoch = 4
33
+
34
+ func efSuccessors(s efState, fenced bool) []efState {
35
+ var out []efState
36
+ for i, w := range efWorkers {
37
+ // Acquire: mint a fresh epoch, become holder.
38
+ if s.epoch < efMaxEpoch {
39
+ n := s
40
+ n.epoch = s.epoch + 1
41
+ n.holder = w
42
+ n.held[i] = n.epoch
43
+ out = append(out, n)
44
+ }
45
+ // WWrite.
46
+ if fenced {
47
+ if !s.wrote[i] && s.holder == w && s.held[i] == s.epoch && s.epoch > 0 {
48
+ n := s
49
+ n.wrote[i] = true
50
+ out = append(out, n)
51
+ }
52
+ } else if s.held[i] > 0 && !s.wrote[i] {
53
+ n := s
54
+ n.wrote[i] = true
55
+ if s.holder != w || s.held[i] != s.epoch {
56
+ n.staleWrite = true
57
+ }
58
+ out = append(out, n)
59
+ }
60
+ }
61
+ // Expire: holder loses lease; its held epoch stays (now stale).
62
+ if s.holder != "" {
63
+ n := s
64
+ n.holder = ""
65
+ out = append(out, n)
66
+ }
67
+ return out
68
+ }
69
+
70
+ func efReach(fenced bool, visit func(efState) bool) int {
71
+ init := efState{}
72
+ seen := map[string]bool{init.key(): true}
73
+ queue := []efState{init}
74
+ visited := 0
75
+ for len(queue) > 0 {
76
+ s := queue[0]
77
+ queue = queue[1:]
78
+ visited++
79
+ if !visit(s) {
80
+ return visited
81
+ }
82
+ for _, n := range efSuccessors(s, fenced) {
83
+ if k := n.key(); !seen[k] {
84
+ seen[k] = true
85
+ queue = append(queue, n)
86
+ }
87
+ }
88
+ }
89
+ return visited
90
+ }
91
+
92
+ func TestEpochFencing_NoStaleWrite(t *testing.T) {
93
+ var bad *efState
94
+ n := efReach(true, func(s efState) bool {
95
+ if s.staleWrite {
96
+ b := s
97
+ bad = &b
98
+ return false
99
+ }
100
+ return true
101
+ })
102
+ if bad != nil {
103
+ t.Fatalf("stale write at %+v", *bad)
104
+ }
105
+ t.Logf("fenced: %d states, no stale write", n)
106
+ }
107
+
108
+ func TestEpochFencing_UnfencedViolated(t *testing.T) {
109
+ var bad *efState
110
+ n := efReach(false, func(s efState) bool {
111
+ if s.staleWrite {
112
+ b := s
113
+ bad = &b
114
+ return false
115
+ }
116
+ return true
117
+ })
118
+ if bad == nil {
119
+ t.Fatal("expected a stale-write state under unfenced writes")
120
+ }
121
+ t.Logf("unfenced: violation after %d states at %+v", n, *bad)
122
+ }
123
+
124
+ // NOTE: a same-worker reacquisition test cannot live here: this state
125
+ // machine keeps one heldEpoch per worker, so a re-acquire overwrites the
126
+ // old credential and fencing on worker id alone already passes. The
127
+ // per-run model EpochFencingRuns.tla covers that case (worker-id fencing
128
+ // violates NoStaleWrite there; epoch fencing holds).
@@ -0,0 +1,3 @@
1
+ module github.com/durax-io/schema/spec
2
+
3
+ go 1.23