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
@@ -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
@@ -24,9 +25,15 @@ module Samagotchi
24
25
  STATES = %i[absent tui_owned deleting stopping skew leaving booting_stuck booting live
25
26
  stopped_starting stopped archived_starting starting archived idle].freeze
26
27
 
28
+ # The states whose session is shown "stopped" (the hub shows the stopped
29
+ # status only there; the file's own status is shown everywhere else).
30
+ STOPPED_STATES = %i[stopping stopped_starting stopped].freeze
31
+
27
32
  autoload :Reading, File.expand_path("session_lifecycle/reading", __dir__)
28
33
  autoload :CANONICAL, File.expand_path("session_lifecycle/canonical", __dir__)
29
34
  autoload :ALLOWED, File.expand_path("session_lifecycle/allowed", __dir__)
35
+ autoload :TRANSITIONING, File.expand_path("session_lifecycle/allowed", __dir__)
36
+ autoload :TAKES_LOCK, File.expand_path("session_lifecycle/allowed", __dir__)
30
37
 
31
38
  # The cell words that are no refusal, per operation: a resume that finds
32
39
  # a worker there or one being started waits for it; a restart's
@@ -35,8 +42,15 @@ module Samagotchi
35
42
 
36
43
  module_function
37
44
 
45
+ # @param transitioning [Boolean] a transition holds the session's lock
46
+ # (Reading#transitioning): an op TRANSITIONING names answers its cell
47
+ # there, whatever the state
38
48
  # @return [Symbol] the cell of +op+ in +state+ (ALLOWED)
39
- def allowed(op, state) = ALLOWED.fetch(op).fetch(state)
49
+ def allowed(op, state, transitioning: false)
50
+ return TRANSITIONING.fetch(op) if transitioning && TRANSITIONING.key?(op)
51
+
52
+ ALLOWED.fetch(op).fetch(state)
53
+ end
40
54
 
41
55
  # A cell as :go, :wait or :refused: :go and :wait are themselves, an
42
56
  # operation's own words (VERDICT_WORDS) theirs, every other a refusal.
@@ -54,7 +68,8 @@ module Samagotchi
54
68
  def read(session_id, state_dir: nil, owner: :read)
55
69
  sd = state_dir || Session.default_state_dir
56
70
  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))
71
+ Reading.derive(presence, continuing: ContinueIntent.in_flight(session_id, state_dir: sd),
72
+ transitioning: SessionTransition.held?(session_id, state_dir: sd))
58
73
  end
59
74
  end
60
75
  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)
@@ -263,12 +301,6 @@ module Samagotchi
263
301
  return DeliverResult.new(status: :refused, code: 409, ack: ReviseAnchor::PARTICIPANT_UNAVAILABLE)
264
302
  end
265
303
 
266
- # compat shim review_client_id: a worker from before participant:
267
- # reads a participant's turn by review:<id> (dequeue is left out:
268
- # its client id is only echoed back).
269
- if ClientId.participant?(client_id) && !worker_has?(client, Delivery::PARTICIPANT_ID_FEATURE)
270
- client_id = ClientId.legacy_participant(client_id)
271
- end
272
304
  # compat shim agent_client_id: a worker from before agent: reads
273
305
  # an agent's line as chi send's (today's owner row).
274
306
  client_id = ClientId::CLI_SEND if ClientId.agent?(client_id) && !agent_reader
@@ -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
 
@@ -88,11 +89,20 @@ module Samagotchi
88
89
  # holds the lock: STOP_WAIT plus the recap's own wait (SessionContinue::RECAP_WAIT).
89
90
  FALLBACK_STOP_WAIT = 40
90
91
 
92
+ # How long a stop waits for its turn cancel: the Bridge's reply (its
93
+ # read timeout) and then the worker's save, each.
91
94
  STOP_CANCEL_WAIT = 3.0
92
95
  # How long a stop from the CLI (chi sessions stop, delete, a continue's
93
96
  # orphan) waits for the worker to let go of the session, here or
94
97
  # through chi web (POST …/stop's wait, capped at it).
95
98
  STOP_WAIT = 10
