samagotchi 0.190.0 → 0.191.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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -1
  3. data/docs/architecture.md +8 -7
  4. data/docs/cli.md +6 -3
  5. data/docs/context.md +9 -2
  6. data/docs/guardrails.md +5 -1
  7. data/docs/internals/attached-context.md +3 -1
  8. data/docs/internals/peers.md +15 -3
  9. data/docs/internals/remote-sessions.md +2 -2
  10. data/docs/internals/session-lifecycle.md +213 -12
  11. data/docs/peers.md +3 -1
  12. data/docs/plugins.md +2 -1
  13. data/docs/scheduling.md +31 -7
  14. data/docs/sessions.md +11 -11
  15. data/docs/sub-agent.md +1 -1
  16. data/lib/samagotchi/bridge.rb +1 -1
  17. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/known-names/plugin.rb +17 -1
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/context_command.rb +5 -1
  21. data/lib/samagotchi/context_sources.rb +28 -0
  22. data/lib/samagotchi/continue_intent.rb +23 -43
  23. data/lib/samagotchi/hold_stop.rb +5 -2
  24. data/lib/samagotchi/participants.rb +13 -5
  25. data/lib/samagotchi/peer_say.rb +29 -14
  26. data/lib/samagotchi/plugin/sessions.rb +9 -5
  27. data/lib/samagotchi/schedule_command.rb +5 -1
  28. data/lib/samagotchi/schedules/prune_part.rb +138 -38
  29. data/lib/samagotchi/schedules.rb +29 -6
  30. data/lib/samagotchi/send_command.rb +6 -6
  31. data/lib/samagotchi/session_access/ask.rb +9 -3
  32. data/lib/samagotchi/session_access/exchange.rb +6 -2
  33. data/lib/samagotchi/session_access/local.rb +104 -31
  34. data/lib/samagotchi/session_access/remote.rb +10 -9
  35. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  36. data/lib/samagotchi/session_access.rb +17 -7
  37. data/lib/samagotchi/session_chain/delete.rb +100 -47
  38. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  39. data/lib/samagotchi/session_chain/links.rb +68 -9
  40. data/lib/samagotchi/session_chain/successor.rb +78 -0
  41. data/lib/samagotchi/session_continue.rb +108 -40
  42. data/lib/samagotchi/session_inbox.rb +1 -1
  43. data/lib/samagotchi/session_inbox_delivery.rb +113 -26
  44. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  45. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  46. data/lib/samagotchi/session_lifecycle.rb +13 -2
  47. data/lib/samagotchi/session_manager/delivery.rb +61 -23
  48. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  49. data/lib/samagotchi/session_manager/lifecycle.rb +50 -14
  50. data/lib/samagotchi/session_manager/removal.rb +65 -13
  51. data/lib/samagotchi/session_manager/spawn.rb +14 -6
  52. data/lib/samagotchi/session_retention.rb +28 -7
  53. data/lib/samagotchi/session_transition.rb +315 -0
  54. data/lib/samagotchi/sessions_command.rb +1 -1
  55. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  56. data/lib/samagotchi/version.rb +1 -1
  57. data/lib/samagotchi/web/app.rb +10 -2
  58. data/lib/samagotchi/web/peer_routes.rb +5 -2
  59. data/lib/samagotchi/web/session_access_routes.rb +5 -2
  60. data/lib/samagotchi/web/session_control.rb +6 -1
  61. data/lib/samagotchi/web/session_create.rb +1 -1
  62. data/lib/samagotchi/worker_boot.rb +28 -6
  63. metadata +3 -1
@@ -7,6 +7,8 @@ require_relative "client_id"
7
7
  require_relative "worker_presence"
8
8
  require_relative "continue_intent"
9
9
  require_relative "session_chain/links"
10
+ require_relative "session_chain/successor"
11
+ require_relative "session_transition"
10
12
 
11
13
  module Samagotchi
12
14
  # Loaded on first use: this autoload keeps SessionManager and its ~80
@@ -41,7 +43,7 @@ module Samagotchi
41
43
 
42
44
  # The refusal of a send whose link is still being continued once the
43
45
  # sender's wait is over.
44
- def continuing_refusal = "being continued as #{id[0, 8]}; send again in a moment"
46
+ def continuing_refusal = "#{SessionChain::Continued.new(asked, id, in_flight: true).message}; send again in a moment"
45
47
  end
46
48
 
47
49
  # A delivery's outcome.
@@ -55,7 +57,9 @@ module Samagotchi
55
57
  # worker comes: it waits for the next start)
56
58
  # @!attribute wake [Symbol] WakePolicy#decide's outcome, :woken for a
57
59
  # start made, or the refusal (:gone, :deleting: a deleter holds its
58
- # lock, :owned: a one-turn chi run's, :scratch). :deleting after the
60
+ # lock, :owned: a one-turn chi run's, :scratch; a :shared row's
61
+ # :continued, a continue holding the transition lock names its new
62
+ # link, or :busy, another transition holds it: Hold.under). :deleting after the
59
63
  # write (status :waits) is a delete that took the lock meanwhile: the
