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
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../session_stores"
4
+ require_relative "running_tasks"
4
5
 
5
6
  module Samagotchi
6
7
  class SessionManager
@@ -13,18 +14,36 @@ module Samagotchi
13
14
  # the previous one a delete would bring back), :delegate_unmovable (a
14
15
  # delegate the deleted link's continue moved can't go back: +ids+,
15
16
  # +detail+ says why), :chain_scheduled (a schedule is on the chain a
16
- # chain delete would take: +schedule_id+).
17
+ # chain delete would take: +schedule_id+), :plan_changed (the plan no
18
+ # longer matches the digest the caller confirmed), :tasks_running
19
+ # (background tasks it or a session the delete takes started still run:
20
+ # +tasks+, a RunningTasks::Listing; +worker_stopped+ when a worker was
21
+ # stopped before the last check found them, +stopped_worker+ whose:
22
+ # +worker_stopped:+ takes true for this session's or that session's id;
23
+ # +links+ the chain's other links, for the words).
17
24
  class DeleteRefused < StandardError
18
- attr_reader :session_id, :reason, :schedule_id, :ids
25
+ attr_reader :session_id, :reason, :schedule_id, :ids, :tasks, :stopped_worker, :links
19
26
 
20
- def initialize(session_id, reason, message: nil, schedule_id: nil, ids: [], detail: nil)
27
+ def initialize(session_id, reason, message: nil, schedule_id: nil, ids: [], detail: nil,
28
+ tasks: RunningTasks::EMPTY, worker_stopped: false, links: [])
21
29
  @session_id = session_id
22
30
  @reason = reason
23
31
  @schedule_id = schedule_id
24
32
  @ids = ids
33
+ @tasks = tasks
34
+ @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
35
+ @links = links
25
36
  super(message || refused_message(detail))
26
37
  end
27
38
 
39
+ def worker_stopped = !@stopped_worker.nil?
40
+
41
+ # This refusal, saying the op stopped +worker_id+'s worker (this
42
+ # session's by default) before the check under the lock refused.
43
+ def with_worker_stopped(worker_id = @session_id)
44
+ DeleteRefused.new(@session_id, @reason, tasks: @tasks, worker_stopped: worker_id, links: @links)
45
+ end
46
+
28
47
  private
29
48
 
30
49
  def refused_message(detail)
@@ -40,23 +59,32 @@ module Samagotchi
40
59
  "#{@ids.map { |id| id[0, 8] }.join(", ")}, moved here by the continue, can't go back to the previous link" \
41
60
  "#{": #{detail}" if detail}"
42
61
  when :chain_scheduled then "an enabled schedule runs on this chain#{cancel}"
62
+ when :plan_changed then "what this delete would do changed since it was shown; review the new plan and try again"
63
+ when :tasks_running
64
+ "#{RunningTasks.words(@session_id, @tasks, links: @links)}#{RunningTasks.worker_words(@session_id, @stopped_worker)}"
43
65
  else "session #{@session_id} can't be deleted now (#{@reason})"
44
66
  end
45
67
  end
46
68
  end
47
69
 
48
70
  # An archive that can't happen now: a turn runs in the session or in one
49
- # of its children (+busy_id+ names which), or it is a scratch session.
71
+ # of its children (+busy_id+ names which), it is a scratch session, or
72
+ # (:tasks_running) background tasks it or a delegate started still run
73
+ # (+tasks+, a RunningTasks::Listing).
50
74
  class ArchiveRefused < StandardError
51
- attr_reader :session_id, :reason, :busy_id
75
+ attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker
52
76
 
53
- def initialize(session_id, reason, busy_id: nil)
77
+ def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false)
54
78
  @session_id = session_id
55
79
  @reason = reason
56
80
  @busy_id = busy_id
81
+ @tasks = tasks
82
+ @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
57
83
  super(archive_refused_message)
58
84
  end
59
85
 
86
+ def worker_stopped = !@stopped_worker.nil?
87
+
60
88
  private
61
89
 
62
90
  def archive_refused_message
@@ -69,6 +97,7 @@ module Samagotchi
69
97
  when :offer_child then "its delegate #{@busy_id[0, 8]} waits for an answer to its step-limit question; answer it first"
70
98
  when :starting then "its worker is starting; try again in a moment"
71
99
  when :starting_child then "its delegate #{@busy_id[0, 8]}'s worker is starting; try again in a moment"
