samagotchi 0.177.1 → 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 (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +27 -1
  3. data/docs/cli.md +27 -5
  4. data/docs/guardrails.md +1 -1
  5. data/docs/internals/background-tasks.md +23 -2
  6. data/docs/internals/bridge.md +17 -6
  7. data/docs/internals/remote-sessions.md +6 -1
  8. data/docs/internals/session-lifecycle.md +17 -8
  9. data/docs/internals/web-frontend.md +7 -3
  10. data/docs/internals/working-set.md +31 -5
  11. data/docs/scheduling.md +8 -1
  12. data/docs/sessions.md +9 -5
  13. data/lib/samagotchi/bridge/card_store.rb +2 -19
  14. data/lib/samagotchi/bridge.rb +38 -6
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/compat.rb +0 -7
  17. data/lib/samagotchi/engine/events.rb +43 -0
  18. data/lib/samagotchi/engine.rb +9 -3
  19. data/lib/samagotchi/event_fanout.rb +56 -0
  20. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  21. data/lib/samagotchi/schedules.rb +9 -4
  22. data/lib/samagotchi/session_access/contract.rb +4 -0
  23. data/lib/samagotchi/session_access/local.rb +16 -4
  24. data/lib/samagotchi/session_access/remote.rb +42 -9
  25. data/lib/samagotchi/session_archive_command.rb +38 -10
  26. data/lib/samagotchi/session_chain/delete.rb +75 -25
  27. data/lib/samagotchi/session_delete_command.rb +33 -10
  28. data/lib/samagotchi/session_lifecycle/allowed.rb +12 -9
  29. data/lib/samagotchi/session_manager/lifecycle.rb +12 -26
  30. data/lib/samagotchi/session_manager/removal.rb +109 -25
  31. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  32. data/lib/samagotchi/sessions_command.rb +1 -1
  33. data/lib/samagotchi/task_files.rb +37 -4
  34. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  35. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  36. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  37. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  38. data/lib/samagotchi/version.rb +1 -1
  39. data/lib/samagotchi/web/app.rb +5 -1
  40. data/lib/samagotchi/web/public/data.js +19 -7
  41. data/lib/samagotchi/web/public/delete_sheet.js +26 -7
  42. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  43. data/lib/samagotchi/web/public/session_actions.js +57 -8
  44. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  45. data/lib/samagotchi/web/public/working_set.js +3 -28
  46. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  47. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  48. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  49. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  50. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  51. data/lib/samagotchi/web/session_control.rb +65 -16
  52. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  53. data/lib/samagotchi/worker_link.rb +9 -1
  54. data/lib/samagotchi/working_set.rb +26 -0
  55. data/lib/samagotchi/working_set_command.rb +9 -6
  56. metadata +4 -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
@@ -14,18 +15,35 @@ module Samagotchi
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
17
  # chain delete would take: +schedule_id+), :plan_changed (the plan no
17
- # longer matches the digest the caller confirmed).
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).
18
24
  class DeleteRefused < StandardError
19
- attr_reader :session_id, :reason, :schedule_id, :ids
25
+ attr_reader :session_id, :reason, :schedule_id, :ids, :tasks, :stopped_worker, :links
20
26
 
21
- 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: [])
22
29
  @session_id = session_id
23
30
  @reason = reason
24
31
  @schedule_id = schedule_id
25
32
  @ids = ids
33
+ @tasks = tasks
34
+ @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
35
+ @links = links
26
36
  super(message || refused_message(detail))
27
37
  end
28
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
+
29
47
  private
30
48
 
31
49
  def refused_message(detail)
@@ -42,23 +60,31 @@ module Samagotchi
42
60
  "#{": #{detail}" if detail}"
43
61
  when :chain_scheduled then "an enabled schedule runs on this chain#{cancel}"
44
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)}"
45
65
  else "session #{@session_id} can't be deleted now (#{@reason})"
46
66
  end
47
67
  end
48
68
  end
49
69
 