60
64
  # file goes with the session (a caller that reports the delivery takes
61
65
  # it back, SessionInbox.withdraw)
@@ -85,7 +89,21 @@ module Samagotchi
85
89
  # (input from a person un-archives it): send (and leave) only
86
90
  # @!attribute refuse_tui [Boolean] a one-turn chi run's session refuses it
87
91
  # @!attribute refuse_scratch [Boolean] a chi scratch session refuses it
88
- WakePolicy = Data.define(:kind, :resolves, :starts, :unstops, :starts_archived, :refuse_tui, :refuse_scratch) do
92
+ # @!attribute hold [Symbol] what the delivery holds of the session's
93
+ # transition lock around its check and write (Hold.under, in the
94
+ # seats: Dispatch.deliver / .wake, SessionManager.deliver_turn):
95
+ # :shared (a transition holding it refuses the delivery, naming the
96
+ # continue's new link when one is in flight, else busy) or :none (it
97
+ # goes in as before, for +hold_reason+). Every row names it.
98
+ # @!attribute hold_reason [String, nil] why a :none row takes no hold
99
+ # (nil for :shared)
100
+ WakePolicy = Data.define(:kind, :resolves, :starts, :unstops, :starts_archived, :refuse_tui, :refuse_scratch,
101
+ :hold, :hold_reason) do
102
+ def initialize(hold:, hold_reason: nil, **) = super
103
+
104
+ # Whether the delivery takes the transition lock shared.
105
+ def shared? = hold == :shared
106
+
89
107
  # @return [WakePolicy]
90
108
  # @raise [ArgumentError] no such kind
91
109
  def self.for(kind) = WakePolicy::ROWS.fetch(kind) { raise ArgumentError, "no inbox kind #{kind.inspect}" }
@@ -153,24 +171,39 @@ module Samagotchi
153
171
  # and never un-archives a retired chain).
154
172
  WakePolicy::ROWS = {
155
173
  send: WakePolicy.new(kind: :send, resolves: :head, starts: true, unstops: true, starts_archived: true,
156
- refuse_tui: true, refuse_scratch: true),
174
+ refuse_tui: true, refuse_scratch: true, hold: :shared),
175
+ # A note's moves are its own: one written before a continue's
176
+ # NoteMove.move moves, one after is adopted by the new link
177
+ # (NoteMove.adoption), a failed continue's go back (give_back), and the
178
+ # new link's boot writes its own (objectives) inside the continue's
179
+ # hold: a refusal would lose what those already carry.
157
180
  note: WakePolicy.new(kind: :note, resolves: :head, starts: false, unstops: false, starts_archived: false,
158
- refuse_tui: true, refuse_scratch: true),
181
+ refuse_tui: true, refuse_scratch: true, hold: :none,
182
+ hold_reason: "NoteMove moves, adopts and gives back a note written during a continue; " \
183
+ "the new link's boot writes its own inside the continue's hold"),
159
184
  push: WakePolicy.new(kind: :push, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
160
- refuse_tui: false, refuse_scratch: false),
185
+ refuse_tui: false, refuse_scratch: false, hold: :shared),
161
186
  # A peer agent's message (chi peer say, PeerMailbox.post): a push's row.
162
187
  peer: WakePolicy.new(kind: :peer, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
163
- refuse_tui: false, refuse_scratch: false),
188
+ refuse_tui: false, refuse_scratch: false, hold: :shared),
164
189
  ring: WakePolicy.new(kind: :ring, resolves: :reader, starts: true, unstops: false, starts_archived: false,
165
- refuse_tui: false, refuse_scratch: false),
190
+ refuse_tui: false, refuse_scratch: false, hold: :none,
191
+ hold_reason: "ChildReports rings once, no retry; a continue's ChildMove moves the rings " \
192
+ "(return_rings gives them back), and its undo wakes for them on its own token"),
166
193
  fresh_verdict: WakePolicy.new(kind: :fresh_verdict, resolves: :pinned, starts: false, unstops: false,
167
- starts_archived: false, refuse_tui: false, refuse_scratch: false),
194
+ starts_archived: false, refuse_tui: false, refuse_scratch: false, hold: :none,
195
+ hold_reason: "VerifyFresh.forward writes once, no retry; the verdict is for " \
196
+ "the card in the parent it names, continued or not, and starts " \
197
+ "no worker"),
168
198
  # Not a delivery: a worker's own leave starting its successor for
169
199
  # what waits (input, rings) or a restart (WorkerBoot, after the
170
200
  # lock's release). A stop wins; an archived session's input still
171
201
  # starts it, as a send's would have.
172
202
  leave: WakePolicy.new(kind: :leave, resolves: :pinned, starts: true, unstops: false, starts_archived: true,
173
- refuse_tui: false, refuse_scratch: false),
203
+ refuse_tui: false, refuse_scratch: false, hold: :none,
204
+ hold_reason: "a respawn after the worker's own release spans two processes (outside " \
205
+ "the lock, D3); a refusal would drop a restart or queued input's start with " \
206
+ "no retry, and a continue stops the worker first (the stop wins)"),
174
207
  # A turn delivery's unattended senders (deliver_turn reads the row by
