samagotchi 0.190.1 → 0.192.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +13 -11
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +17 -6
  6. data/docs/configuration.md +6 -1
  7. data/docs/context.md +8 -1
  8. data/docs/internals/attached-context.md +3 -1
  9. data/docs/internals/inline-widgets.md +2 -1
  10. data/docs/internals/participants.md +1 -5
  11. data/docs/internals/peers.md +15 -3
  12. data/docs/internals/remote-sessions.md +5 -2
  13. data/docs/internals/session-lifecycle.md +233 -18
  14. data/docs/internals/web-frontend.md +107 -9
  15. data/docs/peers.md +3 -1
  16. data/docs/plugins.md +2 -1
  17. data/docs/scheduling.md +31 -7
  18. data/docs/sessions.md +12 -12
  19. data/docs/sub-agent.md +1 -1
  20. data/docs/testing.md +1 -2
  21. data/docs/thin-clients.md +98 -12
  22. data/lib/samagotchi/bridge.rb +3 -4
  23. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  24. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  25. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  26. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +2 -19
  29. data/lib/samagotchi/compat.rb +1 -7
  30. data/lib/samagotchi/config.rb +3 -0
  31. data/lib/samagotchi/context_command.rb +5 -1
  32. data/lib/samagotchi/context_sources.rb +28 -0
  33. data/lib/samagotchi/continue_intent.rb +23 -43
  34. data/lib/samagotchi/delivery.rb +1 -5
  35. data/lib/samagotchi/hold_stop.rb +5 -2
  36. data/lib/samagotchi/participants.rb +13 -5
  37. data/lib/samagotchi/peer_say.rb +29 -14
  38. data/lib/samagotchi/plugin/sessions.rb +9 -5
  39. data/lib/samagotchi/schedule_command.rb +6 -1
  40. data/lib/samagotchi/schedules/prune_part.rb +162 -41
  41. data/lib/samagotchi/schedules.rb +32 -15
  42. data/lib/samagotchi/send_command.rb +6 -6
  43. data/lib/samagotchi/session.rb +7 -0
  44. data/lib/samagotchi/session_access/ask.rb +9 -3
  45. data/lib/samagotchi/session_access/exchange.rb +6 -2
  46. data/lib/samagotchi/session_access/local.rb +103 -32
  47. data/lib/samagotchi/session_access/remote.rb +10 -9
  48. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  49. data/lib/samagotchi/session_access.rb +17 -7
  50. data/lib/samagotchi/session_chain/delete.rb +100 -47
  51. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  52. data/lib/samagotchi/session_chain/successor.rb +78 -0
  53. data/lib/samagotchi/session_continue.rb +112 -42
  54. data/lib/samagotchi/session_inbox.rb +1 -1
  55. data/lib/samagotchi/session_inbox_delivery.rb +111 -25
  56. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  57. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  58. data/lib/samagotchi/session_lifecycle.rb +17 -2
  59. data/lib/samagotchi/session_manager/delivery.rb +61 -29
  60. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  61. data/lib/samagotchi/session_manager/lifecycle.rb +68 -19
  62. data/lib/samagotchi/session_manager/listing.rb +2 -1
  63. data/lib/samagotchi/session_manager/removal.rb +67 -13
  64. data/lib/samagotchi/session_manager/spawn.rb +16 -9
  65. data/lib/samagotchi/session_manager.rb +4 -0
  66. data/lib/samagotchi/session_retention.rb +28 -7
  67. data/lib/samagotchi/session_row.rb +2 -0
  68. data/lib/samagotchi/session_transition.rb +361 -0
  69. data/lib/samagotchi/sessions_command.rb +1 -1
  70. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  71. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/app.rb +13 -3
  74. data/lib/samagotchi/web/ask_create.rb +138 -0
  75. data/lib/samagotchi/web/ask_routes.rb +56 -9
  76. data/lib/samagotchi/web/last_ask.rb +78 -0
  77. data/lib/samagotchi/web/peer_routes.rb +5 -2
  78. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  79. data/lib/samagotchi/web/public/answer_write.js +28 -0
  80. data/lib/samagotchi/web/public/app.js +72 -96
  81. data/lib/samagotchi/web/public/block_fix.js +30 -12
  82. data/lib/samagotchi/web/public/chains.js +3 -1
  83. data/lib/samagotchi/web/public/command_list.js +5 -3
  84. data/lib/samagotchi/web/public/composer.js +9 -6
  85. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  86. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  87. data/lib/samagotchi/web/public/drafts.js +278 -0
  88. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  89. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  90. data/lib/samagotchi/web/public/send_turn.js +51 -20
  91. data/lib/samagotchi/web/public/session_actions.js +80 -16
  92. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  93. data/lib/samagotchi/web/public/session_view.js +7 -2
  94. data/lib/samagotchi/web/public/turn_events.js +0 -2
  95. data/lib/samagotchi/web/public/unqueue.js +22 -9
  96. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  97. data/lib/samagotchi/web/public/views.js +12 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +11 -5
  99. data/lib/samagotchi/web/session_control.rb +8 -1
  100. data/lib/samagotchi/web/session_create.rb +51 -34
  101. data/lib/samagotchi/web/session_hub.rb +52 -36
  102. data/lib/samagotchi/web/session_summary.rb +45 -7
  103. data/lib/samagotchi/web/start_dir.rb +6 -4
  104. data/lib/samagotchi/worker_boot.rb +28 -6
  105. data/lib/samagotchi/worker_presence.rb +22 -6
  106. metadata +10 -1
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../continue_intent"
4
+ require_relative "links"
5
+
6
+ module Samagotchi
7
+ module SessionChain
8
+ # The one answer to "is this link continued, and by whom": +id+ the
9
+ # successor's, +via+ how it was found — :next (a saved session continues
10
+ # the link: Links#next_of, raw), :anchor (a schedule's pruned anchor: the
11
+ # schedule's head, Links#anchor_forward) or :in_flight (a continue of the
12
+ # link holds its transition lock and names its successor, not saved yet
13
+ # or just saved: ContinueIntent.in_flight).
14
+ #
15
+ # Who asks what: SessionAccess::Local#continued_as (peer say/pair, a
16
+ # context push: .of, in flight only while the lock is held),
17
+ # SessionContinue's check (.of, no in-flight: it holds the lock itself),
18
+ # follow_guard (.of without the anchor while it holds the lock, as it
19
+ # always asked; .in_flight when it can't), SessionInbox::Head#continuing
20
+ # and Schedules#continuing_reason (.in_flight alone: their walk already
21
+ # crossed the saved links).
22
+ Successor = Data.define(:id, :via) do
23
+ def in_flight? = via == :in_flight
24
+
25
+ # The successor of +id+, or nil: a saved one first (one Session.list,
26
+ # Links), then, with +anchor+, a pruned anchor's head, then, with
27
+ # +in_flight+, a continue in flight. No archive check: a caller that
28
+ # only asks of archived links checks that first (it lists nothing).
29
+ # @return [Successor, nil]
30
+ def self.of(id, state_dir:, in_flight: false, anchor: true)
31
+ return nil unless Session.valid_id?(id)
32
+
33
+ links = Links.new(state_dir: state_dir)
34
+ if (following = links.next_of(id))
35
+ return new(id: following, via: :next)
36
+ end
37
+ if anchor && (head = links.anchor_forward(id))
38
+ return new(id: head, via: :anchor)
39
+ end
40
+
41
+ in_flight ? self.in_flight(id, state_dir: state_dir) : nil
42
+ end
43
+
44
+ # A continue of +id+ in flight, its successor (ContinueIntent.in_flight:
45
+ # the intent written, the lock held), or nil. Lists nothing.
46
+ # @return [Successor, nil]
47
+ def self.in_flight(id, state_dir:)
48
+ successor = ContinueIntent.in_flight(id, state_dir: state_dir)
49
+ successor && new(id: successor, via: :in_flight)
50
+ end
51
+ end
52
+
53
+ # A link continued by another session (or being continued now): one
54
+ # refusal owning the words. Callers add what to do next as a tail
55
+ # (": say it there", "; send again in a moment").
56
+ # +session_id+ nil names "this session" (a peer's line, which carries no
57
+ # id: the installed chi-peer skills look for "this session was continued
58
+ # as <new id>").
59
+ class Continued < StandardError
60
+ attr_reader :session_id, :successor_id
61
+
62
+ # @param in_flight [Boolean] the successor is not saved yet ("is being
63
+ # continued as")
64
+ def initialize(session_id, successor_id, in_flight: false)
65
+ @session_id = session_id
66
+ @successor_id = successor_id
67
+ @in_flight = in_flight
68
+ subject = session_id ? "session #{session_id.to_s[0, 8]}" : "this session"
69
+ super("#{subject} #{in_flight ? "is being" : "was"} continued as #{successor_id}")
70
+ end
71
+
72
+ def in_flight? = @in_flight
73
+
74
+ # The refusal for +successor+ (a Successor).
75
+ def self.for(session_id, successor) = new(session_id, successor.id, in_flight: successor.in_flight?)
76
+ end
77
+ end
78
+ end
@@ -8,6 +8,7 @@ require_relative "session"
8
8
  require_relative "session_setup"
