samagotchi 0.177.0 → 0.178.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 (88) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +31 -6
  5. data/docs/guardrails.md +1 -1
  6. data/docs/internals/background-tasks.md +23 -2
  7. data/docs/internals/bridge.md +17 -6
  8. data/docs/internals/bundles.md +4 -3
  9. data/docs/internals/participants.md +8 -5
  10. data/docs/internals/remote-sessions.md +6 -1
  11. data/docs/internals/session-lifecycle.md +176 -0
  12. data/docs/internals/web-frontend.md +14 -6
  13. data/docs/internals/working-set.md +33 -6
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +3 -2
  16. data/docs/scheduling.md +8 -1
  17. data/docs/sessions.md +15 -9
  18. data/docs/testing.md +4 -2
  19. data/lib/samagotchi/bridge/card_store.rb +2 -19
  20. data/lib/samagotchi/bridge.rb +38 -6
  21. data/lib/samagotchi/bundle_command/check.rb +1 -1
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/compat.rb +0 -7
  24. data/lib/samagotchi/engine/events.rb +43 -0
  25. data/lib/samagotchi/engine/session.rb +7 -0
  26. data/lib/samagotchi/engine.rb +9 -3
  27. data/lib/samagotchi/event_fanout.rb +56 -0
  28. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  29. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  30. data/lib/samagotchi/note_delivery.rb +9 -4
  31. data/lib/samagotchi/plugin/sessions.rb +2 -1
  32. data/lib/samagotchi/revise_anchor.rb +2 -0
  33. data/lib/samagotchi/schedules.rb +12 -5
  34. data/lib/samagotchi/session_access/contract.rb +4 -0
  35. data/lib/samagotchi/session_access/local.rb +16 -4
  36. data/lib/samagotchi/session_access/remote.rb +42 -9
  37. data/lib/samagotchi/session_archive_command.rb +38 -10
  38. data/lib/samagotchi/session_chain/delete.rb +98 -25
  39. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  40. data/lib/samagotchi/session_delete_command.rb +33 -10
  41. data/lib/samagotchi/session_inbox.rb +29 -0
  42. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  43. data/lib/samagotchi/session_lifecycle/allowed.rb +69 -0
  44. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  45. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  46. data/lib/samagotchi/session_lifecycle.rb +59 -0
  47. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  48. data/lib/samagotchi/session_manager/lifecycle.rb +33 -39
  49. data/lib/samagotchi/session_manager/removal.rb +117 -25
  50. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  51. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  52. data/lib/samagotchi/sessions_command.rb +1 -1
  53. data/lib/samagotchi/system_prompt.rb +22 -2
  54. data/lib/samagotchi/task_files.rb +37 -4
  55. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  56. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  57. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  58. data/lib/samagotchi/tool_names.rb +1 -1
  59. data/lib/samagotchi/tools/memory.rb +29 -0
  60. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  61. data/lib/samagotchi/turn_anchors.rb +5 -0
  62. data/lib/samagotchi/verify_anchor.rb +2 -0
  63. data/lib/samagotchi/version.rb +1 -1
  64. data/lib/samagotchi/web/app.rb +5 -1
  65. data/lib/samagotchi/web/participant_show.rb +3 -4
  66. data/lib/samagotchi/web/participant_view.rb +4 -6
  67. data/lib/samagotchi/web/public/data.js +19 -3
  68. data/lib/samagotchi/web/public/delete_sheet.js +67 -11
  69. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  70. data/lib/samagotchi/web/public/session_actions.js +57 -8
  71. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  72. data/lib/samagotchi/web/public/working_set.js +3 -28
  73. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  74. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  75. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  76. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  77. data/lib/samagotchi/web/public/ws_sections.js +1 -0
  78. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  79. data/lib/samagotchi/web/session_control.rb +66 -16
  80. data/lib/samagotchi/web/session_summary.rb +7 -0
  81. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  82. data/lib/samagotchi/worker_boot.rb +9 -6
  83. data/lib/samagotchi/worker_link.rb +9 -1
  84. data/lib/samagotchi/worker_presence.rb +4 -0
  85. data/lib/samagotchi/working_set.rb +26 -0
  86. data/lib/samagotchi/working_set_command.rb +10 -7
  87. data/lib/samagotchi/working_set_steer.rb +3 -10
  88. metadata +9 -1
@@ -54,8 +54,11 @@ module Samagotchi
54
54
  # worker sees it: one runs, is starting or was started) or :waits (no