175
208
  # the sender, ClientId.wake_kind): they start an idle session as a send
176
209
  # does, but a stop and an archive are the owner's (the sender is
@@ -180,7 +213,7 @@ module Samagotchi
180
213
  # doesn't name.
181
214
  **%i[schedule plugin delegate participant agent automatic].to_h do |kind|
182
215
  [kind, WakePolicy.new(kind: kind, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
183
- refuse_tui: true, refuse_scratch: true)]
216
+ refuse_tui: true, refuse_scratch: true, hold: :shared)]
184
217
  end
185
218
  }.freeze
186
219
 
@@ -190,7 +223,8 @@ module Samagotchi
190
223
 
191
224
  # +id+ for a pinned kind, or for an id not archived (the cheap check
192
225
  # first: only an archived id is walked, with one Session.list).
193
- # Else the walk forward over archived links that have a successor:
226
+ # Else the walk forward over archived links that have a successor (a
227
+ # schedule's pruned anchor: its head, Links#anchor_forward):
194
228
  # to the first link not archived, or the last (a loop a hand-edited
195
229
  # file could make ends where it started); a :reader kind goes one hop
196
230
  # at most. Then, for a kind that would un-archive the link it reaches
@@ -233,7 +267,7 @@ module Samagotchi
233
267
  # send to an archived link with a successor is refused, and chi send
234
268
  # resolves again).
235
269
  def continuing(resolved, state_dir)
236
- successor = ContinueIntent.in_flight(resolved.id, state_dir: state_dir)
270
+ successor = SessionChain::Successor.in_flight(resolved.id, state_dir: state_dir)&.id
237
271
  return nil if successor.nil?
238
272
 
239
273
  via = Session.exist?(successor, state_dir: state_dir) ? :head : :continuing
@@ -241,6 +275,42 @@ module Samagotchi
241
275
  end
242
276
  end
243
277
 
278
+ # What a delivery holds of its session's transition lock (its row's
279
+ # WakePolicy#hold), taken once in each seat (Dispatch.deliver / .wake,
280
+ # SessionManager.deliver_turn) around the check, the write and the
281
+ # start, so no transition (a continue) starts in between; never taken
282
+ # again inside it (a nested seat on this thread opens a second shared
283
+ # hold, which a shared one never conflicts with).
284
+ module Hold
285
+ module_function
286
+
287
+ # The block under +policy+'s hold of +id+, or, when a transition
288
+ # holds the lock now (not waited for), +refused+ called with who
289
+ # continues +id+ (the holding continue's new link, in flight, else a
290
+ # saved successor: SessionChain::Successor) or nil (busy: Busy's
291
+ # words). A :none row,
292
+ # or an id that is no session id (the caller's own refusal follows),
293
+ # is the block alone.
294
+ # @param refused [#call] (successor) the refusal's value
295
+ # @return the block's value, or +refused+'s
296
+ def under(policy, id, state_dir, refused:)
297
+ return yield unless policy.shared? && Session.valid_id?(id)
298
+
299
+ SessionTransition.shared(id, state_dir: state_dir) do |free|
300
+ next yield if free
301
+
302
+ # A delete, a stop or an archive holding it names nobody (Busy's
303
+ # "being deleted": a link being deleted or pruned is not
304
+ # continued anywhere new); else the holder's in-flight continue
305
+ # first (its new link may be saved already), then a saved one.
306
+ next refused.call(nil) if SessionTransition.other_than_continue?(SessionTransition.holder(id, state_dir: state_dir))
307
+
308
+ refused.call(SessionChain::Successor.in_flight(id, state_dir: state_dir) ||
309
+ SessionChain::Successor.of(id, state_dir: state_dir, anchor: false))
310
+ end
311
+ end
312
+ end
313
+
244
314
  # SessionInbox.deliver and SessionInbox.wake.
245
315
  module Dispatch
246
316
  # What a start each kind makes is logged as (SessionManager.start_for_inbox).
@@ -249,10 +319,11 @@ module Samagotchi
249
319
  module_function
250
320
 
251
321
  # Deliver one +kind+ of thing to session +target+, in this order:
252
- # resolve the link (Head.resolve), refuse (WakePolicy#refusal: before
253
- # any write), write (the block: the kind's own writer, given the id
254
- # it writes under), read the presence once, then decide and apply
255
- # (#wake).
322
+ # resolve the link (Head.resolve), then under the row's transition
323
+ # hold (Hold.under: refused :continued or :busy while a transition
324
+ # holds it) refuse (WakePolicy#refusal: before any write), write (the
325
+ # block: the kind's own writer, given the id it writes under), read
326
+ # the presence once, then decide and apply (#wake).
256
327
  # @param wake [Boolean] the delivery may ask for a worker; the block's
257
328
  # value says whether it does (truthy: asks)
258
329
  # @param pin [Boolean] write under +target+ itself, whatever the kind's