9
9
  require_relative "session_inbox"
10
10
  require_relative "session_chain"
11
+ require_relative "session_chain/successor"
11
12
  require_relative "objectives"
12
13
  require_relative "child_move"
13
14
  require_relative "starting_marker"
@@ -16,6 +17,7 @@ require_relative "note_move"
16
17
  require_relative "peer_continue"
17
18
  require_relative "archive_store"
18
19
  require_relative "continue_intent"
20
+ require_relative "session_transition"
19
21
  require_relative "continued_from"
20
22
  require_relative "recap_store"
21
23
  require_relative "bridge_client"
@@ -34,8 +36,10 @@ module Samagotchi
34
36
  # (another session continues it already, or a schedule's pruned
35
37
  # anchor: +ids+ names the successor, or the schedule's head), :open_children
36
38
  # (open children it can't move to the new link: on an older chi's
37
- # worker or open in a one-turn chi run; +ids+ names them) or :folder_gone (its
38
- # folder isn't there).
39
+ # worker or open in a one-turn chi run; +ids+ names them), :folder_gone (its
40
+ # folder isn't there) or :transition_busy (its transition lock not
41
+ # free within LOCK_WAIT: another continue or change of it runs; its
42
+ # words are SessionTransition::Busy's, naming the holder: +detail+).
39
43
  class Refused < StandardError
