kosa8 0.4.0 → 0.5.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.
@@ -0,0 +1,276 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The thread-pool engine behind Cloud#fork_map and Kosa8::RL::Run#map: hand
4
+ # out forks of a base sandbox, run work in them, retry what can pass, and
5
+ # never leave a child behind (Ctrl-C included).
6
+ module Kosa8
7
+ # One item of a fork_map: the +item+, what the block returned (+value+) or
8
+ # raised (+error+), its +failure_class+ ("ok" on success), how many
9
+ # +attempts+ it took, the +sandbox_id+ of its last fork and +ms+.
10
+ ForkResult = Struct.new(:item, :value, :error, :failure_class, :attempts, :sandbox_id, :ms, keyword_init: true) do
11
+ def ok?
12
+ error.nil?
13
+ end
14
+ end
15
+
16
+ # The map was stopped before this item ran.
17
+ class CancelledError < Error
18
+ def initialize(message = "cancelled before it ran")
19
+ super(message, body: { "failure_class" => "error", "retryable" => false })
20
+ end
21
+ end
22
+
23
+ # An item ran past the map's timeout_s; its sandbox was deleted.
24
+ class ItemTimeoutError < TimeoutError
25
+ def initialize(timeout_s)
26
+ super("gave up after #{timeout_s} s; its sandbox was deleted",
27
+ body: { "failure_class" => "timeout", "retryable" => false }, code: "timeout")
28
+ end
29
+ end
30
+
31
+ module ForkMap
32
+ # Children forked ahead of the workers in one call, at most.
33
+ PREFORK_MAX = 100
34
+
35
+ # A failed[] entry of a batch or fork answer as an exception.
36
+ def self.failure_from_entry(entry)
37
+ e = entry.is_a?(Hash) ? entry : {}
38
+ ApiError.new((e["message"] || e["code"] || "not created").to_s, code: e["code"],
39
+ body: e.merge("failure_class" => e["failure_class"] || "infra",
40
+ "retryable" => e.key?("retryable") ? e["retryable"] == true : true))
41
+ end
42
+
43
+ # Forks of +base+ (or sandboxes from make.call(arg)) for workers to take.
44
+ # Every child it made and has not released is tracked, so #close deletes
45
+ # them all, even mid-call.
46
+ class ChildPool
47
+ attr_reader :closed
48
+
49
+ def initialize(cloud, base: nil, make: nil, labels: nil, run_id: nil, lease_s: nil)
50
+ raise ArgumentError, "give a base sandbox to fork, or make: to create each sandbox" if base.nil? == make.nil?
51
+
52
+ @cloud = cloud
53
+ @base = base
54
+ @make = make
55
+ @labels = labels
56
+ @run_id = run_id
57
+ @lease_s = lease_s
58
+ @ready = []
59
+ @live = {}
60
+ @lock = Mutex.new
61
+ @closed = false
62
+ end
63
+
64
+ def prefork(n)
65
+ return unless @make.nil?
66
+
67
+ left = n
68
+ while left.positive? && !@closed
69
+ k = [left, PREFORK_MAX].min
70
+ begin
71
+ kids = fork(k, true)
72
+ rescue StandardError
73
+ return # each worker forks its own and sees the error
74
+ end
75
+ @lock.synchronize { @ready.concat(kids) }
76
+ left -= k
77
+ end
78
+ end
79
+
80
+ def take(arg = nil)
81
+ raise CancelledError if @closed
82
+
83
+ unless @make.nil?
84
+ child = @make.call(arg)
85
+ adopt([child])
86
+ return child
87
+ end
88
+ child = @lock.synchronize { @ready.shift }
89
+ child || fork(1, nil)[0]
90
+ end
91
+
92
+ # Delete a child taken from the pool (once; later calls do nothing).
93
+ def release(child)
94
+ mine = @lock.synchronize { !@live.delete(child.id).nil? }
95
+ ForkMap.quiet_delete(child) if mine
96
+ end
97
+
98
+ # Stop tracking a child without deleting it (keep).
99
+ def forget(child)
100
+ @lock.synchronize { @live.delete(child.id) }
101
+ end
102
+
103
+ def live_ids
104
+ @lock.synchronize { @live.keys }
105
+ end
106
+
107
+ # Delete every child not yet released (queued or in use): one drain
108
+ # call for the lot, then one by one if that failed.
109
+ def close
110
+ kids = @lock.synchronize do
111
+ @closed = true
112
+ @ready.clear
113
+ k = @live.values
114
+ @live.clear
115
+ k
116
+ end
117
+ return if kids.empty?
118
+
119
+ begin
120
+ @cloud.sandboxes.drain(ids: kids.map(&:id))
121
+ rescue StandardError
122
+ kids.each { |k| ForkMap.quiet_delete(k) }
123
+ end
124
+ end
125
+
126
+ private
127
+
128
+ def adopt(kids)
129
+ closed = @lock.synchronize do
130
+ kids.each { |k| @live[k.id] = k } unless @closed
131
+ @closed
132
+ end
133
+ return unless closed
134
+
135
+ kids.each { |k| ForkMap.quiet_delete(k) }
136
+ raise CancelledError
137
+ end
138
+
139
+ def fork(n, partial_ok)
140
+ kids = @base.fork(n, labels: @labels, run_id: @run_id, lease_s: @lease_s, partial_ok: partial_ok)
141
+ adopt(kids)
142
+ if kids.empty?
143
+ failed = kids.respond_to?(:failed) ? kids.failed : []
144
+ raise ForkMap.failure_from_entry(failed.first || { "message" => "the fork made no sandbox" })
145
+ end
146
+ kids.to_a
147
+ end
148
+ end
149
+
150
+ def self.quiet_delete(box)
151
+ box.delete
152
+ rescue StandardError
153
+ nil # gone already, or its lease deletes it
154
+ end
155
+
156
+ # block.call(*args); past timeout_s run on_timeout (delete the sandbox, so
157
+ # the abandoned call fails fast) and raise ItemTimeoutError.
158
+ def self.call_with_timeout(timeout_s, on_timeout, *args, &block)
159
+ return block.call(*args) if timeout_s.nil?
160
+
161
+ box = {}
162
+ t = Thread.new do
163
+ Thread.current.report_on_exception = false
164
+ begin
165
+ box[:value] = block.call(*args)
166
+ rescue Exception => e # rubocop:disable Lint/RescueException (handed to the caller)
167
+ box[:error] = e
168
+ end
169
+ end
170
+ unless t.join(timeout_s)
171
+ on_timeout.call
172
+ raise ItemTimeoutError, timeout_s
173
+ end
174
+ raise box[:error] if box.key?(:error)
175
+
176
+ box[:value]
177
+ end
178
+
179
+ # worker.call(i) for i in 0...n on +concurrency+ threads, results in
180
+ # order. Whatever ends the wait (an exception, Interrupt) stops the
181
+ # workers, and +cleanup+ always runs.
182
+ def self.run_pool(n, concurrency, stop, cleanup, &worker)
183
+ raise ArgumentError, "concurrency must be a whole number of at least 1" unless concurrency.is_a?(Integer) && concurrency >= 1
184
+
185
+ results = Array.new(n)
186
+ threads = []
187
+ begin
188
+ nxt = 0
189
+ lock = Mutex.new
190
+ [concurrency, n].min.times do
191
+ threads << Thread.new do
192
+ Thread.current.report_on_exception = false
193
+ loop do
194
+ i = lock.synchronize do
195
+ j = nxt
196
+ nxt += 1
197
+ j
198
+ end
199
+ break if i >= n
200
+
201
+ results[i] = worker.call(i)
202
+ end
203
+ end
204
+ end
205
+ threads.each(&:join)
206
+ rescue Exception # rubocop:disable Lint/RescueException (Ctrl-C: stop, clean up, re-raise)
207
+ stop[:stopped] = true
208
+ cleanup.call
209
+ threads.each(&:kill)
210
+ raise
211
+ end
212
+ cleanup.call
213
+ results
214
+ end
215
+
216
+ # Wait before the next attempt, in short steps so a stop is seen.
217
+ def self.backoff(cloud, policy, exc, attempt, stop)
218
+ wait = policy.delay(exc, attempt)
219
+ cloud.sleeper.call(wait) unless stop[:stopped]
220
+ end
221
+
222
+ def self.run(cloud, base, items, concurrency: 16, retries: 2, timeout_s: nil, labels: nil, run_id: nil,
223
+ lease_s: nil, policy: nil, &block)
224
+ raise ArgumentError, "fork_map needs a block (child, item)" if block.nil?
225
+ raise ArgumentError, "retries must be a whole number of at least 0" unless retries.is_a?(Integer) && retries >= 0
226
+
227
+ items = items.to_a
228
+ policy ||= RetryPolicy.new(attempts: retries + 1)
229
+ pool = ChildPool.new(cloud, base: base, labels: labels, run_id: run_id, lease_s: lease_s)
230
+ stop = { stopped: false }
231
+ worker = lambda do |i|
232
+ res = ForkResult.new(item: items[i], attempts: 0, failure_class: "ok")
233
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
234
+ (1..(retries + 1)).each do |attempt|
235
+ res.attempts = attempt
236
+ if stop[:stopped]
237
+ res.error = CancelledError.new
238
+ res.failure_class = "error"
239
+ break
240
+ end
241
+ child = nil
242
+ begin
243
+ child = pool.take
244
+ res.sandbox_id = child.id
245
+ c = child
246
+ res.value = call_with_timeout(timeout_s, -> { pool.release(c) }, child, items[i], &block)
247
+ res.error = nil
248
+ res.failure_class = "ok"
249
+ break
250
+ rescue StandardError => e
251
+ res.value = nil
252
+ res.error = e
253
+ fc, retryable = Kosa8.classify_failure(e)
254
+ res.failure_class = fc
255
+ break if !retryable || attempt > retries
256
+
257
+ pool.release(child) unless child.nil?
258
+ child = nil
259
+ backoff(cloud, policy, e, attempt, stop)
260
+ ensure
261
+ pool.release(child) unless child.nil?
262
+ end
263
+ end
264
+ res.ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).to_i
265
+ res
266
+ end
267
+ begin
268
+ pool.prefork([items.size, concurrency].min) unless items.empty?
269
+ rescue Exception # rubocop:disable Lint/RescueException
270
+ pool.close
271
+ raise
272
+ end
273
+ run_pool(items.size, concurrency, stop, -> { pool.close }, &worker)
274
+ end
275
+ end
276
+ end