samagotchi 0.176.0 → 0.177.1

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 (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +47 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +12 -5
  5. data/docs/internals/bundles.md +4 -3
  6. data/docs/internals/participants.md +10 -6
  7. data/docs/internals/prompt-caching.md +3 -0
  8. data/docs/internals/session-lifecycle.md +167 -0
  9. data/docs/internals/web-frontend.md +25 -8
  10. data/docs/internals/working-set.md +78 -6
  11. data/docs/plugins.md +1 -1
  12. data/docs/releasing.md +3 -2
  13. data/docs/sessions.md +8 -5
  14. data/docs/testing.md +4 -2
  15. data/lib/samagotchi/bridge.rb +3 -3
  16. data/lib/samagotchi/bundle_command/check.rb +1 -1
  17. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  18. data/lib/samagotchi/compat.rb +1 -1
  19. data/lib/samagotchi/engine/models.rb +11 -0
  20. data/lib/samagotchi/engine/session.rb +16 -0
  21. data/lib/samagotchi/engine.rb +1 -0
  22. data/lib/samagotchi/engine_snapshots.rb +3 -0
  23. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  24. data/lib/samagotchi/note_delivery.rb +9 -4
  25. data/lib/samagotchi/plugin/sessions.rb +2 -1
  26. data/lib/samagotchi/prompt_part.rb +66 -0
  27. data/lib/samagotchi/revise_anchor.rb +2 -0
  28. data/lib/samagotchi/schedules.rb +3 -1
  29. data/lib/samagotchi/session.rb +10 -1
  30. data/lib/samagotchi/session_chain/delete.rb +28 -5
  31. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  32. data/lib/samagotchi/session_inbox.rb +29 -0
  33. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  34. data/lib/samagotchi/session_lifecycle/allowed.rb +66 -0
  35. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  36. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  37. data/lib/samagotchi/session_lifecycle.rb +59 -0
  38. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  39. data/lib/samagotchi/session_manager/lifecycle.rb +22 -14
  40. data/lib/samagotchi/session_manager/removal.rb +16 -8
  41. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  42. data/lib/samagotchi/sessions_command.rb +1 -1
  43. data/lib/samagotchi/system_prompt.rb +211 -12
  44. data/lib/samagotchi/tool_names.rb +1 -1
  45. data/lib/samagotchi/tools/memory.rb +29 -0
  46. data/lib/samagotchi/turn_anchors.rb +5 -0
  47. data/lib/samagotchi/verify_anchor.rb +2 -0
  48. data/lib/samagotchi/version.rb +1 -1
  49. data/lib/samagotchi/web/participant_show.rb +4 -5
  50. data/lib/samagotchi/web/participant_view.rb +4 -6
  51. data/lib/samagotchi/web/public/app.js +3 -0
  52. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  53. data/lib/samagotchi/web/public/data.js +6 -2
  54. data/lib/samagotchi/web/public/delete_sheet.js +42 -5
  55. data/lib/samagotchi/web/public/index.html +43 -9
  56. data/lib/samagotchi/web/public/session_fields.js +10 -4
  57. data/lib/samagotchi/web/public/session_prefs.js +5 -2
  58. data/lib/samagotchi/web/public/session_state.js +14 -1
  59. data/lib/samagotchi/web/public/session_store.js +1 -1
  60. data/lib/samagotchi/web/public/session_view.js +1 -1
  61. data/lib/samagotchi/web/public/stream_handlers.js +7 -3
  62. data/lib/samagotchi/web/public/tokens.css +2 -2
  63. data/lib/samagotchi/web/public/working_set.js +51 -7
  64. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  65. data/lib/samagotchi/web/public/ws_sections.js +252 -0
  66. data/lib/samagotchi/web/session_control.rb +4 -3
  67. data/lib/samagotchi/web/session_show.rb +13 -2
  68. data/lib/samagotchi/web/session_summary.rb +7 -0
  69. data/lib/samagotchi/worker/command_queue.rb +5 -1
  70. data/lib/samagotchi/worker/startup.rb +1 -1
  71. data/lib/samagotchi/worker.rb +1 -0
  72. data/lib/samagotchi/worker_boot.rb +9 -6
  73. data/lib/samagotchi/worker_presence.rb +4 -0
  74. data/lib/samagotchi/working_set.rb +32 -4
  75. data/lib/samagotchi/working_set_command.rb +3 -2
  76. data/lib/samagotchi/working_set_steer.rb +14 -3
  77. metadata +9 -1
@@ -17,6 +17,7 @@ require_relative "toolkit"
17
17
  require_relative "session_config"
18
18
  require_relative "session_setup"
19
19
  require_relative "prompt_note"
20
+ require_relative "prompt_part"
20
21
  require_relative "working_set_pin"
21
22
  require_relative "session_review"
22
23
  require_relative "session_field"
@@ -182,6 +183,10 @@ module Samagotchi
182
183
  # Engine at each build (a start, a resume's or a woken worker's first
183
184
  # turn, /model) and saved, so what a session ran with can be read later.
184
185
  SessionField.list("prompt_notes") { PromptNote },
186
+ # The sizes of the parts that prompt was made of (Array<PromptPart>:
187
+ # kind, label, chars, tokens, ref), recorded with prompt_notes; the web's
188
+ # head view lists them. An older file has none: [].
189
+ SessionField.list("prompt_parts") { PromptPart },
185
190
  # The session that delegated this one (the `delegate` tool) or that a
186
191
  # plugin forked it from (ctx.sessions.fork), else nil.
187
192
  # Set before the spawn and kept on respawns, like preloaded_memory_names.
@@ -314,13 +319,17 @@ module Samagotchi
314
319
 
315
320
  # The value objects' readers and writers: a writer reads its value as
316
321
  # its FIELDS row does (a file's Hash, the object itself; nil is none).
317
- attr_reader :prompt_notes, :pending_question, :last_turn, :interrupted_turn, :toolkit, :review, :verify_fresh,
322
+ attr_reader :prompt_notes, :prompt_parts, :pending_question, :last_turn, :interrupted_turn, :toolkit, :review, :verify_fresh,
318
323
  :working_set_pins
319
324
 
320
325
  def prompt_notes=(value)
321
326
  @prompt_notes = load_field("prompt_notes", value)
322
327
  end
323
328
 
329
+ def prompt_parts=(value)
330
+ @prompt_parts = load_field("prompt_parts", value)
331
+ end
332
+
324
333
  def pending_question=(value)
325
334
  @pending_question = load_field("pending_question", value)
326
335
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require "json"
4
5
  require_relative "links"
5
6
  require_relative "../archive_store"
@@ -117,6 +118,22 @@ module Samagotchi
117
118
  cut_off: links.gone?(links.chain(id).first))