100
+ when :tasks_running then "#{RunningTasks.words(@session_id, @tasks)}#{RunningTasks.worker_words(@session_id, @stopped_worker)}"
72
101
  else "a turn is running; wait for it or cancel it first"
73
102
  end
74
103
  end
@@ -76,8 +105,14 @@ module Samagotchi
76
105
 
77
106
  # What one archive did: id: the session it was asked for; archived: the
78
107
  # ids (it and its delegates) now hidden for good; stopped: the live
79
- # workers stopped first; discarded: empty sessions its stopping worker deleted.
80
- ArchiveResult = Data.define(:id, :archived, :stopped, :discarded)
108
+ # workers stopped first; discarded: empty sessions its stopping worker
109
+ # deleted; tasks_stopped / tasks_not_stopped / tasks_ended: what a
110
+ # running_tasks: stop did (RunningTasks::RunningTask lists, empty
111
+ # otherwise).
112
+ ArchiveResult = Data.define(:id, :archived, :stopped, :discarded, :tasks_stopped, :tasks_not_stopped,
113
+ :tasks_ended) do
114
+ def initialize(id:, archived:, stopped:, discarded:, tasks_stopped: [], tasks_not_stopped: [], tasks_ended: []) = super
115
+ end
81
116
 
82
117
  # Every store with session-scoped state. Deletion, retention and failed
83
118
  # continuation cleanup all pass through this registry.
@@ -99,19 +134,29 @@ module Samagotchi
99
134
  # continue past the step limit, or it is a scratch session
100
135
  # @param except [Array<String>] descendants left alone with their own
101
136
  # subtrees (delegates a continue moves to the chain's new link)
102
- def archive_session(id_or_prefix, state_dir: nil, wait: 5, except: [])
137
+ # @param running_tasks [RunningTasks::Policy] the background tasks the
138
+ # tree started that still run: IGNORE (left running), REFUSE
139
+ # (ArchiveRefused :tasks_running before anything changes), or a stop
140
+ # (after the workers let go, or the wait ran out: their own waiters
141
+ # then record the stop from the flag on disk), before the marker
142
+ def archive_session(id_or_prefix, state_dir: nil, wait: 5, except: [], running_tasks: RunningTasks::Policy::IGNORE)
103
143
  sd = state_dir || Session.default_state_dir
104
144
  id = archive_target(id_or_prefix, sd)
105
145
  tree, owners = archivable!(id, sd, except: except)
146
+ RunningTasks.check!(tree, state_dir: sd, policy: running_tasks) do |listing|
147
+ ArchiveRefused.new(id, :tasks_running, tasks: listing)
148
+ end
106
149
  stopped = tree.select { |sid| owners[sid] }
150
+ # With +wait+, stop_session waits for the owner to let go.
107
151
  stopped.each { |sid| stop_session(sid, state_dir: sd, wait: wait) }
152
+ RunningTasks.stop!(RunningTasks.of(tree, state_dir: sd), policy: running_tasks) if running_tasks.stop?
108
153
  archived, discarded = tree.partition { |sid| ArchiveStore.archive(sid, state_dir: sd) }
109
154
  # A restart's reminders hand-off no successor took (the stop above
110
155
  # removes a live one's): archived sessions keep no reminders.
111
156
  archived.each { |sid| ReminderCarry.remove(Session.session_dir(sid, state_dir: sd)) }
112
157
  # D8: an archive ends the review (unarchiving doesn't restore it).
113
158
  Participants.end_sessions(archived, by: "archive", state_dir: sd)
114
- ArchiveResult.new(id: id, archived: archived, stopped: stopped, discarded: discarded)
159
+ ArchiveResult.new(id: id, archived: archived, stopped: stopped, discarded: discarded, **running_tasks.result_fields)
115
160
  end
116
161
 
117
162
  # The session and its descendants, with their owners, when they can be
@@ -193,8 +238,17 @@ module Samagotchi
193
238
  # (:continuing) while a continue of the session is in flight
194
239
  # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
195
240
  # head, and with the keywords :continuing and :delegate_unmovable