@@ -273,22 +344,38 @@ module Samagotchi
273
344
  resolved = Resolved.new(id: target, asked: target, via: :pinned) if pin
274
345
  resolved ||= Head.resolve(kind, target, state_dir: sd)
275
346
  at = policy.resolves == :reader ? resolved.asked : resolved.id
276
- if (why = refusal(policy, at, sd, owner))
277
- return Delivered.new(kind: kind, id: resolved.id, asked: resolved.asked, via: resolved.via, status: :refused,
347
+ Hold.under(policy, at, sd, refused: ->(successor) { held(policy, resolved, successor) }) do
348
+ if (why = refusal(policy, at, sd, owner))
349
+ next Delivered.new(kind: kind, id: resolved.id, asked: resolved.asked, via: resolved.via, status: :refused,
278
350
  wake: why)
279
- end
351
+ end
280
352
 
281
- asks = yield(at)
282
- apply(policy, resolved, sd, wake: wake && asks ? true : false, owner: owner, start: start)
353
+ asks = yield(at)
354
+ apply(policy, resolved, sd, wake: wake && asks ? true : false, owner: owner, start: start)
355
+ end
283
356
  end
284
357
 
285
358
  # The wake half of #deliver alone, for a delivery already on disk (a
286
- # failed continue's previous link with rings that came meanwhile).
359
+ # failed continue's previous link with rings that came meanwhile),
360
+ # under the row's hold as #deliver's, or +hold+ instead (:shared: the
361
+ # ring's wake, SessionManager.wake_for_report, whose row holds none
362
+ # for its write).
287
363
  # @return [Delivered]
288
- def wake(kind, target, state_dir: nil, owner: nil, start: nil)
364
+ def wake(kind, target, state_dir: nil, owner: nil, start: nil, hold: nil)
289
365
  sd = state_dir || Session.default_state_dir
290
- apply(WakePolicy.for(kind), Head.resolve(kind, target, state_dir: sd), sd, wake: true, owner: owner,
291
- start: start)
366
+ policy = WakePolicy.for(kind)
367
+ policy = policy.with(hold: hold, hold_reason: nil) if hold
368
+ resolved = Head.resolve(kind, target, state_dir: sd)
369
+ Hold.under(policy, resolved.id, sd, refused: ->(successor) { held(policy, resolved, successor) }) do
370
+ apply(policy, resolved, sd, wake: true, owner: owner, start: start)
371
+ end
372
+ end
373
+
374
+ # A delivery a transition's hold refused, nothing written: :continued
375
+ # (+successor+ names the continue's new link) or :busy.
376
+ def held(policy, resolved, successor)
377
+ Delivered.new(kind: policy.kind, id: resolved.id, asked: resolved.asked, via: resolved.via, status: :refused,
378
+ wake: successor ? :continued : :busy)
292
379
  end
293
380
 
294
381
  # Every kind reads the presence: a session being deleted refuses
@@ -10,8 +10,12 @@ module Samagotchi
10
10
  # whoever runs the session next: wait; :gone, :owned and :deleting (a
11
11
  # deleter holds the lock) are refusals. (:off and :scratch are
12
12
  # op-local: a delivery that asks no worker, a scratch session's file.)
13
+ # A :shared row's delivery while a transition holds the lock
14
+ # (SessionInbox::Hold, Delivered#wake) is :busy, or :continued when the
15
+ # holder is a continue naming its new link (a resolution fact, as
16
+ # continuing is: TRANSITIONING names :busy).
13
17
  DELIVERY_CELLS = { start: :go, live: :go, starting: :wait, stopped: :wait, archived: :wait, none: :wait,
14
- gone: :gone, owned: :owned, deleting: :deleting }.freeze
18
+ gone: :gone, owned: :owned, deleting: :deleting, busy: :busy, continued: :continued }.freeze
15
19
 
16
20
  # The operations that are not inbox deliveries, in the order of LITERAL's
17
21
  # rows: resume_session, restart_session, stop_session, archive
@@ -66,5 +70,20 @@ module Samagotchi
66
70
  end
67
71
  deliveries.merge(literal).freeze
68
72
  end.call
73
+
74
+ # {op => cell} for the operations that answer otherwise while a
75
+ # transition holds the session's lock, in every state (it is a fact
76
+ # beside the state, not one of STATES: any state can be held): each
77
+ # delivery whose WakePolicy row holds :shared is refused :busy
78
+ # (SessionInbox::Hold, before its own checks); a :none row answers its
79
+ # state's cell. TAKES_LOCK: the operations that take the lock
80
+ # themselves: a stop, exclusively (stop_session: Busy, nothing marked),
81
+ # and the ring's column, which is a ring's wake (wake_for_report: shared
82
+ # across its decide and resume; the ring's write, a :none row, holds
83
+ # none and still goes in). The other literal operations read none
84
+ # (archive's column is archivable!, its checks only).
85
+ TAKES_LOCK = { stop: :busy, ring: :busy }.freeze
86
+ TRANSITIONING = SessionInbox::WakePolicy::ROWS.filter_map { |kind, policy| [kind, :busy] if policy.shared? }
87
+ .to_h.merge(TAKES_LOCK).freeze
69
88
  end