40
44
  attr_reader :session_id, :reason, :ids
41
45
 
@@ -51,10 +55,12 @@ module Samagotchi
51
55
  def continue_refused_message(detail)
52
56
  short = @session_id[0, 8]
53
57
  case @reason
54
- when :continued then "#{short} is continued already, by #{@ids.first[0, 8]}; continue that one (or last:#{short})"
58
+ when :continued
59
+ "#{SessionChain::Continued.new(@session_id, @ids.first).message}; continue that one (or last:#{short})"
55
60
  when :open_children
56
61
  "#{short} has delegates still open that can't move to the next link: #{detail}; " \
57
62
  "then continue (or wait for them, stop them or archive them)"
63
+ when :transition_busy then detail || SessionTransition::Busy.new(@session_id).message
58
64
  else "#{short}'s folder #{detail} is gone"
59
65
  end
60
66
  end
@@ -63,14 +69,18 @@ module Samagotchi
63
69
  # How long #run waits for the previous link's worker to write its
64
70
  # recap (IdleRecap's own request timeout).
65
71
  RECAP_WAIT = 30.0
66
- # In the previous link's folder: one continue of a session at a time.
67
- LOCK = ContinueIntent::LOCK
68
72
  # A durable record in the previous link's folder, written before archive
69
73
  # (a send in flight reads it: ContinueIntent.in_flight).