241
+ # @param still [#call, nil] the caller's own check, read again under
242
+ # the deleting lock (#remove_files; DeleteRefused :changed when it no
243
+ # longer holds): an empty session's discard. Not with the chain keywords.
244
+ # @param running_tasks [RunningTasks::Policy] the background tasks the
245
+ # deleted sessions started that still run: IGNORE (left running),
246
+ # REFUSE (DeleteRefused :tasks_running) or a stop, under the
247
+ # deleting lock (#remove_session_files). The result then also has
248
+ # tasks_stopped:, tasks_not_stopped: and tasks_ended:
196
249
  def delete_session(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, purge_runs: true,
197
- allow_scheduled: false, revive_previous: false, refuse_continuing: false)
250
+ allow_scheduled: false, revive_previous: false, refuse_continuing: false, expect: nil,
251
+ still: nil, running_tasks: RunningTasks::Policy::IGNORE)
198
252
  sd = state_dir || Session.default_state_dir
199
253
  given = id_or_prefix.to_s
200
254
  # Only a plain id: anything else could name a path outside the state dir.
@@ -209,10 +263,12 @@ module Samagotchi
209
263
  if revive_previous || refuse_continuing
210
264
  require_relative "../session_chain/delete"
211
265
  return SessionChain::Delete.link(id, state_dir: sd, stop: stop, wait: wait, revive_previous: revive_previous,
212
- refuse_continuing: refuse_continuing)
266
+ refuse_continuing: refuse_continuing, expect: expect,
267
+ running_tasks: running_tasks)
213
268
  end
214
269
 
215
- delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled)
270
+ delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled,
271
+ still: still, running_tasks: running_tasks)
216
272
  end
217
273
 
218
274
  # Delete every link of +id+'s chain with their delegates
@@ -223,7 +279,8 @@ module Samagotchi
223
279
  # @return [Hash] SessionChain::Delete.chain's
224
280
  # @raise [ArgumentError] unknown id (Session::AmbiguousId for a prefix of several)
225
281
  # @raise [DeleteRefused, OwnedByTUI] nothing was deleted
226
- def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT)
282
+ def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, expect: nil,
283
+ running_tasks: RunningTasks::Policy::IGNORE)
227
284
  sd = state_dir || Session.default_state_dir
228
285
  given = id_or_prefix.to_s
229
286
  raise Session::NotFound, given unless Session.valid_id?(given)
@@ -232,22 +289,35 @@ module Samagotchi
232
289
  raise Session::NotFound, given unless Session.exist?(id, state_dir: sd)
233
290
 
234
291
  require_relative "../session_chain/delete"
235
- SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait)
292
+ SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait, expect: expect, running_tasks: running_tasks)
236
293
  end
237
294
 
238
295
  # #delete_session's checks and removal for a full id that exists:
239
296
  # the schedule refusal, the one-turn run, the worker (stopped with
240
297
  # +stop+), then #remove_files. SessionChain::Delete's last step.
241
- # @return [Hash] {id:, removed:, stopped:}
242
- def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false)
298
+ # The running-tasks refusal comes before the worker is stopped; the
299
+ # check under the lock is the last word (+worker_stopped+ then).
300
+ # @return [Hash] {id:, removed:, stopped:, tasks_stopped:, tasks_not_stopped:, tasks_ended:}
301
+ def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false,
302
+ still: nil, running_tasks: RunningTasks::Policy::IGNORE)
243
303
  sd = state_dir
244
304
  path = Session.session_file(id, state_dir: sd)
245
305
  dir = Session.session_dir(id, state_dir: sd)
246
306
  refuse_scheduled!(id, sd) unless allow_scheduled
307
+ RunningTasks.check!([id], state_dir: sd, policy: running_tasks) do |listing|
308
+ DeleteRefused.new(id, :tasks_running, tasks: listing)
309
+ end
247
310
 
248
311
  held = release_for_delete!(id, state_dir: sd, stop: stop, wait: wait)
249
- removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs)
250
- { id: id, removed: removed, stopped: held }
312
+ begin
313
+ removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs, still: still,
314
+ running_tasks: running_tasks)
315
+ rescue DeleteRefused => e
316
+ raise e unless held && e.reason == :tasks_running
317
+
318
+ raise e.with_worker_stopped
319
+ end
320
+ { id: id, removed: removed, stopped: held, **running_tasks.result_fields }
251
321
  end
252
322
 
253
323
  # +id+ free for a delete: a one-turn run refuses, a worker that owns it
@@ -276,12 +346,15 @@ module Samagotchi
276
346
  # @return [Array<Hash>] #delete_session's result for each