70
89
  end
@@ -13,12 +13,17 @@ module Samagotchi
13
13
  # @!attribute continuing [String, nil] ContinueIntent.in_flight's
14
14
  # successor: a fact, not a state (only a send's or a schedule's link
15
15
  # resolution reads it)
16
- Reading = Data.define(:state, :presence, :continuing) do
16
+ # @!attribute transitioning [Boolean] a transition holds the session's
17
+ # transition lock now (SessionTransition.held?): a fact, not a state,
18
+ # orthogonal to them all; a :shared delivery row answers TRANSITIONING's
19
+ # cell then (SessionLifecycle.allowed's transitioning:)
20
+ Reading = Data.define(:state, :presence, :continuing, :transitioning) do
17
21
  # @param presence [WorkerPresence] with its link read
18
22
  # @param continuing [String, nil]
23
+ # @param transitioning [Boolean]
19
24
  # @return [Reading]
20
- def self.derive(presence, continuing: nil)
21
- new(state: state_of(presence), presence: presence, continuing: continuing)
25
+ def self.derive(presence, continuing: nil, transitioning: false)
26
+ new(state: state_of(presence), presence: presence, continuing: continuing, transitioning: transitioning)
22
27
  end
23
28
 
24
29
  # The first of STATES whose facts hold. A lock held by someone that is
@@ -60,6 +65,7 @@ module Samagotchi
60
65
 
61
66
  def facts = presence
62
67
  def continuing? = !continuing.nil?
68
+ def transitioning? = transitioning == true
63
69
  end
64
70
  end
65
71
  end
@@ -3,6 +3,7 @@
3
3
  require_relative "session"
4
4
  require_relative "worker_presence"
5
5
  require_relative "continue_intent"
6
+ require_relative "session_transition"
6
7
 
7
8
  module Samagotchi
8
9
  # A session's lifecycle state, derived from what is on disk now: one read of
@@ -27,6 +28,8 @@ module Samagotchi
27
28
  autoload :Reading, File.expand_path("session_lifecycle/reading", __dir__)
28
29
  autoload :CANONICAL, File.expand_path("session_lifecycle/canonical", __dir__)
29
30
  autoload :ALLOWED, File.expand_path("session_lifecycle/allowed", __dir__)
31
+ autoload :TRANSITIONING, File.expand_path("session_lifecycle/allowed", __dir__)
32
+ autoload :TAKES_LOCK, File.expand_path("session_lifecycle/allowed", __dir__)
30
33
 
31
34
  # The cell words that are no refusal, per operation: a resume that finds
32
35
  # a worker there or one being started waits for it; a restart's
@@ -35,8 +38,15 @@ module Samagotchi
35
38
 
36
39
  module_function
37
40
 
41
+ # @param transitioning [Boolean] a transition holds the session's lock
42
+ # (Reading#transitioning): an op TRANSITIONING names answers its cell
43
+ # there, whatever the state
38
44
  # @return [Symbol] the cell of +op+ in +state+ (ALLOWED)
39
- def allowed(op, state) = ALLOWED.fetch(op).fetch(state)
45
+ def allowed(op, state, transitioning: false)
46
+ return TRANSITIONING.fetch(op) if transitioning && TRANSITIONING.key?(op)
47
+
48
+ ALLOWED.fetch(op).fetch(state)
49
+ end
40
50
 
41
51
  # A cell as :go, :wait or :refused: :go and :wait are themselves, an
42
52
  # operation's own words (VERDICT_WORDS) theirs, every other a refusal.
@@ -54,7 +64,8 @@ module Samagotchi
54
64
  def read(session_id, state_dir: nil, owner: :read)
55
65
  sd = state_dir || Session.default_state_dir
56
66
  presence = WorkerPresence.read(session_id, state_dir: sd, owner: owner, link: :look)
57
- Reading.derive(presence, continuing: ContinueIntent.in_flight(session_id, state_dir: sd))
67
+ Reading.derive(presence, continuing: ContinueIntent.in_flight(session_id, state_dir: sd),
68
+ transitioning: SessionTransition.held?(session_id, state_dir: sd))
58
69
  end
59
70
  end
60
71
  end
@@ -3,13 +3,14 @@
3
3
  require_relative "../turn_anchors"
4
4
  require_relative "../archive_store"
5
5
  require_relative "../client_id"
6
- require_relative "../continue_intent"
7
6
  require_relative "../degrade"
8
7
  require_relative "../delivery"
9
8
  require_relative "../log"
10
9
  require_relative "../session"
11
10
  require_relative "../session_chain/links"
11
+ require_relative "../session_chain/successor"
12
12
  require_relative "../session_inbox"
13
+ require_relative "../session_transition"
13
14
  require_relative "../steer"
14
15
  require_relative "../worker_link"
15
16
  require_relative "../worker_presence"
@@ -61,7 +62,7 @@ module Samagotchi
61
62
  refused = error == Delivery::QUEUE_UNAVAILABLE["error"] ||
62
63
  error == Delivery::ASK_UNAVAILABLE["error"] ||