70
74
  CONTINUE_INTENT = ContinueIntent::FILE
71
75
  # How often a last:<id> continue looks again when another continue
72
- # moved the chain's end while it waited for the lock.
76
+ # moved the chain's end while it waited for the lock, or held it past
77
+ # its wait.
73
78
  TRIES = 3
79
+ # How long each try of #run waits for the transition locks of the
80
+ # previous link and the new one, after the recap: past it the continue
81
+ # is refused :transition_busy (a last:<id> one with tries left looks
82
+ # again, and waits again: the other continue's new link may be its end).
83
+ LOCK_WAIT = 10.0
74
84
 
75
85
  # One thing a continue carries from the previous link to the new one.
76
86
  # +carry+ names the method run in spawn_session's before_spawn (once the
@@ -147,9 +157,9 @@ module Samagotchi
147
157
  Checked = Data.define(:plan, :choice)
148
158
 
149
159
  # Repair an interrupted continue before showing sessions or starting
150
- # another continue. An active continue holds LOCK, so its intent is left
151
- # alone; after a crash, an unsaved successor means the previous link is
152
- # unarchived.
160
+ # another continue. An active continue holds its transition lock
161
+ # (SessionTransition), so its intent is left alone; after a crash, an
162
+ # unsaved successor means the previous link is unarchived.
153
163
  def self.repair_interrupted(state_dir:)
154
164
  return unless Dir.exist?(state_dir)
155
165
 
@@ -186,9 +196,12 @@ module Samagotchi
186
196
  # does its movable attached context (ContextMove).
187
197
  # Before that its live worker is asked for a recap and given up to
188
198
  # +recap_wait+ seconds to write it.
189
- # One continue of a session at a time (a lock in its folder): a double
190
- # click finds the first one's link and is refused; a last:<id> one
191
- # follows the chain to its new end instead.
199
+ # One continue of a session at a time (its transition lock,
200
+ # SessionTransition, taken after the recap with the new link's, up to
201
+ # +lock_wait+ seconds, then everything checked again): a double click
202
+ # finds the first one's link and is refused (busy, when the first holds
203
+ # the lock past the wait); a last:<id> one follows the chain to its new
204
+ # end instead.
192
205
  # @param id_or_ref [String] an id, a prefix, or last:<id> (SessionChain.resolve)
193
206
  # @param prompt [String, nil] its first message (nil: it starts idle)
194
207
  # @param preview [String, nil] what the lists show before the first turn;
@@ -202,48 +215,102 @@ module Samagotchi
202
215
  # SessionChain.opener_for the previous link)
203
216
  # @raise [ArgumentError] no such session (Session::AmbiguousId for a prefix of several)
204
217
  # @raise [Refused] continued already, delegates open that can't
205
- # move, or its folder is gone
218
+ # move, its folder is gone, or its transition lock stayed held
219
+ # (:transition_busy)
206
220
  # @raise [ArchiveRefused, OwnedByTUI] as archive_session
207
221
  def self.run(id_or_ref, prompt: nil, preview: nil, model: nil, state_dir: nil, recap_wait: RECAP_WAIT, archive_wait: 5,
208
- client_id: nil)
222
+ client_id: nil, lock_wait: LOCK_WAIT)
209
223
  sd = state_dir || Session.default_state_dir
210
224
  repair_interrupted(state_dir: sd)
225
+ last = id_or_ref.to_s.strip.start_with?(SessionChain::LAST_PREFIX)
211
226
  TRIES.times do |try|
212
227
  id = SessionChain.resolve(id_or_ref, state_dir: sd)