277
347
  # @raise [DeleteRefused, OwnedByTUI, Session::NotFound] the first
278
348
  # refusal; the ids before it are deleted
279
- def delete_ids(ids, state_dir: nil, stop: false, wait: STOP_WAIT)
349
+ # @param running_tasks [RunningTasks::Policy] for every id (a stop's
350
+ # tally is the batch's: each result's task fields count so far).
351
+ # Schedules#prune keeps IGNORE.
352
+ def delete_ids(ids, state_dir: nil, stop: false, wait: STOP_WAIT, running_tasks: RunningTasks::Policy::IGNORE)
280
353
  sd = state_dir || Session.default_state_dir
281
354
  results = []
282
355
  # Not a map: the ids deleted before a refusal must reach the ensure's purge.
283
356
  ids.each do |id| # rubocop:disable Style/MapIntoArray
284
- results << delete_session(id, state_dir: sd, stop: stop, wait: wait, purge_runs: false)
357
+ results << delete_session(id, state_dir: sd, stop: stop, wait: wait, purge_runs: false, running_tasks: running_tasks)
285
358
  end
286
359
  results
287
360
  ensure
@@ -312,12 +385,15 @@ module Samagotchi
312
385
  # @raise [DeleteRefused] see #remove_session_files
313
386
  # @param locked [Boolean] the caller holds +id+'s owner lock (kind
314
387
  # deleting) already: SessionChain::Delete, across its undo
315
- def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil, locked: false)
388
+ # @param running_tasks [RunningTasks::Policy] see #remove_session_files
389
+ def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil, locked: false,
390
+ running_tasks: RunningTasks::Policy::IGNORE)
316
391
  removed = []
317
392
  SESSION_STATE_STORES.each do |store|
318
393
  case store
319
394
  when :session_files
320
- removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still, locked: locked))
395
+ removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still, locked: locked,
396
+ running_tasks: running_tasks))
321
397
  when :plugin_session_state
322
398
  PluginSessionState.remove(id)
323
399
  when :context_sources
@@ -354,15 +430,31 @@ module Samagotchi
354
430
  # The lock file goes with the directory; a worker starting after that
355
431
  # makes a new one, and finds no session (Session.load). The delete and
356
432
  # the retention sweep and failed-continue cleanup use #remove_files.
433
+ # The background tasks +id+ started are read again here, on the final
434
+ # file, under the lock (+running_tasks+): REFUSE refuses on any, a stop
435
+ # stops them (RunningTasks.stop!, up to about 4 s with the lock held:
436
+ # meanwhile a send, a schedule or a resume is refused as deleting).
357
437
  # @return [Array<String>] the paths removed
358
438
  # @raise [DeleteRefused] a worker took the lock, or a start was
359
- # claimed, after the caller's check, or +still+ no longer holds
360
- def remove_session_files(id, path, dir, state_dir:, still: nil, locked: false)
439
+ # claimed, after the caller's check, or +still+ no longer holds, or
440
+ # (:tasks_running, REFUSE) a task started since the op's check.
441
+ # SessionChain::Delete lists its whole batch under its locks first
442
+ # and passes RunningTasks.after_check (no re-check here, so no id is
443
+ # refused after another of the batch went).
444
+ def remove_session_files(id, path, dir, state_dir:, still: nil, locked: false,
445
+ running_tasks: RunningTasks::Policy::IGNORE)
361
446
  lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
362
447
  raise DeleteRefused.new(id, :worker_running) if !locked && Dir.exist?(dir) && lock.nil?
363
448
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
364
449
  raise DeleteRefused.new(id, :changed) if still && !still.call
365
450
 
451
+ unless running_tasks.ignore?
452
+ listing = RunningTasks.of([id], state_dir: state_dir)
453
+ raise DeleteRefused.new(id, :tasks_running, tasks: listing) if running_tasks.refuse? && !listing.empty?
454
+
455
+ RunningTasks.stop!(listing, policy: running_tasks) if running_tasks.stop?
456
+ end
457
+
366
458
  removed = []
367
459
  if File.exist?(path)
368
460
  FileUtils.rm_f(path)