55
55
  # worker comes: it waits for the next start)
56
56
  # @!attribute wake [Symbol] WakePolicy#decide's outcome, :woken for a
57
- # start made, or the refusal (:gone, :owned: a one-turn chi run's,
58
- # :scratch)
57
+ # start made, or the refusal (:gone, :deleting: a deleter holds its
58
+ # lock, :owned: a one-turn chi run's, :scratch). :deleting after the
59
+ # write (status :waits) is a delete that took the lock meanwhile: the
60
+ # file goes with the session (a caller that reports the delivery takes
61
+ # it back, SessionInbox.withdraw)
59
62
  # @!attribute queued [Integer, nil] notes waiting (a note kind's), nil else
60
63
  Delivered = Data.define(:kind, :id, :asked, :via, :status, :wake, :queued) do
61
64
  def initialize(kind:, id:, asked:, via:, status:, wake:, queued: nil) = super
@@ -93,19 +96,22 @@ module Samagotchi
93
96
  def self.for_sender(client_id) = self.for(ClientId.wake_kind(client_id))
94
97
 
95
98
  # Why the delivery is refused before anything is written, else nil:
96
- # :gone (no session), :owned (a one-turn chi run's), :scratch.
99
+ # :gone (no session), :deleting (a deleter holds its lock: what is
100
+ # written goes with it), :owned (a one-turn chi run's), :scratch.
97
101
  # @param load [#call, nil] the session, read only when the scratch
98
102
  # flag decides (nil: not a scratch session)
99
103
  # @return [Symbol, nil]
100
104
  def refusal(presence, load: nil)
101
105
  return :gone unless presence.exists?
106
+ return :deleting if presence.deleting?
102
107
  return :owned if refuse_tui && presence.tui_owned?
103
108
 
104
109
  :scratch if refuse_scratch && scratch?(load)
105
110
  end
106
111
 
107
112
  # What the delivery means for the session's worker, in this order:
108
- # :gone, :owned (a one-turn chi run's), :live (a worker holds it: it
113
+ # :gone, :owned (a one-turn chi run's), :deleting (a deleter holds the
114
+ # lock: the session is going, no worker sees it), :live (a worker holds it: it
109
115
  # sees the delivery), :stopped (the stop marker: the only "stopped",
110
116
  # the file's status never decides), :archived, :starting (a worker is
111
117
  # being started: it reads the store on its first pass), :none (the
@@ -118,6 +124,7 @@ module Samagotchi
118
124
  def decide(presence, wake: true, load: nil)
119
125
  return :gone unless presence.exists?
120
126
  return :owned if presence.tui_owned?
127
+ return :deleting if presence.deleting?
121
128
  return :live if presence.owned?
122
129
  return :stopped if presence.stop_marked? && !unstops
123
130
  return :archived if presence.archived? && !starts_archived
@@ -279,9 +286,10 @@ module Samagotchi
279
286
  start: start)
280
287
  end
281
288
 
289
+ # Every kind reads the presence: a session being deleted refuses
290
+ # them all (WakePolicy#refusal).
282
291
  def refusal(policy, id, state_dir, owner)
283
292
  return :gone unless Session.exist?(id, state_dir: state_dir)
284
- return nil unless policy.refuse_tui || policy.refuse_scratch
285
293
 
286
294
  policy.refusal(presence(id, state_dir, owner), load: -> { Session.load(id, state_dir: state_dir) })
287
295
  end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../session_inbox"