99
+ # How long a stop waits for its session's transition lock (a short
100
+ # hold: a send's shared one, a holder that names nothing) before it is
101
+ # refused (SessionTransition::Busy). A continue naming its new link, a
102
+ # delete or an archive is refused at once (refuse_transitions). An
103
+ # owner-side stop (a worker stopping its delegates) tries once (0): it
104
+ # holds its own owner.lock.
105
+ STOP_LOCK_WAIT = 10
96
106
  # The cancel reason of a turn a session stop cancels (Bridge::CANCEL_REASONS):
97
107
  # not the user's Stop, which only ends the turn ("user").
98
108
  STOP_CANCEL_REASON = "session_stopped"
@@ -212,32 +222,68 @@ module Samagotchi
212
222
  # With +wait+ (seconds), also wait for the owner to let go of the session,
213
223
  # so a resume right after spawns a fresh worker instead of finding the
214
224
  # dying one.
215
- # A turn still running is canceled first (STOP_CANCEL_WAIT), as the
216
- # web's Cancel does, with reason STOP_CANCEL_REASON: its worker saves it. The TERM stops (and saves)
225
+ # The cancel, the mark and the TERM run under the session's transition
226
+ # lock, held exclusively (kind :stop, +lock_wait+ seconds to take it,
227
+ # a continue naming its new link, a delete or an archive refused at
228
+ # once: SessionTransition.exclusive's refuse_transitions; one this
229
+ # thread holds, a continue's or a delete's, passes through), never the
230
+ # owner wait: a send, a continue or a delete doesn't interleave with
231
+ # them, a refused stop leaves the running turn alone, and a ring
232
+ # wake's start (#wake_for_report) comes before the stop or after it,
233
+ # whole. A turn still running is canceled first, as the web's Cancel
234
+ # does, with reason STOP_CANCEL_REASON: its worker saves it. That is
235
+ # the one Bridge wait under the hold, bounded (STOP_CANCEL_WAIT for
236
+ # the reply, then as long for the save). The TERM stops (and saves)
217
237
  # what still runs (WorkerSignals), with a short grace after the marker.
238
+ # @param lock_wait [Numeric] 0 from a worker (it holds an owner.lock:
239
+ # one try, never a wait)
218
240
  # @return [Boolean, nil] with +wait+: whether the owner was gone in time
219
241
  # @raise [OwnedByTUI] when the interactive TUI owns the session
220
- def stop_session(session_id, state_dir: nil, wait: nil)
242
+ # @raise [SessionTransition::Busy] another change held the lock
243
+ # past +lock_wait+, or a transition held it (its words name the
244
+ # holder; a stop's: Busy#taker :stop); nothing was canceled or marked
245
+ def stop_session(session_id, state_dir: nil, wait: nil, lock_wait: STOP_LOCK_WAIT)
221
246
  sd = state_dir || Session.default_state_dir
222
- owner = refuse_tui!(session_id, state_dir: sd)
247
+ refuse_tui!(session_id, state_dir: sd)
223
248
 
224
- 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
249
+ under_stop_lock(session_id, sd, lock_wait) do
250
+ cancel_running_turn(session_id, state_dir: sd)
251
+ # The owner read again under the lock: a worker a ring wake started
252
+ # while the stop waited for it is the one to TERM.
253
+ owner = refuse_tui!(session_id, state_dir: sd)
254
+ # Mark first: a worker that has not taken the lock yet sees it and exits.
255
+ Session.mark_stopped(session_id, state_dir: sd)
256
+ # A stop drops the reminders: a restart's hand-off no successor took
257
+ # yet must not bring them back on the next resume.
258
+ ReminderCarry.remove(Session.session_dir(session_id, state_dir: sd))
259
+ # A deleter holding the lock (chi web, the CLI) is no worker to stop.
260
+ pid = owner&.deleting? ? 0 : owner&.pid.to_i
261
+ begin
262
+ Process.kill("TERM", pid) if pid && pid > 0
263
+ rescue Errno::ESRCH
264
+ nil # already exited
265
+ end
266
+ continue_stopped(pid)
236
267
  end