118
119
  end
119
120
 
121
+ # The ids each delete choice shows, encoded as stable, sorted sets.
122
+ def digest(plan)
123
+ canonical = case plan
124
+ when LinkPlan
125
+ [[plan.id], [plan.previous].compact, plan.revive, plan.moved,
126
+ plan.delegates.delete, plan.delegates.leave].map(&:sort)
127
+ when ChainPlan
128
+ [plan.links.sort, *plan.delegates.sort.map do |link, delegates|
129
+ [link, delegates.delete.sort, delegates.leave.sort]
130
+ end]
131
+ else
132
+ raise ArgumentError, "unknown delete plan: #{plan.class}"
133
+ end
134
+ Digest::SHA256.hexdigest(JSON.generate(canonical))[0, 16]
135
+ end
136
+
120
137
  # Whether +id+ is in a chain of 2 or more links that still exist (D1):
121
138
  # a link alone past a gap (its predecessor deleted) is deleted as a
122
139
  # session in no chain is.
@@ -130,17 +147,19 @@ module Samagotchi
130
147
  # @raise [SessionManager::DeleteRefused] :continuing, :scheduled,
131
148
  # :delegate_unmovable, :worker_running, :still_stopping
132
149
  # @raise [SessionManager::OwnedByTUI]
133
- def link(id, state_dir:, stop:, wait:, revive_previous:, refuse_continuing:)
150
+ def link(id, state_dir:, stop:, wait:, revive_previous:, refuse_continuing:, expect: nil)
134
151
  ContinueIntent.hold(id, state_dir: state_dir) do |held|
135
152
  raise SessionManager::DeleteRefused.new(id, :continuing) if refuse_continuing && !held
136
153
 
137
154
  links = Links.new(state_dir: state_dir)
138
155
  unless chained?(id, links)
156
+ raise SessionManager::DeleteRefused.new(id, :plan_changed) unless expect.nil?
157
+
139
158
  return plain(SessionManager.delete_resolved(id, state_dir: state_dir, stop: stop, wait: wait))