4
+ require_relative "../session_lifecycle"
5
+
6
+ module Samagotchi
7
+ module SessionLifecycle
8
+ # What a delivery's WakePolicy#decide outcome is as a cell: a worker
9
+ # sees it (:live) or one is started (:start): go; it waits on disk for
10
+ # whoever runs the session next: wait; :gone, :owned and :deleting (a
11
+ # deleter holds the lock) are refusals. (:off and :scratch are
12
+ # op-local: a delivery that asks no worker, a scratch session's file.)
13
+ DELIVERY_CELLS = { start: :go, live: :go, starting: :wait, stopped: :wait, archived: :wait, none: :wait,
14
+ gone: :gone, owned: :owned, deleting: :deleting }.freeze
15
+
16
+ # The operations that are not inbox deliveries, in the order of LITERAL's
17
+ # rows: resume_session, restart_session, stop_session, archive
18
+ # (archivable!), delete (release_for_delete!, stop: false), a schedule's
19
+ # busy check in chain and in same mode (Schedules#busy_reason), and a
20
+ # terminal attaching (TerminalUI::LocalLink#live_worker).
21
+ LITERAL_OPS = %i[resume restart stop archive delete sched_chain sched_same attach].freeze
22
+
23
+ # What each literal operation answers in each state today, with neutral
24
+ # op-local facts (not scratch, saved status idle, no input/, no question
25
+ # or offer, not SIGSTOPped, features restart and activity, an idle worker
26
+ # with no streams). For schedules, worker_busy is "its worker is starting
27
+ # or leaving", deleting is DeliverResult::DELETING's detail, and
28
+ # worker_newer is WorkerLink::Skew#short_message. Resume's live is "a
29
+ # worker holds it"; restart's fallback is its unresponsive-worker path,
30
+ # its stop_marked a stop marked and its deleting a deleter holds the lock
31
+ # (it reads this table: restart_session's precheck); attach's gone_* are
32
+ # LocalLink's [:gone, why]. absent's delete and schedule cells are
33
+ # unreachable (a gone session is refused before the gate). Resolution (a
34
+ # chain's head, a continue's successor) stays outside: these are the
35
+ # link's own.
36
+ LITERAL = {
37
+ absent: %i[gone gone gone gone go go go wait],
38
+ tui_owned: %i[owned_by_tui owned_by_tui owned_by_tui owned_by_tui owned_by_tui go go wait],
39
+ deleting: %i[live deleting go go worker_running deleting deleting wait],
40
+ stopping: %i[live stop_marked go go worker_running stopped stopped gone_stopped],
41
+ skew: %i[live fallback go go worker_running worker_newer worker_newer gone_worker_newer],
42
+ leaving: %i[live not_running go go worker_running worker_busy worker_busy wait],
43
+ booting_stuck: %i[live fallback go go worker_running worker_busy worker_busy wait],
44
+ booting: %i[live starting go go worker_running worker_busy worker_busy wait],
45
+ live: %i[live go go go worker_running go go go],
46
+ stopped_starting: %i[go stop_marked go starting worker_running stopped stopped gone_stopped],
47
+ stopped: %i[go stop_marked go go go stopped stopped gone_stopped],
48
+ archived_starting: %i[starting not_running go starting worker_running worker_busy go wait],
49
+ starting: %i[starting not_running go starting worker_running worker_busy go wait],
50
+ archived: %i[go not_running go go go go go wait],
51
+ idle: %i[go not_running go go go go go wait]
52
+ }.freeze
53
+
54
+ # {op => {state => cell}}: every operation in every state (STATES order).
55
+ # The delivery columns are generated from SessionInbox::WakePolicy::ROWS
56
+ # (each row's #decide on CANONICAL, wake asked, no scratch file), so a
57
+ # row change moves its column; the literal columns are goldens of what
58
+ # the deciders do, pinned by spec/session_lifecycle/matrix_spec.rb.
59
+ ALLOWED = lambda do
60
+ deliveries = SessionInbox::WakePolicy::ROWS.to_h do |kind, policy|
61
+ [kind, STATES.to_h { |state| [state, DELIVERY_CELLS.fetch(policy.decide(CANONICAL.fetch(state), wake: true, load: nil))] }.freeze]
62
+ end
63
+ literal = LITERAL_OPS.each_with_index.to_h do |op, index|
64
+ [op, STATES.to_h { |state| [state, LITERAL.fetch(state).fetch(index)] }.freeze]
65
+ end
66
+ deliveries.merge(literal).freeze
67
+ end.call
68
+ end
69
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../owner_lock"
4
+ require_relative "../worker_link"
5
+ require_relative "../worker_presence"
6
+ require_relative "../worker_sidecar"
7
+ require_relative "../session_lifecycle"
8
+
9
+ module Samagotchi
10
+ module SessionLifecycle
11
+ # The fewest facts that make each state (STATES order), as a
12
+ # WorkerPresence with its link: what ALLOWED's delivery columns are
13
+ # decided on. Each derives back to its own state (Reading.derive). A
14
+ # compound state takes the decided facts: stopping is a worker whose
15
+ # Bridge answers, with a stop; stopped_starting a start marked before
16
+ # the stop (one marked after it holds a resume off: a row fact the
17
+ # characterization matrix keeps).
18
+ CANONICAL = lambda do
19
+ worker = OwnerLock::Owner.new(pid: 1, kind: "worker")
20
+ sidecar = WorkerSidecar.new(port: 1, pid: 1)
21
+ live = WorkerLink::Live.new(sidecar: sidecar, owner: worker)
22
+ at = lambda do |owner: nil, link: WorkerLink::None.new(owner: owner), exists: true, stop: false, start: false, archived: false|
23
+ WorkerPresence.new(session_id: "canonical", exists: exists, owner: owner, stop_marked: stop,
24
+ starting_marked: start, archived: archived, link: link)
25
+ end
26
+ tui = OwnerLock::Owner.new(pid: 1, kind: "tui")
27
+ deleting = OwnerLock::Owner.new(pid: 1, kind: OwnerLock::DELETING)
28
+ leaving = worker.with(leaving_at: "2020-01-01T00:00:00Z", leave_wait: 1.0)
29
+ {
30
+ absent: at.call(exists: false),
31
+ tui_owned: at.call(owner: tui),
32
+ deleting: at.call(owner: deleting, link: WorkerLink::Starting.new(owner: deleting)),
33
+ stopping: at.call(owner: worker, link: live, stop: true),
34
+ skew: at.call(owner: worker, link: WorkerLink::Skew.new(sidecar: sidecar.with(protocol: WorkerLink::PROTOCOL + 1),
35
+ owner: worker, reason: :protocol)),
36
+ leaving: at.call(owner: leaving, link: WorkerLink::Leaving.new(owner: leaving)),
37
+ booting_stuck: at.call(owner: worker, link: WorkerLink::Starting.new(owner: worker, stuck: true)),
38
+ booting: at.call(owner: worker, link: WorkerLink::Starting.new(owner: worker)),
39
+ live: at.call(owner: worker, link: live),
40
+ stopped_starting: at.call(stop: true, start: true),
41
+ stopped: at.call(stop: true),
42
+ archived_starting: at.call(archived: true, start: true),
43
+ starting: at.call(start: true),
44
+ archived: at.call(archived: true),
45
+ idle: at.call
46
+ }.freeze
47
+ end.call
48
+ end
49
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../worker_link"
4
+ require_relative "../worker_presence"
5
+ require_relative "../session_lifecycle"
6
+
7
+ module Samagotchi
8
+ module SessionLifecycle
9
+ # One read of a session's lifecycle: the state (one of STATES), the
10
+ # facts it was derived from, and the successor of a continue in flight.
11
+ # @!attribute state [Symbol] one of STATES
12
+ # @!attribute presence [WorkerPresence] read with its link (:look)
13
+ # @!attribute continuing [String, nil] ContinueIntent.in_flight's
14
+ # successor: a fact, not a state (only a send's or a schedule's link
15
+ # resolution reads it)
16
+ Reading = Data.define(:state, :presence, :continuing) do
17
+ # @param presence [WorkerPresence] with its link read
18
+ # @param continuing [String, nil]
19
+ # @return [Reading]
20
+ def self.derive(presence, continuing: nil)
21
+ new(state: state_of(presence), presence: presence, continuing: continuing)
22
+ end
23
+
24
+ # The first of STATES whose facts hold. A lock held by someone that is
25
+ # neither a one-turn run nor a deleter, without a worker's link (a lock
26
+ # record still blank: WorkerLink reads it Starting), is booting.
27
+ # @return [Symbol]
28
+ def self.state_of(presence)
29
+ return :absent unless presence.exists?
30
+
31
+ owner = presence.owner
32
+ return :tui_owned if owner&.tui?
33
+ return :deleting if owner&.deleting?
34
+ return :stopping if owner&.worker? && presence.stop_marked?
35
+ return link_state(presence.link) if owner
36
+
37
+ unowned_state(presence)
38
+ end
39
+
40
+ def self.link_state(link)
41
+ case link
42
+ when WorkerLink::Skew then :skew
43
+ when WorkerLink::Leaving then :leaving
44
+ when WorkerLink::Live then :live
45
+ when WorkerLink::Starting then link.stuck ? :booting_stuck : :booting
46
+ else :booting
47
+ end
48
+ end
49
+ private_class_method :link_state
50
+
51
+ def self.unowned_state(presence)
52
+ stop = presence.stop_marked?
53
+ start = presence.starting?
54
+ return start ? :stopped_starting : :stopped if stop
55
+ return start ? :archived_starting : :archived if presence.archived?
56
+
57
+ start ? :starting : :idle
58
+ end
59
+ private_class_method :unowned_state
60
+
61
+ def facts = presence
62
+ def continuing? = !continuing.nil?
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "session"
4
+ require_relative "worker_presence"
5
+ require_relative "continue_intent"
6
+
7
+ module Samagotchi
8
+ # A session's lifecycle state, derived from what is on disk now: one read of
9
+ # the liveness facts (WorkerPresence, with the WorkerLink looked at, never
10
+ # unlinked) and of a continue in flight (ContinueIntent.in_flight), named
11
+ # by the first of STATES whose facts hold (Reading.derive). Nothing is
12
+ # stored: see docs/internals/session-lifecycle.md (Derived states).
13
+ #
14
+ # A read only: it writes, clears and unlinks nothing (the marker writers
15
+ # are pinned in spec/session_lifecycle_writers_spec.rb). One decider
16
+ # reads it (restart_session's precheck, ALLOWED[:restart]); ALLOWED is what
17
+ # each operation does in each state, pinned against the deciders by
18
+ # spec/session_lifecycle/matrix_spec.rb.
19
+ module SessionLifecycle
20
+ # In precedence order: the first whose facts hold names the session.
21
+ # The compound states (stopped_starting, archived_starting) are there
22
+ # because the deciders disagree on which of two facts wins.
23
+ STATES = %i[absent tui_owned deleting stopping skew leaving booting_stuck booting live
24
+ stopped_starting stopped archived_starting starting archived idle].freeze
25
+
26
+ autoload :Reading, File.expand_path("session_lifecycle/reading", __dir__)
27
+ autoload :CANONICAL, File.expand_path("session_lifecycle/canonical", __dir__)
28
+ autoload :ALLOWED, File.expand_path("session_lifecycle/allowed", __dir__)
29
+
30
+ # The cell words that are no refusal, per operation: a resume that finds
31
+ # a worker there or one being started waits for it; a restart's
32
+ # fallback (an unresponsive worker's path) goes.
33
+ VERDICT_WORDS = { resume: { live: :wait, starting: :wait }, restart: { fallback: :go } }.freeze
34
+
35
+ module_function
36
+
37
+ # @return [Symbol] the cell of +op+ in +state+ (ALLOWED)
38
+ def allowed(op, state) = ALLOWED.fetch(op).fetch(state)
39
+
40
+ # A cell as :go, :wait or :refused: :go and :wait are themselves, an
41
+ # operation's own words (VERDICT_WORDS) theirs, every other a refusal.
42
+ # @return [Symbol]
43
+ def verdict(op, cell)
44
+ return cell if %i[go wait].include?(cell)
45
+
46
+ VERDICT_WORDS.fetch(op, {}).fetch(cell, :refused)
47
+ end
48
+
49
+ # Read +session_id+'s state now.
50
+ # @param state_dir [String, nil] nil: Session.default_state_dir
51
+ # @param owner [OwnerLock::Owner, nil, :read, #call] as WorkerPresence.read takes it
52
+ # @return [Reading]
53
+ def read(session_id, state_dir: nil, owner: :read)
54
+ sd = state_dir || Session.default_state_dir
55
+ presence = WorkerPresence.read(session_id, state_dir: sd, owner: owner, link: :look)
56
+ Reading.derive(presence, continuing: ContinueIntent.in_flight(session_id, state_dir: sd))
57
+ end
58
+ end
59
+ end
@@ -58,7 +58,7 @@ module Samagotchi
58
58
  # tool's follow-up says it after "Error: session <id8>".