213
- result = with_lock(id, sd) do
214
- follow = id_or_ref.to_s.strip.start_with?(SessionChain::LAST_PREFIX) && try < TRIES - 1
215
- next :moved if follow && SessionChain.next_of(id, state_dir: sd)
228
+ result = continue_once(id, follow: last && try < TRIES - 1, lock_wait: lock_wait, prompt: prompt, preview: preview,
229
+ model: model, state_dir: sd, recap_wait: recap_wait, archive_wait: archive_wait,
230
+ client_id: client_id)
231
+ return result unless result == :moved
232
+ end
233
+ end
234
+
235
+ # One try of #run on the resolved +id+: the refusals known before
236
+ # anything changes and the recap, unlocked (a send during the wait goes
237
+ # in, a delete may take the link); then, under the transition locks of
238
+ # +id+ and the new link's reserved id (one SessionTransition.exclusive,
239
+ # sorted, tried for +lock_wait+ seconds), everything checked again and the
240
+ # transition (#run_locked): each delivery and undo inside it runs on
241
+ # this thread, under the token. :moved when +follow+ (a last:<id> try
242
+ # with tries left) finds a link after +id+, or the locks held past the
243
+ # wait. Whatever way it ends, a reserved folder left with no session
244
+ # file goes (#drop_unsaved).
245
+ private_class_method def self.continue_once(id, follow:, lock_wait:, prompt:, preview:, model:, state_dir:, recap_wait:,
246
+ archive_wait:, client_id:)
247
+ return :moved if follow && SessionChain.next_of(id, state_dir: state_dir)
248
+
249
+ previous = Session.load(id, state_dir: state_dir)
250
+ # The link may be continued between the next_of look above and this check: move on, not refuse.
251
+ begin
252
+ checked = check!(previous, state_dir, model: model)
253
+ rescue Refused => e
254
+ raise unless follow && e.reason == :continued
255
+
256
+ return :moved
257
+ end
258
+ # archive_session's refusals that can be known now, before the wait.
259
+ SessionManager.archivable!(id, state_dir, except: checked.plan.move)
260
+ recap_before_archive(id, state_dir, wait: recap_wait)
261
+ successor_id = SecureRandom.uuid
262
+ begin
263
+ with_lock([id, successor_id], state_dir, deadline: lock_wait) do
264
+ next :moved if follow && SessionChain.next_of(id, state_dir: state_dir)
216
265
 
217
- run_locked(id, prompt: prompt, preview: preview, model: model, state_dir: sd, recap_wait: recap_wait,
218
- archive_wait: archive_wait, client_id: client_id)
266
+ run_locked(id, successor_id, prompt: prompt, preview: preview, model: model, state_dir: state_dir,
267
+ archive_wait: archive_wait, client_id: client_id)
219
268
  end
220
- return result unless result == :moved
269
+ rescue SessionTransition::Busy => e
270
+ return :moved if follow
271
+
272
+ raise Refused.new(id, :transition_busy, detail: e.message)
273
+ ensure
274
+ drop_unsaved(id, successor_id, state_dir)
221
275
  end
222
276
  end
223
277
 
224
- private_class_method def self.with_lock(id, state_dir, &)
225
- dir = Session.session_dir(id, state_dir: state_dir)
226
- FileUtils.mkdir_p(dir)
227
- File.open(File.join(dir, LOCK), File::RDWR | File::CREAT, 0o600) do |lock|
228
- lock.flock(File::LOCK_EX)
229
- yield
278
+ # The block under the transition locks of +ids+ (sorted), tried until
279
+ # +deadline+ seconds from now.
280
+ # @raise [SessionTransition::Busy]
281
+ private_class_method def self.with_lock(ids, state_dir, deadline:, &)
282
+ SessionTransition.exclusive(ids, kind: :continue, state_dir: state_dir, deadline: deadline, &)
283
+ end
284
+
285
+ # A continue's folders that #with_lock made or kept and no session file
286
+ # is in: the new link's reserved one, never saved (a refusal or failure
287
+ # before its save; a crash's, from #repair_intent), with any note a
288
+ # writer left there given back to +id+ first (as #give_back_strays);
289
+ # +id+'s own, when it was deleted while the continue waited, holding only
290
+ # the lock (SessionTransition.forget). A saved session is left alone.
291
+ private_class_method def self.drop_unsaved(id, successor_id, state_dir)
292
+ dir = Session.session_dir(successor_id, state_dir: state_dir)
293
+ if Dir.exist?(dir) && !Session.exist?(successor_id, state_dir: state_dir)
294
+ NoteMove.give_back(from: successor_id, to: id, moved: [], state_dir: state_dir) if Session.exist?(id, state_dir: state_dir)
295
+ FileUtils.rm_rf(dir)
230
296
  end