140
159
  end
141
160
 
142
161
  plan = link_plan(id, state_dir: state_dir, links: links, undo: revive_previous)
143
- return delete_link(plan, state_dir: state_dir, stop: stop, wait: wait) unless plan.previous
162
+ return delete_link(plan, state_dir: state_dir, stop: stop, wait: wait, expect: expect) unless plan.previous
144
163
 
145
164
  # Taken before the link's file goes: after it, a continue of the
146
165
  # previous link would no longer be refused. The plan is made again
@@ -149,7 +168,7 @@ module Samagotchi
149
168
  raise SessionManager::DeleteRefused.new(plan.previous, :continuing) unless previous_held
150
169
 
151
170
  again = link_plan(id, state_dir: state_dir, links: Links.new(state_dir: state_dir), undo: true)
152
- return delete_link(again, state_dir: state_dir, stop: stop, wait: wait)
171
+ return delete_link(again, state_dir: state_dir, stop: stop, wait: wait, expect: expect)
153
172
  end
154
173
  end
155
174
  end
@@ -180,7 +199,9 @@ module Samagotchi
180
199
  # files. So a refusal (a schedule on a delegate, a one-turn run, a
181
200
  # worker that took the link or a delegate after the checks) leaves
182
201
  # every session in place.
183
- def delete_link(plan, state_dir:, stop:, wait:)
202
+ def delete_link(plan, state_dir:, stop:, wait:, expect: nil)
203
+ raise SessionManager::DeleteRefused.new(plan.id, :plan_changed) if !expect.nil? && expect != digest(plan)
204
+
184
205
  id = plan.id
185
206
  check_link!(plan, state_dir)
186
207
  stopped = SessionManager.release_for_delete!(id, state_dir: state_dir, stop: stop, wait: wait)
@@ -314,9 +335,11 @@ module Samagotchi
314
335
  # earlier ones; refusal: the message of a part-way refusal, or nil)
315
336
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
316
337
  # nothing was deleted
317
- def chain(id, state_dir:, stop:, wait:)
338
+ def chain(id, state_dir:, stop:, wait:, expect: nil)
318
339
  links = Links.new(state_dir: state_dir)
319
340
  plan = chain_plan(id, state_dir: state_dir, links: links)
341
+ raise SessionManager::DeleteRefused.new(plan.id, :plan_changed) if !expect.nil? && expect != digest(plan)
342
+
320
343
  check_chain!(plan, state_dir, stop: stop)
321
344
  hold_all(plan.links, state_dir) do
322
345
  stopped = plan.links.select do |link|
@@ -35,7 +35,7 @@ module Samagotchi
35
35
  end
36
36
 
37
37
  def link_json(plan, links, whole, at, state_dir)