59
59
  # @return [String]
60
60
  def refusal_text
61
- refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || continued? || wake_refused? ||
61
+ refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || continued? || wake_refused? || deleting? ||
62
62
  DeliverResult::REMOTE_REFUSALS.include?(error)
63
63
  "#{refused ? "refused" : "failed"}: #{detail || "could not queue it"}"
64
64
  end
@@ -76,6 +76,9 @@ module Samagotchi
76
76
  # (DeliverResult::STOPPED / ARCHIVED: only a person's message does).
77
77
  def wake_refused? = DeliverResult::WAKE_REFUSALS.include?(error)
78
78
 
79
+ # A session being deleted (DeliverResult::DELETING): nothing went in.
80
+ def deleting? = error == DeliverResult::DELETING["error"]
81
+
79
82
  # A --cut's outcome ("now", "waits", "off"), nil when nothing was cut.
80
83
  def cut = ack["cut"]
81
84
 
@@ -101,6 +104,11 @@ module Samagotchi
101
104
  DeliverResult::ARCHIVED = { "error" => "session_archived",
102
105
  "detail" => "the session is archived; only its owner's message brings it back" }.freeze
103
106
  DeliverResult::WAKE_REFUSALS = [DeliverResult::STOPPED["error"], DeliverResult::ARCHIVED["error"]].freeze