237
- continue_stopped(pid)
238
268
  wait_for_owner_release(session_id, timeout: wait, state_dir: sd) if wait
239
269
  end
240
270
 
271
+ # The block under +session_id+'s transition lock, kind :stop, for a
272
+ # saved session; a gone one's folder is never made again (the block
273
+ # alone: Session.mark_stopped's NotFound follows), and a lock file
274
+ # left for a session deleted meanwhile is taken back.
275
+ # @raise [SessionTransition::Busy]
276
+ private def under_stop_lock(session_id, state_dir, lock_wait, &)
277
+ return yield unless Session.exist?(session_id, state_dir: state_dir)
278
+
279
+ begin
280
+ SessionTransition.exclusive([session_id], kind: :stop, state_dir: state_dir, deadline: lock_wait,
281
+ refuse_transitions: true, &)
282
+ ensure
283
+ SessionTransition.forget(session_id, state_dir: state_dir)
284
+ end
285
+ end
286
+
241
287
  # A stopped worker (SIGSTOP, Ctrl-Z) runs its TERM handler only once
242
288
  # continued: CONT it after the TERM (as ProcessGroup.stop does), so it
243
289
  # leaves now rather than outliving the stop's wait. Best effort: one the
@@ -250,11 +296,14 @@ module Samagotchi
250
296
 
251
297
  # Cancel the session's running turn over its Bridge and wait (up to
252
298
  # STOP_CANCEL_WAIT) for the worker to save it. Best effort: without a
253
- # live Bridge, or when it doesn't answer, the stop goes on as before.
299
+ # live Bridge, or when it doesn't answer within STOP_CANCEL_WAIT (its
300
+ # read timeout: the stop holds the transition lock), the stop goes on
301
+ # as before.
254
302
  private def cancel_running_turn(session_id, state_dir:)
255
303
  return unless Session.load(session_id, state_dir: state_dir).status == Session::STATUS_RUNNING
256
304
 
257
- client = WorkerLink.client(session_id, session_dir: Session.session_dir(session_id, state_dir: state_dir))
305
+ client = WorkerLink.client(session_id, session_dir: Session.session_dir(session_id, state_dir: state_dir),
306
+ read_timeout: STOP_CANCEL_WAIT)
258
307
  return unless client && client.cancel(reason: STOP_CANCEL_REASON).status == 202
259
308
 
260
309
  BridgeClient.poll(STOP_CANCEL_WAIT) do
@@ -39,7 +39,7 @@ module Samagotchi
39
39
  # @param include_archived [Boolean] archived sessions too
40
40
  # @return [Array<SessionRow>] see SessionRow for the fields
41
41
  def session_rows(live: false, cwd: nil, limit: nil, include_tests: true, exclude: nil, state_dir: nil,
42
- project_root: nil, include_archived: false, sort: nil, order: nil)
42
+ project_root: nil, include_archived: false, sort: nil, order: nil, exclude_delegates: false)
43
43
  sd = state_dir || Session.default_state_dir
44
44
  SessionContinue.repair_interrupted(state_dir: sd)
45
45
  root = cwd && folder_path(cwd)
@@ -51,6 +51,7 @@ module Samagotchi
51
51
  rows = Session.list(state_dir: sd, sort: sort || "updated_at", order: order || "desc", project_root: project_root,
52
52
  include_archived: include_archived).lazy
53
53
  .reject { |s| (!include_tests && s.test_run) || s.id == exclude }
54
+ .reject { |s| exclude_delegates && (s.delegate? || s.scratch) }
54
55
  .select { |s| root.nil? || in_folder?(s.working_directory, root) }
55
56
  .filter_map do |s|
56
57
  dir = Session.session_dir(s.id, state_dir: sd)
@@ -12,7 +12,10 @@ module Samagotchi
12
12
  # read again under the owner lock, no longer holds), :scheduled (an
13
13
  # enabled schedule's target, anchor or head: +schedule_id+),
14
14
  # :continuing (a continue of +session_id+ is in flight: this link, or