38
- { previous_id: plan.previous, moved: moved_count(plan, state_dir), notes: plan.notes, unarchived: plan.revive.size,
38
+ { digest: Delete.digest(plan), previous_id: plan.previous, moved: moved_count(plan, state_dir), notes: plan.notes, unarchived: plan.revive.size,
39
39
  deletes: plan.delegates.delete.size, left_running: plan.delegates.leave.size,
40
40
  earlier: at, next_id: links.next_of(plan.id), later: whole.links.size - at - 1,
41
41
  refusal: refusal(state_dir) { link_checks(plan, state_dir) } }
@@ -48,7 +48,7 @@ module Samagotchi
48
48
  end
49
49
 
50
50
  def chain_json(plan, state_dir)
51
- { links: plan.links.size, deletes: plan.delegates.values.sum { |d| d.delete.size },
51
+ { digest: Delete.digest(plan), links: plan.links.size, deletes: plan.delegates.values.sum { |d| d.delete.size },
52
52
  left_running: plan.delegates.values.sum { |d| d.leave.size },
53
53
  refusal: refusal(state_dir) { chain_checks(plan, state_dir) } }
54
54
  end
@@ -94,6 +94,35 @@ module Samagotchi
94
94
  false
95
95
  end
96
96
 
97
+ # Take back a file a delivery wrote (an input, a note) once it read
98
+ # the session as being deleted (WakePolicy's :deleting, or gone) after
99
+ # its write: the delete took the lock between its check and its write.
100
+ # @return [Boolean] true when nobody has it: removed now, or gone with
101
+ # the session (its folder, if the write made it again, is removed when
102
+ # empty); false when a worker claimed it meanwhile (renamed to
103
+ # .processing: the delete gave up and the file is delivered after all)
104
+ def self.withdraw(path, session_id, state_dir:)
105
+ removed = begin
106
+ File.delete(path)
107
+ true
108
+ rescue Errno::ENOENT
109
+ false
110
+ end
111
+ return removed if Session.exist?(session_id, state_dir: state_dir)
112
+
113
+ remove_left_folder(File.dirname(path), session_id, state_dir)
114
+ true
115
+ end
116
+
117
+ # A gone session's folder that a late write made again (mkdir_p),
118
+ # inbox folder first, both only while empty.
119
+ def self.remove_left_folder(inbox_dir, session_id, state_dir)
120
+ [inbox_dir, Session.session_dir(session_id, state_dir: state_dir)].each { |dir| Dir.rmdir(dir) }
121
+ rescue SystemCallError
122
+ nil
123
+ end
124
+ private_class_method :remove_left_folder
125
+
97
126
  # Queue a context note for a session: background text its worker adds
98
127
  # to the conversation between turns. It never starts a turn.
99
128
  # @param source [String] where it came from ("cli", "slack", "session")
@@ -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,66 @@
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). worker_busy is a schedule's "its worker is starting
27
+ # or leaving"; resume's live is "a worker holds it"; restart's fallback
28
+ # is its unresponsive-worker path, its stop_marked a stop marked (it
29
+ # reads this table: restart_session's precheck); attach's gone_* are LocalLink's
30
+ # [:gone, why]. absent's delete and schedule cells are unreachable (a
31
+ # gone session is refused before the gate). Resolution (a chain's head,
32
+ # a continue's successor) stays outside: these are the link's own.
33
+ LITERAL = {
34
+ absent: %i[gone gone gone gone go go go wait],
35
+ tui_owned: %i[owned_by_tui owned_by_tui owned_by_tui owned_by_tui owned_by_tui go go wait],
36
+ deleting: %i[live starting go go worker_running worker_busy worker_busy wait],
37
+ stopping: %i[live stop_marked go go worker_running stopped stopped gone_stopped],
38
+ skew: %i[live fallback go go worker_running worker_busy worker_busy gone_worker_newer],
39
+ leaving: %i[live not_running go go worker_running worker_busy worker_busy wait],
40
+ booting_stuck: %i[live fallback go go worker_running worker_busy worker_busy wait],
41
+ booting: %i[live starting go go worker_running worker_busy worker_busy wait],
42
+ live: %i[live go go go worker_running go go go],
43
+ stopped_starting: %i[go stop_marked go starting worker_running stopped stopped gone_stopped],
44
+ stopped: %i[go stop_marked go go go stopped stopped gone_stopped],
45
+ archived_starting: %i[starting not_running go starting worker_running worker_busy go wait],
46
+ starting: %i[starting not_running go starting worker_running worker_busy go wait],
47
+ archived: %i[go not_running go go go go go wait],
48
+ idle: %i[go not_running go go go go go wait]
49
+ }.freeze
50
+
51
+ # {op => {state => cell}}: every operation in every state (STATES order).
52
+ # The delivery columns are generated from SessionInbox::WakePolicy::ROWS
53
+ # (each row's #decide on CANONICAL, wake asked, no scratch file), so a
54
+ # row change moves its column; the literal columns are goldens of what
55
+ # the deciders do, pinned by spec/session_lifecycle/matrix_spec.rb.
56
+ ALLOWED = lambda do
57
+ deliveries = SessionInbox::WakePolicy::ROWS.to_h do |kind, policy|
58
+ [kind, STATES.to_h { |state| [state, DELIVERY_CELLS.fetch(policy.decide(CANONICAL.fetch(state), wake: true, load: nil))] }.freeze]
59
+ end
60
+ literal = LITERAL_OPS.each_with_index.to_h do |op, index|
61
+ [op, STATES.to_h { |state| [state, LITERAL.fetch(state).fetch(index)] }.freeze]
62
+ end
63
+ deliveries.merge(literal).freeze
64
+ end.call
65
+ end
66
+ 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,6 +10,7 @@ require_relative "../process_group"
10
10
  require_relative "../reminder_carry"
11
11
  require_relative "../session"
12
12
  require_relative "../session_inbox"
13
+ require_relative "../session_lifecycle"
13
14
  require_relative "../task_files"
14
15
  require_relative "../tools/task_record"
15
16
  require_relative "../task_transcript"
@@ -23,7 +24,9 @@ module Samagotchi
23
24
  # WorkerIdleExit#hold_for_restart hold (:turn_running, :reminders, ...),
24
25
  # :fallback_held (disk-visible work blocks an unresponsive-worker restart),
25
26
  # :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).
27
+ # reaches it until it is continued), :stop_marked (the session is stopped,
28
+ # or being stopped: `chi sessions stop`, no successor would come), or
29
+ # :failed (the worker answered something else or didn't release).
27
30
  class RestartRefused < StandardError
28
31
  attr_reader :session_id, :reason, :version, :holds, :pid
29
32
 
@@ -58,6 +61,8 @@ module Samagotchi
58
61
  where = via.remote? ? " on #{via.remote}" : ""
59
62
  "session #{session_id}'s worker#{" (pid #{pid})" if pid} is stopped (SIGSTOP or Ctrl-Z) and can't take " \
60
63
  "a restart: continue it#{" with `kill -CONT #{pid}`" if pid}#{where}, then restart again"
64
+ when :stop_marked
65
+ "session #{session_id} can't restart: #{DeliverResult::STOPPED["detail"]} (on the newest chi)"
61
66
  when :not_running
62
67
  "session #{session_id} has no running worker; the next prompt starts one on the newest chi"
63
68
  when :unsupported
@@ -107,24 +112,27 @@ module Samagotchi
107
112
  def restart_session(session_id, state_dir: nil, wait: RESTART_WAIT, client_id: ClientId::CLI_RESTART)
108
113
  sd = state_dir || Session.default_state_dir
109
114
  Session.load(session_id, state_dir: sd) # ArgumentError for none
110
- owner = refuse_tui!(session_id, state_dir: sd)
115
+ # The lifecycle precheck is ALLOWED[:restart] for the state read now
116
+ # (a stop marked refuses before the worker is asked); the op-local
117
+ # checks (SIGSTOP, features, the Bridge's reply, the fallback) are here.
118
+ reading = SessionLifecycle.read(session_id, state_dir: sd, owner: session_owner(session_id, state_dir: sd))
119
+ cell = SessionLifecycle.allowed(:restart, reading.state)
120
+ raise OwnedByTUI, session_id if cell == :owned_by_tui
121
+ raise Session::NotFound, session_id if cell == :gone
122
+
123
+ owner = reading.presence.owner
111
124
  # A stopped worker answers neither the ask (READ_TIMEOUT) nor the
112
125
  # fallback's TERM (FALLBACK_STOP_WAIT): say so now, not after ~70 s.
113
126
  raise RestartRefused.new(session_id, :stopped, pid: owner.pid) if owner&.worker? && ProcessGroup.stopped?(owner.pid)
127
+ raise RestartRefused.new(session_id, cell) if SessionLifecycle.verdict(:restart, cell) == :refused
114
128
 
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)
129
+ link = reading.presence.link
130
+ if cell == :fallback
131
+ skew = link.is_a?(WorkerLink::Skew)
132
+ return restart_fallback(session_id, owner: owner, sidecar: (link.sidecar if skew), state_dir: sd, wait: wait,
133
+ why: skew ? :skew : :starting_stuck)
119
134
  end
120
135
 
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)
125
- end
126
- raise RestartRefused.new(session_id, :not_running) unless link.live?
127
-
128
136
  sidecar = link.sidecar
129
137
  unless sidecar.features.include?("restart")
130
138
  raise RestartRefused.new(session_id, :unsupported, version: sidecar.version)
@@ -143,7 +151,7 @@ module Samagotchi
143
151
  raise RestartRefused.new(session_id, :failed) unless reply.status == 200
144
152
 
145
153
  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,
154
+ fresh = WorkerLink.await(session_id, session_dir: Session.session_dir(session_id, state_dir: sd), timeout: wait, unlink: false, interval: 0.1,
147
155
  until: ->(live) { live.epoch != sidecar.epoch || live.started_at != sidecar.started_at })
148
156
  # Timed out: the last outcome, the old worker's Live too, is no successor.
149
157
  changed = fresh.live? && (fresh.epoch != sidecar.epoch || fresh.started_at != sidecar.started_at)