107
+ # Any sender's turn to a session a deleter holds (its owner lock kind
108
+ # deleting: a delete, an empty session's discard), or that went while
109
+ # the input was written: refused (a 409 from chi web), its file taken
110
+ # back (SessionInbox.withdraw), never accepted and then removed.
111
+ DeliverResult::DELETING = { "error" => "session_deleting", "detail" => "the session is being deleted" }.freeze
104
112
 
105
113
  # The unclaimed input files +author+ wrote.
106
114
  PARTICIPANT_QUEUE_LOCK = "participants.lock"
@@ -140,7 +148,8 @@ module Samagotchi
140
148
  # a web tab, a TUI) un-stops a stopped session and starts an archived
141
149
  # link; a schedule's, a plugin's, a delegate's, a participant's or an
142
150
  # unknown one's is refused there (:refused 409, DeliverResult::STOPPED
143
- # / ARCHIVED, nothing written)
151
+ # / ARCHIVED, nothing written); anyone's to a session being deleted
152
+ # is refused (:refused 409, DeliverResult::DELETING)
144
153
  # @param images [Array<Hash>] refs ({file:, name:}) already in images/
145
154
  # @param delivery [String, nil] what the message asks the running turn
146
155
  # for: "next_step" (default), "cut" or "queue"
@@ -314,10 +323,14 @@ module Samagotchi
314
323
  # A worker that idle-exited since the resume never reads it either:
315
324
  # wake a new one. (The exiting worker also looks for input it left;
316
325
  # one the first resume spawned that is still starting is left be.)
317
- start_for_send(manager, session_id, state_dir, client_id, before: false) do
326
+ refused = start_for_send(manager, session_id, state_dir, client_id, before: false, written: path) do
318
327
  FileUtils.rm_f(path) if path.is_a?(String)
319
328
  raise OwnedByTUI, session_id
320
329
  end
330
+ # A delete that took the lock between the check and the write: the
331
+ # file is taken back (unless a worker claimed it already).
332
+ return refused if refused && SessionInbox.withdraw(path, session_id, state_dir: state_dir || Session.default_state_dir)
333
+
321
334
  DeliverResult.new(status: :accepted, via: :file,
322
335
  ack: { "status" => "accepted", "enqueued_id" => enqueued_id, "session_id" => session_id })
323
336
  end
@@ -341,14 +354,24 @@ module Samagotchi
341
354
  # held for its last work) has its input served by its own respawn
342
355
  # (WorkerBoot's leave): a stop that landed before this send is
343
356
  # cleared, as resume_session clears it (a person's send un-stops); one
344
- # that lands after it still wins.
357
+ # that lands after it still wins. A deleter holding the lock refuses
358
+ # any sender, before the write and after it (DeliverResult::DELETING),
359
+ # and so does a session gone after the write (+written+, the file's
360
+ # path: a stand-in manager's write makes none).
345
361
  # @return [DeliverResult, nil] the refusal of a wake the sender may not
346
- # make (+before+ only), else nil
347
- private def start_for_send(manager, session_id, state_dir, client_id, before:)
362
+ # make (+before+ only) or of a session being deleted, else nil
363
+ private def start_for_send(manager, session_id, state_dir, client_id, before:, written: nil)
348
364
  presence = delivery_presence(manager, session_id, state_dir)
349
365
  policy = SessionInbox::WakePolicy.for_sender(client_id)
350
366
  outcome = policy.decide(presence)
351
367
  yield if outcome == :owned && block_given?
368
+ if outcome == :deleting || (outcome == :gone && !before)
369
+ if before || written.is_a?(String)
370
+ Log.info(:worker, "send_deleting_refused", sid: session_id[0, 8], kind: policy.kind, before: before)
371
+ return DeliverResult.new(status: :refused, code: 409, ack: DeliverResult::DELETING)
372
+ end
373
+ return nil if outcome == :deleting
374
+ end
352
375
  if %i[stopped archived].include?(outcome)
353
376
  return nil unless before
354
377
 
@@ -10,10 +10,9 @@ require_relative "../process_group"
10
10
  require_relative "../reminder_carry"
11
11
  require_relative "../session"