15
- # the previous one a delete would bring back), :delegate_unmovable (a
15
+ # the previous one a delete would bring back), :transition_held (another
16
+ # change holds its transition lock: a delete, a send's shared hold; the
17
+ # words SessionTransition::Busy's, naming the holder: .held),
18
+ # :delegate_unmovable (a
16
19
  # delegate the deleted link's continue moved can't go back: +ids+,
17
20
  # +detail+ says why), :chain_scheduled (a schedule is on the chain a
18
21
  # chain delete would take: +schedule_id+), :protection_unreadable (a
@@ -41,6 +44,14 @@ module Samagotchi
41
44
 
42
45
  def worker_stopped = !@stopped_worker.nil?
43
46
 
47
+ # A delete's refusal for a transition lock not taken in time
48
+ # (SessionTransition::Busy, which names the holder): :continuing when
49
+ # a continue holds it, else :transition_held; Busy's words either way,
50
+ # with "try again" (Busy#retry_message: a stop's words name no delete).
51
+ def self.held(busy)
52
+ new(busy.session_id, busy.kind == :continue ? :continuing : :transition_held, message: busy.retry_message)
53
+ end
54
+
44
55
  # This refusal, saying the op stopped +worker_id+'s worker (this
45
56
  # session's by default) before the check under the lock refused.
46
57
  def with_worker_stopped(worker_id = @session_id)
@@ -58,6 +69,7 @@ module Samagotchi
58
69
  when :changed then "session #{@session_id} changed since it was checked"
59
70
  when :scheduled then "this session is the target of an enabled schedule#{cancel}"
60
71
  when :continuing then "a continue of #{short} is under way; try again in a moment"
72
+ when :transition_held then "session #{short} is busy with another change; try again in a moment"
61
73
  when :delegate_unmovable
62
74
  "#{@ids.map { |id| id[0, 8] }.join(", ")}, moved here by the continue, can't go back to the previous link" \
63
75
  "#{": #{detail}" if detail}"
@@ -80,7 +92,7 @@ module Samagotchi
80
92
  attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker, :sessions, :stopped_workers
81
93
 
82
94
  def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false, sessions: nil,
83
- stopped_workers: [])
95
+ stopped_workers: [], message: nil)
84
96
  @session_id = session_id
85
97
  @reason = reason
86
98
  @busy_id = busy_id
@@ -88,7 +100,17 @@ module Samagotchi
88
100
  @sessions = sessions
89
101
  @stopped_workers = stopped_workers
90
102
  @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
91
- super(archive_refused_message)
103
+ super(message || archive_refused_message)
104
+ end
105
+
106
+ # An archive's refusal for a transition lock not taken in time (its
107
+ # own, or a worker's stop's: SessionTransition::Busy, which names the
108
+ # holder and the session held): :transition_held, Busy's words with
109
+ # "try again" (Busy#retry_message); +stopped_workers+ the workers it
110
+ # stopped before.
111
+ def self.held(busy, stopped_workers: [])
112
+ new(busy.session_id, :transition_held, busy_id: busy.session_id, stopped_workers: stopped_workers,
113
+ message: busy.retry_message)
92
114
  end
93
115
 
94
116
  def worker_stopped = !@stopped_worker.nil?
@@ -113,6 +135,11 @@ module Samagotchi
113
135
  end
114
136
  end
115
137
 
138
+ # How long an archive waits for its tree's transition locks (another
139
+ # change holding one: a continue, a delete, a send's shared hold) before
140
+ # it is refused ArchiveRefused :transition_held.
141
+ ARCHIVE_LOCK_WAIT = 10
142
+
116
143
  # What one archive did: id: the session it was asked for; archived: the
117
144
  # ids (it and its delegates) now hidden for good; stopped: the live
118
145
  # workers stopped first; discarded: empty sessions its stopping worker
@@ -158,16 +185,35 @@ module Samagotchi
158
185
  ArchiveRefused.new(id, :tasks_running, tasks: listing, sessions: tree.size)
159
186
  end
160
187
  stopped = tree.select { |sid| owners[sid] }