50
70
  # An archive that can't happen now: a turn runs in the session or in one
51
- # 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).
52
74
  class ArchiveRefused < StandardError
53
- attr_reader :session_id, :reason, :busy_id
75
+ attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker
54
76
 
55
- def initialize(session_id, reason, busy_id: nil)
77
+ def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false)
56
78
  @session_id = session_id
57
79
  @reason = reason
58
80
  @busy_id = busy_id
81
+ @tasks = tasks
82
+ @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
59
83
  super(archive_refused_message)
60
84
  end
61
85
 
86
+ def worker_stopped = !@stopped_worker.nil?
87
+
62
88
  private
63
89
 
64
90
  def archive_refused_message
@@ -71,6 +97,7 @@ module Samagotchi
71
97
  when :offer_child then "its delegate #{@busy_id[0, 8]} waits for an answer to its step-limit question; answer it first"
72
98
  when :starting then "its worker is starting; try again in a moment"
73
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)}"
74
101
  else "a turn is running; wait for it or cancel it first"
75
102
  end
76
103
  end
@@ -78,8 +105,14 @@ module Samagotchi
78
105
 
79
106
  # What one archive did: id: the session it was asked for; archived: the
80
107
  # ids (it and its delegates) now hidden for good; stopped: the live
81
- # workers stopped first; discarded: empty sessions its stopping worker deleted.
82
- 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
83
116
 
84
117
  # Every store with session-scoped state. Deletion, retention and failed
85
118
  # continuation cleanup all pass through this registry.
@@ -101,19 +134,29 @@ module Samagotchi
101
134
  # continue past the step limit, or it is a scratch session
102
135
  # @param except [Array<String>] descendants left alone with their own
103
136
  # subtrees (delegates a continue moves to the chain's new link)
104
- 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)
105
143
  sd = state_dir || Session.default_state_dir
106
144
  id = archive_target(id_or_prefix, sd)
107
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
108
149
  stopped = tree.select { |sid| owners[sid] }
150
+ # With +wait+, stop_session waits for the owner to let go.
109
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?
110
153
  archived, discarded = tree.partition { |sid| ArchiveStore.archive(sid, state_dir: sd) }
111
154
  # A restart's reminders hand-off no successor took (the stop above
112
155
  # removes a live one's): archived sessions keep no reminders.
113
156
  archived.each { |sid| ReminderCarry.remove(Session.session_dir(sid, state_dir: sd)) }
114
157
  # D8: an archive ends the review (unarchiving doesn't restore it).
115
158
  Participants.end_sessions(archived, by: "archive", state_dir: sd)
116
- 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)
117
160
  end
118
161
 
119
162
  # The session and its descendants, with their owners, when they can be
@@ -198,9 +241,14 @@ module Samagotchi
198
241
  # @param still [#call, nil] the caller's own check, read again under
199
242
  # the deleting lock (#remove_files; DeleteRefused :changed when it no
200
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:
201
249
  def delete_session(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, purge_runs: true,
202
250
  allow_scheduled: false, revive_previous: false, refuse_continuing: false, expect: nil,
203
- still: nil)
251
+ still: nil, running_tasks: RunningTasks::Policy::IGNORE)
204
252
  sd = state_dir || Session.default_state_dir
205
253
  given = id_or_prefix.to_s
206
254
  # Only a plain id: anything else could name a path outside the state dir.
@@ -215,11 +263,12 @@ module Samagotchi
215
263
  if revive_previous || refuse_continuing
216
264
  require_relative "../session_chain/delete"
217
265
  return SessionChain::Delete.link(id, state_dir: sd, stop: stop, wait: wait, revive_previous: revive_previous,
218
- refuse_continuing: refuse_continuing, expect: expect)
266
+ refuse_continuing: refuse_continuing, expect: expect,
267
+ running_tasks: running_tasks)
219
268
  end
220
269
 
221
270
  delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled,
222
- still: still)
271
+ still: still, running_tasks: running_tasks)
223
272
  end