@@ -0,0 +1,334 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../log"
5
+ require_relative "../process_group"
6
+ require_relative "../session"
7
+ require_relative "../task_files"
8
+ require_relative "../task_transcript"
9
+ require_relative "../tools/task_record"
10
+
11
+ module Samagotchi
12
+ class SessionManager
13
+ # The background tasks a session started that still run (its
14
+ # task_create tasks and the executes it handed over), and the one rule a
15
+ # delete, an archive and restart's fallback apply to them: with doubt,
16
+ # ask, and never kill. Read from disk only (the session file, then each
17
+ # task.json under its working directory), so an old worker needs
18
+ # nothing. Stopping loads Tools::TaskRuntime at call time.
19
+ # See docs/internals/background-tasks.md.
20
+ module RunningTasks
21
+ # One task a session started: +root+ is the session's working
22
+ # directory (where tmp/tasks is), nil when rebuilt from a 409 body.
23
+ RunningTask = Data.define(:session_id, :id, :command, :root) do
24
+ def initialize(session_id:, id:, command: nil, root: nil) = super
25
+
26
+ # The wire form (no root: chi web's folders are its own business).
27
+ def to_wire = { "session_id" => session_id, "id" => id, "command" => command }
28
+
29
+ def self.from_wire(data)
30
+ data = {} unless data.is_a?(Hash)
31
+ new(session_id: data["session_id"].to_s, id: data["id"].to_s, command: data["command"])
32
+ end
33
+ end
34
+
35
+ # What #of found: +running+ (verified: the pid still leads the group
36
+ # chi started, at the start time it read then), +unverified+ (a pid
37
+ # that leads a group, with no start time to compare: a record from
38
+ # before 2026-10-09, or a ps that read nothing now) and +unreadable+
39
+ # (a task.json that can't be read). Each is an Array<RunningTask>.
40
+ Listing = Data.define(:running, :unverified, :unreadable) do
41
+ def initialize(running: [], unverified: [], unreadable: []) = super
42
+
43
+ def empty? = running.empty? && unverified.empty? && unreadable.empty?
44
+ def all = running + unverified + unreadable
45
+ def size = all.size
46
+
47
+ def to_wire = to_h.transform_keys(&:to_s).transform_values { |tasks| tasks.map(&:to_wire) }
48
+
49
+ def self.from_wire(data)
50
+ data = {} unless data.is_a?(Hash)
51
+ new(**members.to_h { |key| [key, Array(data[key.to_s]).map { |task| RunningTask.from_wire(task) }] })
52
+ end
53
+ end
54
+
55
+ EMPTY = Listing.new
56
+
57
+ # What one op's stops came to, one outcome per task (the first one
58
+ # wins: a stop thread that answers after the deadline doesn't change
59
+ # an +unconfirmed+): :stopped (the record now says stopped), :ended
60
+ # (it had already finished, or its pid isn't chi's any more),
61
+ # :failed (an error), :unconfirmed (the wait ran out), :unverified
62
+ # and :unreadable (never signalled). All but :stopped and :ended are
63
+ # "not stopped".
64
+ class Tally
65
+ Outcome = Data.define(:task, :outcome, :error)
66
+ NOT_STOPPED = %i[failed unconfirmed unverified unreadable].freeze
67
+
68
+ def initialize
69
+ @lock = Mutex.new
70
+ @outcomes = {}
71
+ end
72
+
73
+ def add(task, outcome, error = nil)
74
+ @lock.synchronize { @outcomes[[task.session_id, task.id]] ||= Outcome.new(task: task, outcome: outcome, error: error) }
75
+ end
76
+
77
+ def outcomes = @lock.synchronize { @outcomes.values }
78
+ def stopped = pick(:stopped)
79
+ def ended = pick(:ended)
80
+ def not_stopped = outcomes.select { |o| NOT_STOPPED.include?(o.outcome) }.map(&:task)
81
+
82
+ private
83
+
84
+ def pick(kind) = outcomes.select { |o| o.outcome == kind }.map(&:task)
85
+ end
86
+
87
+ # How an op treats running tasks: :ignore (today's: they keep
88
+ # running), :refuse (DeleteRefused/ArchiveRefused :tasks_running) or
89
+ # :stop (stopped by +by+, "user", "retention" or "scratch", their
90
+ # outcomes in +tally+).
91
+ Policy = Data.define(:mode, :by, :tally) do
92
+ def self.stop(by:) = new(mode: :stop, by: by.to_s, tally: Tally.new)
93
+
94
+ def ignore? = mode == :ignore
95
+ def refuse? = mode == :refuse
96
+ def stop? = mode == :stop
97
+
98
+ # The result keys a delete adds for a stop: the tasks the op
99
+ # stopped, did not stop and found ended ({} unless +stop?+, so a
100
+ # delete's result is today's).
101
+ def result_fields
102
+ return {} unless tally
103
+
104
+ { tasks_stopped: tally.stopped, tasks_not_stopped: tally.not_stopped, tasks_ended: tally.ended }
105
+ end
106
+ end
107
+ Policy::IGNORE = Policy.new(mode: :ignore, by: nil, tally: nil)
108
+ Policy::REFUSE = Policy.new(mode: :refuse, by: nil, tally: nil)
109
+
110
+ # The words restart's hold and the refusals lead with.
111
+ LEAD = "background tasks it started are still running"
112
+ # How many tasks the words name before "+N more" (running_tasks.js NAMED_MAX).
113
+ MAX_NAMED = 3
114
+ # A task's command is cut to this many characters (running_tasks.js cutCommand).
115
+ COMMAND_CHARS = 42
116
+ # The log tag of a session file or task.json the check can't read.
117
+ CHECK_FAILED = "session_task_check_failed"
118
+
119
+ module_function
120
+
121
+ # Whose worker a refusal says was stopped: +worker_stopped+ is false,
122
+ # true (+session_id+'s) or a session id. nil for none.
123
+ def stopped_worker(session_id, worker_stopped)
124
+ return nil if worker_stopped.nil? || worker_stopped == false
125
+
126
+ worker_stopped == true ? session_id.to_s : worker_stopped.to_s
127
+ end
128
+
129
+ # "; its worker was stopped" (+stopped_worker+ is +session_id+),
130
+ # "; 9d0e1f2a's worker was stopped" (another), "" (none).
131
+ def worker_words(session_id, stopped_worker)
132
+ return "" unless stopped_worker
133
+ return "; its worker was stopped" if stopped_worker == session_id.to_s
134
+
135
+ "; #{stopped_worker[0, 8]}'s worker was stopped"
136
+ end
137
+
138
+ # The policy a batch's removals get once the batch was listed under its
139
+ # locks (SessionChain::Delete): a REFUSE already checked does no
140
+ # per-id re-check; IGNORE and a stop are unchanged.
141
+ def after_check(policy) = policy.refuse? ? Policy::IGNORE : policy
142
+
143
+ # REFUSE's one listing of a whole batch under its locks: the batch's
144
+ # DeleteRefused :tasks_running (+refusal+ builds it) before anything of
145
+ # it goes. Nothing for another policy.
146
+ def refuse_batch!(ids, state_dir:, policy:, &refusal)
147
+ return unless policy.refuse?
148
+
149
+ listing = of(ids, state_dir: state_dir)
150
+ raise yield(listing) unless listing.empty?
151
+ end
152
+
153
+ # The tasks the sessions +ids+ started that may still run; never
154
+ # writes, never loads TaskRuntime. A session with no file (a folder
155
+ # left alone) is skipped, one that can't be read too (with a warn).
156
+ # @return [Listing]
157
+ def of(ids, state_dir:)
158
+ found = { running: [], unverified: [], unreadable: [] }
159
+ Array(ids).each do |sid|
160
+ session = readable_session(sid, state_dir)
161
+ next unless session
162
+
163
+ root = session.working_directory.to_s
164
+ next if root.empty?
165
+
166
+ TaskTranscript.created_ids_in(session.messages).each do |id|
167
+ kind, task = classify(sid, id, root)
168
+ found[kind] << task if kind
169
+ end
170
+ end
171
+ Listing.new(**found)
172
+ end
173
+
174
+ # +listing+ of +ids+ when +policy+ refuses on it, raised as the op's
175
+ # refusal (+refusal+ builds it from the listing); else the listing
176
+ # (EMPTY unless the policy refuses: a stop lists again where it stops).
177
+ # @return [Listing]
178
+ def check!(ids, state_dir:, policy:, &refusal)
179
+ return EMPTY unless policy.refuse?
180
+
181
+ listing = of(ids, state_dir: state_dir)
182
+ raise yield(listing) unless listing.empty?
183
+
184
+ listing
185
+ end
186
+
187
+ # Stops +listing+'s verified tasks, each on its own thread under its
188
+ # session's folder (TaskFiles.with_root), all joined against one
189
+ # deadline; the unverified and unreadable ones are never signalled.
190
+ # Every outcome goes into +policy.tally+. Doesn't log: the caller does,
191
+ # with no command text (a command line can carry tokens).
192
+ # @return [Tally]
193
+ def stop!(listing, policy:)
194
+ tally = policy.tally || Tally.new
195
+ listing.unverified.each { |task| tally.add(task, :unverified) }
196
+ listing.unreadable.each { |task| tally.add(task, :unreadable) }
197
+ return tally if listing.running.empty?
198
+
199
+ require_relative "../tools/task_runtime"
200
+ runtime = Tools::TaskRuntime
201
+ deadline = monotonic + runtime::STOP_GRACE_SEC + ProcessGroup::KILL_WAIT_SEC + 0.5
202
+ threads = listing.running.map { |task| [task, stop_thread(task, policy.by, tally)] }
203
+ threads.each do |task, thread|
204
+ tally.add(task, :unconfirmed) unless thread.join([deadline - monotonic, 0].max)
205
+ end
206
+ tally
207
+ end
208
+
209
+ # One task's stop, its outcome into +tally+.
210
+ def stop_thread(task, by, tally)
211
+ Thread.new do
212
+ Thread.current.report_on_exception = false
213
+ record, error = TaskFiles.with_root(task.root) { Tools::TaskRuntime.stop_task(task.id, by: by) }
214
+ if error
215
+ tally.add(task, :failed, error)
216
+ else
217
+ tally.add(task, record&.status == "stopped" ? :stopped : :ended)
218
+ end
219
+ rescue StandardError => e
220
+ tally.add(task, :failed, "#{e.class}: #{e.message}")
221
+ end
222
+ end
223
+
224
+ # "background tasks it started are still running: npm run dev, rspec",
225
+ # and for a task of another session in +tasks+ "its delegate
226
+ # 9d0e1f2a's background tasks are still running: …" (or "link
227
+ # 9d0e1f2a's" for one of +links+, a chain delete's other links).
228
+ # @param tasks [Listing, Array<RunningTask>]
229
+ def words(session_id, tasks, links: [])
230
+ named = tasks.is_a?(Listing) ? named_tasks(tasks) : tasks.map { |task| [task, command_name(task)] }
231
+ named.group_by { |task, _| task.session_id }.map do |sid, group|
232
+ names = cut(group.map(&:last))
233
+ if sid == session_id.to_s then "#{LEAD}: #{names}"
234
+ elsif links.include?(sid) then "link #{sid[0, 8]}'s background tasks are still running: #{names}"
235
+ else "its delegate #{sid[0, 8]}'s background tasks are still running: #{names}"
236
+ end
237
+ end.join("; ")
238
+ end
239
+
240
+ # The --stop-tasks hint after a refusal: the short form for a CLI
241
+ # line (+via+ nil), the full command (ChiInvocation) for a terminal's.
242
+ def hint(via, op, id)
243
+ return "--stop-tasks stops them first" unless via
244
+
245
+ "#{via.command("sessions #{op} --stop-tasks #{id}")} stops them first"
246
+ end
247
+
248
+ # What a delete/archive line adds for a stop: "stopped 2 background
249
+ # tasks", "1 not stopped: task 3f9a2c1d (may still be running)";
250
+ # empty when nothing was stopped or left.
251
+ # @return [Array<String>]
252
+ def stop_words(result)
253
+ stopped = Array(result[:tasks_stopped])
254
+ left = Array(result[:tasks_not_stopped])
255
+ parts = []
256
+ parts << "stopped #{stopped.size} background task#{"s" unless stopped.size == 1}" unless stopped.empty?
257
+ parts << "#{left.size} not stopped: #{cut(left.map { |task| command_name(task) })}" unless left.empty?
258
+ parts
259
+ end
260
+
261
+ # Each task of +listing+ with the name the words give it.
262
+ def named_tasks(listing)
263
+ listing.running.map { |task| [task, command_name(task)] } +
264
+ listing.unverified.map { |task| [task, "task #{short_task(task.id)} (may still be running)"] } +
265
+ listing.unreadable.map { |task| [task, "task #{short_task(task.id)} (record unreadable)"] }
266
+ end
267
+
268
+ def command_name(task)
269
+ command = task.command.to_s.strip.gsub(/\s+/, " ")
270
+ return "task #{short_task(task.id)}" if command.empty?
271
+
272
+ command.length > COMMAND_CHARS ? "#{command[0, COMMAND_CHARS]}…" : command
273
+ end
274
+
275
+ # A task id's hex part (20261027123456-3f9a2c1d → 3f9a2c1d).
276
+ def short_task(id) = id.to_s.split("-").last.to_s[0, 8]
277
+
278
+ def cut(names)
279
+ return names.join(", ") if names.size <= MAX_NAMED
280
+
281
+ "#{names.first(MAX_NAMED).join(", ")} +#{names.size - MAX_NAMED} more"
282
+ end
283
+
284
+ def readable_session(sid, state_dir)
285
+ Session.load(sid, state_dir: state_dir)
286
+ rescue Session::NotFound
287
+ nil
288
+ rescue ArgumentError, SystemCallError => e
289
+ Log.warn(:worker, CHECK_FAILED, sid: sid, error: e.class.name, msg: e.message.to_s[0, 200])
290
+ nil
291
+ end
292
+
293
+ # [kind, RunningTask] for a task that may still run, else nil.
294
+ def classify(sid, id, root)
295
+ return nil unless TaskFiles::TASK_ID.match?(id)
296
+
297
+ path = File.join(root, TaskFiles::TASKS_DIR, id, TaskFiles::METADATA_FILENAME)
298
+ return nil unless File.file?(path)
299
+
300
+ record = Tools::TaskRecord.from_file(JSON.parse(File.read(path)))
301
+ raise JSON::ParserError, "not a task record" unless record
302
+ return nil unless record.running?
303
+
304
+ kind = liveness(record)
305
+ kind && [kind, RunningTask.new(session_id: sid, id: id, command: record.command.to_s, root: root)]
306
+ rescue JSON::ParserError, SystemCallError => e
307
+ Log.warn(:worker, CHECK_FAILED, sid: sid, task_id: id, error: e.class.name, msg: e.message.to_s[0, 200])
308
+ [:unreadable, RunningTask.new(session_id: sid, id: id, root: root)]
309
+ end
310
+
311
+ # :running for a pid that leads the group chi started, at the start
312
+ # time read then; :unverified for one that leads a group with no
313
+ # start time to compare (none recorded, or none readable now); nil
314
+ # for a dead pid or one another process reuses.
315
+ def liveness(record)
316
+ pid = record.pid
317
+ return nil unless ProcessGroup.leader?(pid)
318
+
319
+ started = record.pid_started
320
+ return :unverified if started.nil?
321
+
322
+ now = ProcessGroup.start_time(pid)
323
+ return :unverified if now.nil?
324
+
325
+ now == started ? :running : nil
326
+ end
327
+
328
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
329
+
330
+ private_class_method :stop_thread, :named_tasks, :command_name, :short_task, :cut, :readable_session,
331
+ :classify, :liveness, :monotonic
332
+ end
333
+ end
334
+ end
@@ -195,8 +195,8 @@ module Samagotchi
195
195
  # landing between the check and the resume is a small window, left as