161
- # With +wait+, stop_session waits for the owner to let go.
162
- stopped.each { |sid| stop_session(sid, state_dir: sd, wait: wait) }
163
- stop_archived_tasks!(id, tree, stopped, sd, running_tasks) if running_tasks.stop?
164
- archived, discarded = tree.partition { |sid| ArchiveStore.archive(sid, state_dir: sd) }
188
+ done = []
189
+ # With +wait+, stop_session waits for the owner to let go (its own
190
+ # transition lock taken for its mark and TERM only).
191
+ stopped.each do |sid|
192
+ stop_session(sid, state_dir: sd, wait: wait)
193
+ done << sid
194
+ end
195
+ archived, discarded = under_archive_locks(tree, sd) do
196
+ stop_archived_tasks!(id, tree, stopped, sd, running_tasks) if running_tasks.stop?
197
+ tree.partition { |sid| ArchiveStore.archive(sid, state_dir: sd) }
198
+ end
165
199
  # A restart's reminders hand-off no successor took (the stop above
166
200
  # removes a live one's): archived sessions keep no reminders.
167
201
  archived.each { |sid| ReminderCarry.remove(Session.session_dir(sid, state_dir: sd)) }
168
202
  # D8: an archive ends the review (unarchiving doesn't restore it).
169
203
  Participants.end_sessions(archived, by: "archive", state_dir: sd)
170
204
  ArchiveResult.new(id: id, archived: archived, stopped: stopped, discarded: discarded, **running_tasks.result_fields)
205
+ rescue SessionTransition::Busy => e
206
+ raise ArchiveRefused.held(e, stopped_workers: done || [])
207
+ end
208
+
209
+ # The block under the exclusive transition locks (kind :archive) of
210
+ # +tree+'s sessions still on disk (one its stopping worker discarded
211
+ # gets no folder again), within ARCHIVE_LOCK_WAIT; ids this thread
212
+ # holds (a continue's previous link) pass through.
213
+ # @raise [SessionTransition::Busy]
214
+ private def under_archive_locks(tree, state_dir, &)
215
+ ids = tree.select { |sid| Session.exist?(sid, state_dir: state_dir) }
216
+ SessionTransition.exclusive(ids, kind: :archive, state_dir: state_dir, deadline: ARCHIVE_LOCK_WAIT, &)
171
217
  end
172
218
 
173
219
  # An archive's stop, after the workers let go: a stop with +only+
@@ -261,8 +307,10 @@ module Samagotchi
261
307
  # the running ones stay; without them (the automatic deletes) they
262
308
  # are left. The result then also has unarchived:, moved_back:,
263
309
  # deleted: and left_running: (ids)
264
- # @param refuse_continuing [Boolean] a user's delete refuses
265
- # (:continuing) while a continue of the session is in flight
310
+ # @param refuse_continuing [Boolean] a user's delete (either keyword
311
+ # takes SessionChain::Delete.link, which holds the transition locks
312
+ # exclusively and so refuses, :continuing or :transition_held, while a
313
+ # continue or another change of the session holds them)
266
314
  # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
267
315
  # head, and with the keywords :continuing and :delegate_unmovable
268
316
  # @param still [#call, nil] the caller's own check, read again under
@@ -290,8 +338,7 @@ module Samagotchi
290
338
  if revive_previous || refuse_continuing
291
339
  require_relative "../session_chain/delete"
292
340
  return SessionChain::Delete.link(id, state_dir: sd, stop: stop, wait: wait, revive_previous: revive_previous,
293
- refuse_continuing: refuse_continuing, expect: expect,
294
- running_tasks: running_tasks)
341
+ expect: expect, running_tasks: running_tasks)
295
342
  end
296
343
 
297
344
  delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled,
@@ -506,11 +553,18 @@ module Samagotchi
506
553
 
507
554
  # Stop the worker that owns +id+ or is being started for it (the stop
508
555
  # marker: one that takes the lock leaves at once), and wait for both to
509
- # be gone.
556
+ # be gone. A stop that meets another change's transition hold (a plain
557
+ # delete takes none itself; SessionChain::Delete's pass through) is
558
+ # the delete's refusal (DeleteRefused.held), not a raw Busy.
510
559
  # @return [Boolean] whether no owner and no start was left within +wait+
560
+ # @raise [DeleteRefused] :continuing / :transition_held
511
561
  private def stop_held(id, state_dir:, wait:)