224
273
 
225
274
  # Delete every link of +id+'s chain with their delegates
@@ -230,7 +279,8 @@ module Samagotchi
230
279
  # @return [Hash] SessionChain::Delete.chain's
231
280
  # @raise [ArgumentError] unknown id (Session::AmbiguousId for a prefix of several)
232
281
  # @raise [DeleteRefused, OwnedByTUI] nothing was deleted
233
- def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, expect: nil)
282
+ def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, expect: nil,
283
+ running_tasks: RunningTasks::Policy::IGNORE)
234
284
  sd = state_dir || Session.default_state_dir
235
285
  given = id_or_prefix.to_s
236
286
  raise Session::NotFound, given unless Session.valid_id?(given)
@@ -239,23 +289,35 @@ module Samagotchi
239
289
  raise Session::NotFound, given unless Session.exist?(id, state_dir: sd)
240
290
 
241
291
  require_relative "../session_chain/delete"
242
- SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait, expect: expect)
292
+ SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait, expect: expect, running_tasks: running_tasks)
243
293
  end
244
294
 
245
295
  # #delete_session's checks and removal for a full id that exists:
246
296
  # the schedule refusal, the one-turn run, the worker (stopped with
247
297
  # +stop+), then #remove_files. SessionChain::Delete's last step.
248
- # @return [Hash] {id:, removed:, stopped:}
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:}
249
301
  def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false,
250
- still: nil)
302
+ still: nil, running_tasks: RunningTasks::Policy::IGNORE)
251
303
  sd = state_dir
252
304
  path = Session.session_file(id, state_dir: sd)
253
305
  dir = Session.session_dir(id, state_dir: sd)
254
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
255
310
 
256
311
  held = release_for_delete!(id, state_dir: sd, stop: stop, wait: wait)
257
- removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs, still: still)
258
- { 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 }
259
321
  end
260
322
 
261
323
  # +id+ free for a delete: a one-turn run refuses, a worker that owns it
@@ -284,12 +346,15 @@ module Samagotchi
284
346
  # @return [Array<Hash>] #delete_session's result for each
285
347
  # @raise [DeleteRefused, OwnedByTUI, Session::NotFound] the first
286
348
  # refusal; the ids before it are deleted
287
- 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)
288
353
  sd = state_dir || Session.default_state_dir
289
354
  results = []
290
355
  # Not a map: the ids deleted before a refusal must reach the ensure's purge.
291
356
  ids.each do |id| # rubocop:disable Style/MapIntoArray
292
- 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)
293
358
  end
294
359
  results
295
360
  ensure
@@ -320,12 +385,15 @@ module Samagotchi
320
385
  # @raise [DeleteRefused] see #remove_session_files
321
386
  # @param locked [Boolean] the caller holds +id+'s owner lock (kind
322
387
  # deleting) already: SessionChain::Delete, across its undo
323
- 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)
324
391
  removed = []
325
392
  SESSION_STATE_STORES.each do |store|
326
393
  case store
327
394
  when :session_files
328
- 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))
329
397
  when :plugin_session_state
330
398
  PluginSessionState.remove(id)
331
399
  when :context_sources
@@ -362,15 +430,31 @@ module Samagotchi
362
430
  # The lock file goes with the directory; a worker starting after that
363
431
  # makes a new one, and finds no session (Session.load). The delete and
364
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).
365
437
  # @return [Array<String>] the paths removed
366
438
  # @raise [DeleteRefused] a worker took the lock, or a start was
367
- # claimed, after the caller's check, or +still+ no longer holds
368
- 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)
369
446
  lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
370
447
  raise DeleteRefused.new(id, :worker_running) if !locked && Dir.exist?(dir) && lock.nil?
371
448
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
372
449
  raise DeleteRefused.new(id, :changed) if still && !still.call
373
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
+
374
458
  removed = []
375
459
  if File.exist?(path)
376
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
@@ -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 stop_marked 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