297
+ SessionTransition.forget(id, state_dir: state_dir)
298
+ rescue StandardError => e
299
+ Log.warn(:worker, "continue_cleanup_failed", sid: id, error: e.class.name, msg: e.message)
231
300
  end
232
301
 
233
- private_class_method def self.run_locked(id, prompt:, preview:, model:, state_dir:, recap_wait:, archive_wait:, client_id:)
302
+ # The transition: +previous+ checked again (it may have changed, been
303
+ # continued or deleted during the recap; a turn sent to it during the
304
+ # wait may have delegated, they move too, or a delegate finished),
305
+ # the intent, the archive, the new link and its carry, or the undo.
306
+ private_class_method def self.run_locked(id, successor_id, prompt:, preview:, model:, state_dir:, archive_wait:,
307
+ client_id:)
234
308
  previous = Session.load(id, state_dir: state_dir)
235
309
  checked = check!(previous, state_dir, model: model)
236
310
  plan = checked.plan
237
- # archive_session's refusals that can be known now, before the wait.
238
- SessionManager.archivable!(id, state_dir, except: plan.move)
239
- recap_before_archive(id, state_dir, wait: recap_wait)
240
- # Again: a turn sent to it during the wait may have delegated (they
241
- # move too), or a delegate finished.
242
- plan = move_plan!(id, state_dir)
243
311
  already = [id, *SessionManager.descendant_ids(id, state_dir, except: plan.move)].select do |sid|
244
312
  ArchiveStore.archived?(Session.session_dir(sid, state_dir: state_dir))
245
313
  end
246
- successor_id = SecureRandom.uuid
247
314
  intent_path = continue_intent_path(id, state_dir)
248
315
  ContinueIntent.write(intent_path, successor_id: successor_id, previously_archived: already)
249
316
  archive = SessionManager.archive_session(id, state_dir: state_dir, wait: archive_wait, except: plan.move)
@@ -276,9 +343,9 @@ module Samagotchi
276
343
  end
277
344
 
278
345
  private_class_method def self.repair_intent(session, state_dir, path, sessions)
279
- lock_path = File.join(Session.session_dir(session.id, state_dir: state_dir), LOCK)
280
- File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
281
- next unless lock.flock(File::LOCK_EX | File::LOCK_NB)
346
+ # Not taken (a continue runs, on this thread too): its intent is left.
347
+ SessionTransition.try_exclusive(session.id, kind: :repair, state_dir: state_dir) do |token|
348
+ next unless token
282
349
  next unless File.file?(path)
283
350
 
284
351
  intent = ContinueIntent.read(path)
@@ -287,6 +354,9 @@ module Samagotchi
287
354
  unless successor.is_a?(Hash) && successor["continues"] == session.id
288
355
  archived = intent.archived_ids || (archived_descendants(session.id, sessions, state_dir) - intent.previously_archived)
289
356
  undo_failed_continue(session.id, state_dir, moved: [], archived: archived)
357
+ # The folder the crashed continue reserved for it (its lock), when
358
+ # it was never saved.
359
+ drop_unsaved(session.id, intent.successor_id, state_dir) if intent.successor_id
290
360
  end
291
361
  FileUtils.rm_f(path)
292
362
  end
@@ -540,11 +610,11 @@ module Samagotchi
540
610
  # @raise [Refused, ModelProfile::MissingModel]
541
611
  private_class_method def self.check!(previous, state_dir, model: nil)