512
562
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + wait.to_f
513
- return false unless stop_session(id, state_dir: state_dir, wait: wait)
563
+ begin
564
+ return false unless stop_session(id, state_dir: state_dir, wait: wait)
565
+ rescue SessionTransition::Busy => e
566
+ raise DeleteRefused.held(e)
567
+ end
514
568
 
515
569
  while StartingMarker.fresh?(id, state_dir: state_dir) || session_owner(id, state_dir: state_dir)
516
570
  return false if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
@@ -69,9 +69,8 @@ module Samagotchi
69
69
  setup: SessionSetup.new, continues: nil, note: nil, note_source: "chi", before_spawn: nil,
70
70
  review: nil, verify_fresh: nil, scratch: false, session_id: nil, driver: :creator)
71
71
  sd = state_dir || Session.default_state_dir
72
- if session_id && (!Session.valid_id?(session_id) || Session.exist?(session_id, state_dir: sd))
73
- raise ArgumentError, "invalid or existing session id #{session_id.inspect}"
74
- end
72
+ raise ArgumentError, "invalid session id #{session_id.inspect}" if session_id && !Session.valid_id?(session_id)
73
+ raise IdTaken, "existing session id #{session_id.inspect}" if session_id && Session.exist?(session_id, state_dir: sd)
75
74
 
76
75
  # The resolved ref is stored (a resumed session keeps its model when an
77
76
  # alias is retargeted), with the name as typed beside it. A wrong host
@@ -197,15 +196,23 @@ module Samagotchi
197
196
  # gone, stopped (the stop marker; the file's status never decides),
198
197
  # archived, a scratch session, a one-turn run's or owned, or a
199
198
  # continue's new link still taking its delegates (its own spawn
200
- # comes): the ring waits on disk for whoever runs it next. A stop
201
- # landing between the check and the resume is a small window, left as
202
- # is. An archived parent with a later link wakes that link (one hop:
203
- # ChildReports reads its predecessor's rings, no further).
199
+ # comes): the ring waits on disk for whoever runs it next. The check
200
+ # and the resume run under the session's transition lock, held shared
201
+ # (SessionInbox.wake's hold: the resolved link's), so a stop (which
202
+ # takes it exclusively for its mark and TERM) lands before the check
203
+ # or after the start, never between them; a transition holding it now
204
+ # leaves the ring on disk (:busy, or :continued naming no one here:
205
+ # the continue carries the rings). Inside a continue's own hold (its
206
+ # undo: wake_for_rings) the hold passes through. An archived parent
207
+ # with a later link wakes that link (one hop: ChildReports reads its
208
+ # predecessor's rings, no further).
204
209
  # @return [Symbol] :woken, or why not (:gone, :deleting: a deleter
205
- # holds its lock, :stopped, :archived, :scratch, :owned, :starting)
210
+ # holds its lock, :stopped, :archived, :scratch, :owned, :starting,
211
+ # :busy / :continued: a transition holds it)
206
212
  def wake_for_report(session_id, state_dir: nil)
207
213
  sd = state_dir || Session.default_state_dir
208
- outcome = SessionInbox.wake(:ring, session_id, state_dir: sd, owner: ->(id) { session_owner(id, state_dir: sd) }).wake
214
+ outcome = SessionInbox.wake(:ring, session_id, state_dir: sd, owner: ->(id) { session_owner(id, state_dir: sd) },
215
+ hold: :shared).wake
209
216
  outcome == :live ? :owned : outcome
210
217
  end
211
218
 
@@ -122,6 +122,10 @@ module Samagotchi
122
122
  end
123
123
  end
124
124
 
125
+ # spawn_session's session_id: is a session already (a retried create
126
+ # whose id its request_id names: Web::AskCreate goes on with that one).
127
+ class IdTaken < ArgumentError; end
128
+
125
129
  # A `chi scratch` session: its terminal's alone (Session::SCRATCH_REFUSED).
126
130
  # An OwnedByTUI, so every caller that refuses a terminal's session
127
131
  # (chi send, chi web's 409 owned_by_tui) refuses it the same way.