63
64
  error == Delivery::PAIR_UNAVAILABLE["error"] ||
64
- continued? || wake_refused? || deleting? || DeliverResult::REMOTE_REFUSALS.include?(error)
65
+ continued? || busy? || wake_refused? || deleting? || DeliverResult::REMOTE_REFUSALS.include?(error)
65
66
  "#{refused ? "refused" : "failed"}: #{detail || "could not queue it"}"
66
67
  end
67
68
 
@@ -74,6 +75,11 @@ module Samagotchi
74
75
  # (deliver_turn's follow:); the sender resolves the head again.
75
76
  def continued? = error == DeliverResult::CONTINUED
76
77
 
78
+ # A transition (another change than a continue naming its new link)
79
+ # held the session's transition lock (DeliverResult::BUSY): nothing
80
+ # went in; the sender tries again in a moment.
81
+ def busy? = error == DeliverResult::BUSY
82
+
77
83
  # A stopped or archived session its sender may not wake
78
84
  # (DeliverResult::STOPPED / ARCHIVED: only a person's message does).
79
85
  def wake_refused? = DeliverResult::WAKE_REFUSALS.include?(error)
@@ -97,6 +103,12 @@ module Samagotchi
97
103
  # A followed send's refusal (DeliverResult#continued?), here and from a
98
104
  # remote's turn route alike.
99
105
  DeliverResult::CONTINUED = "link_continued"
106
+ # Any sender's turn while a transition holds the session's transition
107
+ # lock and names no continue's new link (DeliverResult#busy?): 409,
108
+ # nothing written, its detail SessionTransition::Busy's words. The code
109
+ # a continue's own busy refusal has on the wire too (SessionContinue::
110
+ # Refused :transition_busy).
111
+ DeliverResult::BUSY = "transition_busy"
100
112
  # An unattended sender's turn (a schedule, a plugin, a delegate
101
113
  # follow-up, a participant: ClientId.wake_kind) to a session its owner
102
114
  # stopped or archived: refused, nothing written (a 409 from chi web).
@@ -173,7 +185,11 @@ module Samagotchi
173
185
  # continue took since is refused (:refused 409 link_continued, nothing
174
186
  # written: #follow_guard) rather than un-archived beside its new link;
175
187
  # the sender resolves again. Others name the id they mean (the web
176
- # composer, schedules, delegates, plugins, participants).
188
+ # composer, schedules, delegates, plugins, participants). Any
189
+ # sender's turn is delivered under the session's transition lock
190
+ # shared (its row's hold, SessionInbox::Hold): while a transition
191
+ # holds it, :refused 409 link_continued naming a continue's new link
192
+ # (successor_id), else 409 transition_busy (DeliverResult::BUSY).
177
193
  # @param manager [#resume_session, #write_turn_input] this class, or a
178
194
  # stand-in (the web's specs); #session_owner is optional
179
195
  # @param bridge [#call, nil] returns the BridgeClient or nil; defaults to
@@ -194,7 +210,7 @@ module Samagotchi
194
210
  bridge: nil, enqueued_id: nil)
195
211
  raise ArgumentError, "deliver_turn needs the sender's client_id" if client_id.to_s.empty?
196
212
 