12
12
  require_relative "../session_inbox"
13
- require_relative "../task_files"
14
- require_relative "../tools/task_record"
15
- require_relative "../task_transcript"
13
+ require_relative "../session_lifecycle"
16
14
  require_relative "../worker_link"
15
+ require_relative "running_tasks"
17
16
 
18
17
  module Samagotchi
19
18
  class SessionManager
@@ -23,7 +22,10 @@ module Samagotchi
23
22
  # WorkerIdleExit#hold_for_restart hold (:turn_running, :reminders, ...),
24
23
  # :fallback_held (disk-visible work blocks an unresponsive-worker restart),
25
24
  # :stopped (its worker, +pid+, is SIGSTOPped: neither the ask nor a TERM
26
- # reaches it until it is continued), or :failed (the worker answered something else or didn't release).
25
+ # reaches it until it is continued), :stop_marked (the session is stopped,
26
+ # or being stopped: `chi sessions stop`, no successor would come),
27
+ # :deleting (a deleter holds the lock: the session is going), or
28
+ # :failed (the worker answered something else or didn't release).
27
29
  class RestartRefused < StandardError
28
30
  attr_reader :session_id, :reason, :version, :holds, :pid
29
31
 
@@ -46,7 +48,7 @@ module Samagotchi
46
48
  reminders: "it has reminders, which its worker's older chi can't carry over a restart",
47
49
  command_running: "a /btw (or another command) is still running",
48
50
  relays_open: "a delegate's approval relayed here is open or just answered",
49
- background_tasks: "background tasks it started are still running",
51
+ background_tasks: RunningTasks::LEAD,
50
52
  scratch: "a chi scratch session's worker ends with its terminal"
51
53
  }.merge(WorkerIdleExit::LEAVING_WORDS).freeze
52
54
 
@@ -58,6 +60,10 @@ module Samagotchi
58
60
  where = via.remote? ? " on #{via.remote}" : ""