542
612
  # A schedule's pruned anchor counts as continued, by the schedule's
543
- # head (Links#anchor_forward): continuing it would start a second
544
- # line beside the chain.
545
- links = SessionChain::Links.new(state_dir: state_dir)
546
- if (following = links.next_of(previous.id) || links.anchor_forward(previous.id))
547
- raise Refused.new(previous.id, :continued, ids: [following])
613
+ # head (Successor via :anchor): continuing it would start a second
614
+ # line beside the chain. No in-flight look: under the lock (#run_locked)
615
+ # this continue holds it, and a stale intent names nobody.
616
+ if (following = SessionChain::Successor.of(previous.id, state_dir: state_dir))
617
+ raise Refused.new(previous.id, :continued, ids: [following.id])
548
618
  end
549
619
 
550
620
  plan = move_plan!(previous.id, state_dir)
@@ -48,7 +48,7 @@ module Samagotchi
48
48
  # The one delivery path (session_inbox_delivery.rb), loaded on first
49
49
  # use: the bundle test kit's load budget stays as it was.
50
50
  delivery = File.expand_path("session_inbox_delivery", __dir__)
51
- %i[Dispatch Delivered Head Resolved WakePolicy].each { |name| autoload name, delivery }
51
+ %i[Dispatch Delivered Head Hold Resolved WakePolicy].each { |name| autoload name, delivery }
52
52
 
53
53
  # A delivery of +kind+ to session +target+ (Dispatch.deliver: resolve,
54
54
  # refuse, the block's write, one presence read, the WakePolicy's wake).
@@ -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
 
@@ -234,7 +267,7 @@ module Samagotchi
234
267
  # send to an archived link with a successor is refused, and chi send
235
268
  # resolves again).
236
269
  def continuing(resolved, state_dir)
237
- successor = ContinueIntent.in_flight(resolved.id, state_dir: state_dir)
270
+ successor = SessionChain::Successor.in_flight(resolved.id, state_dir: state_dir)&.id
238
271
  return nil if successor.nil?
239
272
 
240
273
  via = Session.exist?(successor, state_dir: state_dir) ? :head : :continuing
@@ -242,6 +275,42 @@ module Samagotchi
242
275
  end
243
276
  end
244
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
+
245
314
  # SessionInbox.deliver and SessionInbox.wake.
246
315
  module Dispatch
247
316
  # What a start each kind makes is logged as (SessionManager.start_for_inbox).
@@ -250,10 +319,11 @@ module Samagotchi
250
319
  module_function
251
320
 
252
321
  # Deliver one +kind+ of thing to session +target+, in this order:
253
- # resolve the link (Head.resolve), refuse (WakePolicy#refusal: before
254
- # any write), write (the block: the kind's own writer, given the id
255
- # it writes under), read the presence once, then decide and apply
256
- # (#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).
257
327
  # @param wake [Boolean] the delivery may ask for a worker; the block's
258
328
  # value says whether it does (truthy: asks)
259
329
  # @param pin [Boolean] write under +target+ itself, whatever the kind's
@@ -274,22 +344,38 @@ module Samagotchi
274
344
  resolved = Resolved.new(id: target, asked: target, via: :pinned) if pin
275
345
  resolved ||= Head.resolve(kind, target, state_dir: sd)
276
346
  at = policy.resolves == :reader ? resolved.asked : resolved.id
277
- if (why = refusal(policy, at, sd, owner))
278
- 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,
279
350
  wake: why)
280
- end
351
+ end
281
352
 
282
- asks = yield(at)
283
- 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
284
356
  end
285
357
 
286
358
  # The wake half of #deliver alone, for a delivery already on disk (a
287
- # 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).
288
363
  # @return [Delivered]
289
- 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)
290
365
  sd = state_dir || Session.default_state_dir
291
- apply(WakePolicy.for(kind), Head.resolve(kind, target, state_dir: sd), sd, wake: true, owner: owner,
292
- 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)
293
379
  end
294
380
 
295
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