197
- follow_guard(session_id, state_dir, follow) do
213
+ follow_guard(session_id, state_dir, follow, SessionInbox::WakePolicy.for_sender(client_id)) do
198
214
  deliver_turn_now(session_id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
199
215
  no_interrupt: no_interrupt, author: author, pending_limit: pending_limit,
200
216
  anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge,
@@ -202,31 +218,53 @@ module Samagotchi
202
218
  end
203
219
  end
204
220
 
205
- # A followed send (deliver_turn's follow:) to an archived link: refused
206
- # when a continue took it (a successor saved, or a continue holding its
207
- # lock now: its successor comes), else the delivery under a shared hold
208
- # of the continue lock (ContinueIntent.hold), so no continue starts
209
- # between this check and the input going in. Any other delivery, or
210
- # a link not archived, is the block alone. Head.resolve answers the
211
- # sender before the delivery: a continue that ends or starts in
212
- # between is caught here, and chi send resolves again (SendCommand#target).
221
+ # The delivery under the sender's row's transition hold
222
+ # (SessionInbox::Hold.under: SessionTransition.shared, never waited
223
+ # for), across all of it: the resume, the Bridge's wait and post, the
224
+ # file and the second liveness check (a frozen worker's post, up to
225
+ # BridgeClient::READ_TIMEOUT, keeps a continue of the session waiting
226
+ # that long, and refused busy past its LOCK_WAIT), so no transition
227
+ # starts between the check and the input going in. Refused, nothing
228
+ # written, while one holds it: link_continued naming the continue's
229
+ # new link, else transition_busy. Inside it, a followed send (follow:)
230
+ # to an archived link a continue took (a successor saved) is refused
231
+ # too: chi send resolves again (SendCommand#target). Head.resolve
232
+ # answers the sender before the delivery: a continue that ends or
233
+ # starts in between is caught here.
213
234
  # @return [DeliverResult] the block's, or the refusal
214
- private def follow_guard(session_id, state_dir, follow)
235
+ private def follow_guard(session_id, state_dir, follow, policy)
215
236
  sd = state_dir || Session.default_state_dir
216
- return yield unless follow && Session.valid_id?(session_id) &&
217
- ArchiveStore.archived?(Session.session_dir(session_id, state_dir: sd))
218
-
219
- ContinueIntent.hold(session_id, state_dir: sd) do |held|
220
- successor = SessionChain::Links.new(state_dir: sd).next_of(session_id) if held
221
- next yield if held && successor.nil?
237
+ held = ->(successor) { held_refusal(session_id, successor, policy, sd) }
238
+ SessionInbox::Hold.under(policy, session_id, sd, refused: held) do
239
+ if follow && Session.valid_id?(session_id) && ArchiveStore.archived?(Session.session_dir(session_id, state_dir: sd)) &&
240
+ (successor = SessionChain::Successor.of(session_id, state_dir: sd, anchor: false))
241
+ next continued_refusal(session_id, successor)
242
+ end
222
243
 
223
- words = successor ? "being continued as #{successor[0, 8]}" : "being continued"
224
- DeliverResult.new(status: :refused, code: 409,
225
- ack: { "error" => DeliverResult::CONTINUED, "detail" => "#{words}; send again in a moment",
226
- "session_id" => session_id, "successor_id" => successor }.compact)
244
+ yield
227
245
  end
228
246
  end
229
247
 
248
+ # A turn a transition's hold refused: the continue's new link named
249
+ # (link_continued), else busy (transition_busy, Busy's words naming
250
+ # the holder: Busy.held).
251
+ private def held_refusal(session_id, successor, policy, state_dir)
252
+ Log.info(:worker, "send_transition_refused", sid: session_id[0, 8], kind: policy.kind,
253
+ successor: successor&.id.to_s[0, 8])
254
+ return continued_refusal(session_id, successor) if successor
255
+
256
+ DeliverResult.new(status: :refused, code: 409,
257
+ ack: { "error" => DeliverResult::BUSY, "detail" => SessionTransition::Busy.held(session_id, state_dir: state_dir).message,
258
+ "session_id" => session_id })
259
+ end
260
+
261
+ private def continued_refusal(session_id, successor)
262
+ DeliverResult.new(status: :refused, code: 409,
263
+ ack: { "error" => DeliverResult::CONTINUED,
264
+ "detail" => "#{SessionChain::Continued.for(session_id, successor).message}; send again in a moment",
265
+ "session_id" => session_id, "successor_id" => successor.id })
266
+ end
267
+
230
268
  private def deliver_turn_now(session_id, prompt:, client_id:, images:, delivery:, no_interrupt:, author:,
231
269
  pending_limit:, anchors:, state_dir:, manager:, bridge:, enqueued_id: nil)
232
270
  anchors = TurnAnchors.from(anchors)
@@ -4,6 +4,7 @@ require_relative "../analytics_file"
4
4
  require_relative "../session_inbox"
5
5
  require_relative "../worker_link"
6
6
  require_relative "../starting_marker"
7
+ require_relative "../session_transition"
7
8
 
8
9
  module Samagotchi
9
10
  class SessionManager
@@ -14,8 +15,10 @@ module Samagotchi
14
15
  # and is still empty. A turn's drawing (Bridge::TurnDrawings::FILE)
15
16
  # exists only after a turn that kept messages: never a skeleton file.
16
17
  # The starting marker is one too: a start left one behind; a fresh one
17
- # keeps the session from the deleters itself.
18
- EMPTY_SKELETON_FILES = ["pid", "owner.lock", WorkerLink::FILE, AnalyticsFile::NAME, StartingMarker::FILE].freeze
18
+ # keeps the session from the deleters itself. So is the transition lock
19
+ # (a send's shared hold leaves it: SessionInbox::Hold).
20
+ EMPTY_SKELETON_FILES = ["pid", "owner.lock", WorkerLink::FILE, AnalyticsFile::NAME, StartingMarker::FILE,
21
+ SessionTransition::LOCK].freeze
19
22
  EMPTY_DIRS = [SessionInbox::INPUT_DIR, SessionInbox::NOTES_DIR, "images"].freeze
20
23
  EMPTY_SKELETON_DIRS = (EMPTY_DIRS + [SessionInbox::OUTPUT_DIR]).freeze
21
24
 
@@ -11,6 +11,7 @@ require_relative "../reminder_carry"
11
11
  require_relative "../session"
12
12
  require_relative "../session_inbox"
13
13
  require_relative "../session_lifecycle"
14
+ require_relative "../session_transition"
14
15
  require_relative "../worker_link"
15
16
  require_relative "running_tasks"
16
17
 
@@ -93,6 +94,11 @@ module Samagotchi
93
94
  # orphan) waits for the worker to let go of the session, here or
94
95
  # through chi web (POST …/stop's wait, capped at it).
95
96
  STOP_WAIT = 10
97
+ # How long a stop waits for its session's transition lock (another
98
+ # change holding it: a continue, a delete, a send's shared hold) before
99
+ # it is refused (SessionTransition::Busy). An owner-side stop (a worker
100
+ # stopping its delegates) tries once (0): it holds its own owner.lock.
101
+ STOP_LOCK_WAIT = 10
96
102
  # The cancel reason of a turn a session stop cancels (Bridge::CANCEL_REASONS):
97
103
  # not the user's Stop, which only ends the turn ("user").
98
104
  STOP_CANCEL_REASON = "session_stopped"
@@ -215,29 +221,59 @@ module Samagotchi
215
221
  # A turn still running is canceled first (STOP_CANCEL_WAIT), as the
216
222
  # web's Cancel does, with reason STOP_CANCEL_REASON: its worker saves it. The TERM stops (and saves)
217
223
  # what still runs (WorkerSignals), with a short grace after the marker.
224
+ # The mark and the TERM run under the session's transition lock, held
225
+ # exclusively (kind :stop, +lock_wait+ seconds to take it; one this
226
+ # thread holds, a continue's or a delete's, passes through), never the
227
+ # cancel's Bridge wait or the owner wait: a send, a continue or a delete
228
+ # doesn't interleave with them, and a ring wake's start
229
+ # (#wake_for_report) comes before the stop or after it, whole.
230
+ # @param lock_wait [Numeric] 0 from a worker (it holds an owner.lock:
231
+ # one try, never a wait)
218
232
  # @return [Boolean, nil] with +wait+: whether the owner was gone in time
219
233
  # @raise [OwnedByTUI] when the interactive TUI owns the session
220
- def stop_session(session_id, state_dir: nil, wait: nil)
234
+ # @raise [SessionTransition::Busy] another change held the lock
235
+ # past +lock_wait+ (its words name the holder); nothing was marked
236
+ def stop_session(session_id, state_dir: nil, wait: nil, lock_wait: STOP_LOCK_WAIT)
221
237
  sd = state_dir || Session.default_state_dir
222
- owner = refuse_tui!(session_id, state_dir: sd)
238
+ refuse_tui!(session_id, state_dir: sd)
223
239
 
224
240
  cancel_running_turn(session_id, state_dir: sd)
225
- # Mark first: a worker that has not taken the lock yet sees it and exits.
226
- Session.mark_stopped(session_id, state_dir: sd)
227
- # A stop drops the reminders: a restart's hand-off no successor took
228
- # yet must not bring them back on the next resume.
229
- ReminderCarry.remove(Session.session_dir(session_id, state_dir: sd))
230
- # A deleter holding the lock (chi web, the CLI) is no worker to stop.
231
- pid = owner&.deleting? ? 0 : owner&.pid.to_i
232
- begin
233
- Process.kill("TERM", pid) if pid && pid > 0
234
- rescue Errno::ESRCH
235
- nil # already exited
241
+ under_stop_lock(session_id, sd, lock_wait) do
242
+ # The owner read again under the lock: a worker a ring wake started
243
+ # while the stop waited for it is the one to TERM.
244
+ owner = refuse_tui!(session_id, state_dir: sd)
245
+ # Mark first: a worker that has not taken the lock yet sees it and exits.
246
+ Session.mark_stopped(session_id, state_dir: sd)
247
+ # A stop drops the reminders: a restart's hand-off no successor took
248
+ # yet must not bring them back on the next resume.
249
+ ReminderCarry.remove(Session.session_dir(session_id, state_dir: sd))
250
+ # A deleter holding the lock (chi web, the CLI) is no worker to stop.
251
+ pid = owner&.deleting? ? 0 : owner&.pid.to_i
252
+ begin
253
+ Process.kill("TERM", pid) if pid && pid > 0
254
+ rescue Errno::ESRCH
255
+ nil # already exited
256
+ end
257
+ continue_stopped(pid)
236
258
  end
237
- continue_stopped(pid)
238
259
  wait_for_owner_release(session_id, timeout: wait, state_dir: sd) if wait
239
260
  end
240
261
 
262
+ # The block under +session_id+'s transition lock, kind :stop, for a
263
+ # saved session; a gone one's folder is never made again (the block
264
+ # alone: Session.mark_stopped's NotFound follows), and a lock file
265
+ # left for a session deleted meanwhile is taken back.
266
+ # @raise [SessionTransition::Busy]
267
+ private def under_stop_lock(session_id, state_dir, lock_wait, &)
268
+ return yield unless Session.exist?(session_id, state_dir: state_dir)
269
+
270
+ begin
271
+ SessionTransition.exclusive([session_id], kind: :stop, state_dir: state_dir, deadline: lock_wait, &)
272
+ ensure
273
+ SessionTransition.forget(session_id, state_dir: state_dir)
274
+ end
275
+ end
276
+
241
277
  # A stopped worker (SIGSTOP, Ctrl-Z) runs its TERM handler only once
242
278
  # continued: CONT it after the TERM (as ProcessGroup.stop does), so it
243
279
  # leaves now rather than outliving the stop's wait. Best effort: one the