59
61
  "session #{session_id}'s worker#{" (pid #{pid})" if pid} is stopped (SIGSTOP or Ctrl-Z) and can't take " \
60
62
  "a restart: continue it#{" with `kill -CONT #{pid}`" if pid}#{where}, then restart again"
63
+ when :stop_marked
64
+ "session #{session_id} can't restart: #{DeliverResult::STOPPED["detail"]} (on the newest chi)"
65
+ when :deleting
66
+ "session #{session_id} can't restart: #{DeliverResult::DELETING["detail"]}"
61
67
  when :not_running
62
68
  "session #{session_id} has no running worker; the next prompt starts one on the newest chi"
63
69
  when :unsupported
@@ -107,23 +113,26 @@ module Samagotchi
107
113
  def restart_session(session_id, state_dir: nil, wait: RESTART_WAIT, client_id: ClientId::CLI_RESTART)
108
114
  sd = state_dir || Session.default_state_dir
109
115
  Session.load(session_id, state_dir: sd) # ArgumentError for none
110
- owner = refuse_tui!(session_id, state_dir: sd)
116
+ # The lifecycle precheck is ALLOWED[:restart] for the state read now
117
+ # (a stop marked refuses before the worker is asked); the op-local
118
+ # checks (SIGSTOP, features, the Bridge's reply, the fallback) are here.
119
+ reading = SessionLifecycle.read(session_id, state_dir: sd, owner: session_owner(session_id, state_dir: sd))
120
+ cell = SessionLifecycle.allowed(:restart, reading.state)
121
+ raise OwnedByTUI, session_id if cell == :owned_by_tui
122
+ raise Session::NotFound, session_id if cell == :gone
123
+
124
+ owner = reading.presence.owner
111
125
  # A stopped worker answers neither the ask (READ_TIMEOUT) nor the
112
126
  # fallback's TERM (FALLBACK_STOP_WAIT): say so now, not after ~70 s.
113
127
  raise RestartRefused.new(session_id, :stopped, pid: owner.pid) if owner&.worker? && ProcessGroup.stopped?(owner.pid)
128
+ raise RestartRefused.new(session_id, cell) if SessionLifecycle.verdict(:restart, cell) == :refused
114
129
 
115
- dir = Session.session_dir(session_id, state_dir: sd)
116
- link = WorkerLink.resolve(dir, unlink: false, owner: owner)
117
- if link.is_a?(WorkerLink::Skew)
118
- return restart_fallback(session_id, owner: owner, sidecar: link.sidecar, state_dir: sd, wait: wait, why: :skew)
119
- end
120
-
121
- if link.is_a?(WorkerLink::Starting)
122
- return restart_fallback(session_id, owner: owner, sidecar: nil, state_dir: sd, wait: wait, why: :starting_stuck) if link.stuck
123
-
124
- raise RestartRefused.new(session_id, :starting)
130
+ link = reading.presence.link
131
+ if cell == :fallback
132
+ skew = link.is_a?(WorkerLink::Skew)
133
+ return restart_fallback(session_id, owner: owner, sidecar: (link.sidecar if skew), state_dir: sd, wait: wait,
134
+ why: skew ? :skew : :starting_stuck)
125
135
  end
126
- raise RestartRefused.new(session_id, :not_running) unless link.live?
127
136
 
128
137
  sidecar = link.sidecar
129
138
  unless sidecar.features.include?("restart")
@@ -143,7 +152,7 @@ module Samagotchi
143
152
  raise RestartRefused.new(session_id, :failed) unless reply.status == 200
144
153
 
145
154
  Log.info(:worker, "restart", sid: session_id, from: sidecar.version, by: client_id)
146
- fresh = WorkerLink.await(session_id, session_dir: dir, timeout: wait, unlink: false, interval: 0.1,
155
+ fresh = WorkerLink.await(session_id, session_dir: Session.session_dir(session_id, state_dir: sd), timeout: wait, unlink: false, interval: 0.1,
147
156
  until: ->(live) { live.epoch != sidecar.epoch || live.started_at != sidecar.started_at })
148
157
  # Timed out: the last outcome, the old worker's Live too, is no successor.
149
158
  changed = fresh.live? && (fresh.epoch != sidecar.epoch || fresh.started_at != sidecar.started_at)
@@ -155,7 +164,7 @@ module Samagotchi
155
164
  Log.info(:worker, "restart_fallback", sid: session_id, why: why, error: error&.class&.name, msg: error&.message)
156
165
  dir = Session.session_dir(session_id, state_dir: state_dir)
157
166
  session = Session.load(session_id, state_dir: state_dir)
158
- holds = restart_fallback_holds(session, dir)
167
+ holds = restart_fallback_holds(session, dir, state_dir)
159
168
  raise RestartRefused.new(session_id, :fallback_held, holds: holds) unless holds.empty?
160
169
  raise RestartRefused.new(session_id, :failed, version: sidecar&.version) unless (owner&.pid || 0).to_i.positive?
161
170
 
@@ -187,33 +196,18 @@ module Samagotchi
187
196
  Restarted.new(session_id: session_id, from_version: sidecar&.version, version: (fresh.version if changed))
188
197
  end
189
198
 
190
- private def restart_fallback_holds(session, session_dir)
199
+ # A task that may still run holds it (RunningTasks.of: a live one, one
200
+ # chi can't verify, an unreadable record); a record left marked
201
+ # running by a crashed worker whose pid is gone doesn't.
202
+ private def restart_fallback_holds(session, session_dir, state_dir)
191
203
  holds = []
192
204
  holds << :turn_running if session.status == Session::STATUS_RUNNING
193
205
  holds << :question_pending if session.pending_question
194
206
  holds << :input_queued unless SessionInbox.find_new_input_files(session_dir).empty?
195
- holds << :background_tasks if running_created_task?(session)
207
+ holds << :background_tasks unless RunningTasks.of([session.id], state_dir: state_dir).empty?
196
208
  holds
197
209
  end
198
210
 
199
- private def running_created_task?(session)
200
- root = session.working_directory.to_s
201
- return false if root.empty?
202
-
203
- TaskTranscript.created_ids_in(session.messages).any? do |id|
204
- next false unless TaskFiles::TASK_ID.match?(id)
205
-
206
- path = File.join(root, TaskFiles::TASKS_DIR, id, TaskFiles::METADATA_FILENAME)
207
- next false unless File.file?(path)
208
-
209
- Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.running?
210
- rescue JSON::ParserError, SystemCallError => e
211
- Log.warn(:worker, "restart_task_check_failed", sid: session.id, task_id: id,
212
- error: e.class.name, msg: e.message)
213
- true
214
- end
215
- end
216
-
217
211
  # Stop a session by sending TERM (then CONT, for a stopped one) to its process.
218
212
  # With +wait+ (seconds), also wait for the owner to let go of the session,
219
213
  # so a resume right after spawns a fresh worker instead of finding the