196
196
  # is. An archived parent with a later link wakes that link (one hop:
197
197
  # ChildReports reads its predecessor's rings, no further).
198
- # @return [Symbol] :woken, or why not (:gone, :stopped, :archived,
199
- # :scratch, :owned, :starting)
198
+ # @return [Symbol] :woken, or why not (:gone, :deleting: a deleter
199
+ # holds its lock, :stopped, :archived, :scratch, :owned, :starting)
200
200
  def wake_for_report(session_id, state_dir: nil)
201
201
  sd = state_dir || Session.default_state_dir
202
202
  outcome = SessionInbox.wake(:ring, session_id, state_dir: sd, owner: ->(id) { session_owner(id, state_dir: sd) }).wake
@@ -325,7 +325,7 @@ module Samagotchi
325
325
  next false
326
326
  rescue Samagotchi::SessionManager::RestartRefused => e
327
327
  @stdout.flush
328
- @stderr.puts %i[not_running unsupported fallback_held stopped failed].include?(e.reason) ? e.message : "session #{id}: #{e.message}"
328
+ @stderr.puts %i[not_running unsupported fallback_held stopped stop_marked deleting failed].include?(e.reason) ? e.message : "session #{id}: #{e.message}"
329
329
  next false
330
330
  rescue ArgumentError => e
331
331
  @stdout.flush