kosa8 0.4.0 → 0.5.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.
data/lib/kosa8/rl.rb ADDED
@@ -0,0 +1,617 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+
6
+ # RL training on kosa8 Cloud: leases that die with the trainer, runs that
7
+ # record rollouts (shown on app.kosa8.com, RL runs), and Run#map, one
8
+ # training step over forks with a sealed grader.
9
+ module Kosa8
10
+ module RL
11
+ # Default lease: a sandbox is deleted this long after the last heartbeat.
12
+ DEFAULT_LEASE_S = 600
13
+ # Rows per POST /v1/rl/runs/{id}/rollouts.
14
+ MAX_ROWS_PER_CALL = 500
15
+ # Failure classes masked by default: the sandbox or the platform failed,
16
+ # not the policy, so the rollout must not train as reward 0. "error" is
17
+ # your own solve raising (a harness bug). Add "timeout" to mask timeouts.
18
+ DEFAULT_MASK = %w[infra quota error].freeze
19
+ MASKABLE = %w[ok exit_nonzero timeout infra quota client error].freeze
20
+ STDOUT_TAIL = 64 * 1024
21
+ ROW_STDOUT_TAIL = 4096
22
+ META_MAX = 8192
23
+
24
+ # Keeps leased sandboxes alive while the trainer is, and deletes them
25
+ # when it stops. A thread sends a heartbeat every +interval_s+ (default a
26
+ # third of +lease_s+) for the sandboxes picked by run_id:, labels: or
27
+ # ids:. On #close (and at exit) the thread stops and, with drain: true,
28
+ # every matching sandbox is deleted. If the process is killed outright
29
+ # the heartbeats stop and kosa8 Cloud deletes them lease_s later.
30
+ class Lease
31
+ attr_reader :beats, :last_error, :drained, :lease_s, :interval_s
32
+
33
+ def initialize(cloud, run_id: nil, labels: nil, ids: nil, lease_s: DEFAULT_LEASE_S, interval_s: nil, drain: true,
34
+ on_tick: nil)
35
+ raise ArgumentError, "a lease needs run_id:, labels: or ids: (which sandboxes)" if run_id.nil? && labels.nil? && ids.nil?
36
+
37
+ Cloud.check_lease(lease_s)
38
+ @cloud = cloud
39
+ @selector = { run_id: run_id, labels: labels, ids: ids }
40
+ @lease_s = lease_s
41
+ @interval_s = interval_s.nil? ? [5.0, lease_s / 3.0].max : interval_s.to_f
42
+ @drain = drain
43
+ @on_tick = on_tick
44
+ @beats = 0
45
+ @last_error = nil
46
+ @drained = nil
47
+ @lock = Mutex.new
48
+ @cv = ConditionVariable.new
49
+ @stopped = false
50
+ @closed = false
51
+ @thread = nil
52
+ end
53
+
54
+ def start
55
+ return self unless @thread.nil?
56
+
57
+ @thread = Thread.new { loop_beats }
58
+ @thread.report_on_exception = false
59
+ lease = self
60
+ at_exit { lease.close }
61
+ self
62
+ end
63
+
64
+ # One heartbeat (and the tick) now.
65
+ def beat
66
+ @beats += 1 if @cloud.sandboxes.heartbeat(**@selector).is_a?(Integer)
67
+ rescue StandardError => e
68
+ @last_error = e
69
+ ensure
70
+ tick
71
+ end
72
+
73
+ # Stop heartbeating, run the last tick, and drain (drain: true). Safe to call twice.
74
+ def close
75
+ @lock.synchronize do
76
+ return if @closed
77
+
78
+ @closed = true
79
+ @stopped = true
80
+ @cv.broadcast
81
+ end
82
+ @thread&.join(5)
83
+ tick
84
+ return unless @drain
85
+
86
+ begin
87
+ @drained = @cloud.sandboxes.drain(**@selector)
88
+ rescue StandardError => e
89
+ @last_error = e
90
+ end
91
+ end
92
+
93
+ private
94
+
95
+ def tick
96
+ @on_tick&.call
97
+ rescue StandardError => e
98
+ @last_error = e
99
+ end
100
+
101
+ def loop_beats
102
+ loop do
103
+ @lock.synchronize do
104
+ @cv.wait(@lock, @interval_s) unless @stopped
105
+ end
106
+ break if @stopped
107
+
108
+ beat
109
+ end
110
+ end
111
+ end
112
+
113
+ # One rollout. +masked+ means leave it out of the gradient (the failure
114
+ # was not the policy's); then +reward+ is nil, never 0.
115
+ RolloutResult = Struct.new(:task, :group, :index, :step, :reward, :failure_class, :masked, :metrics, :output,
116
+ :exit_code, :stdout, :stderr, :error, :attempts, :duration_ms, :sandbox_id,
117
+ :grader_id, :tokens, :cost_usd, :recorded, :meta, keyword_init: true) do
118
+ def ok?
119
+ %w[ok exit_nonzero].include?(failure_class) && !masked
120
+ end
121
+
122
+ # The row POST /v1/rl/runs/{id}/rollouts takes.
123
+ def to_row
124
+ m = (meta || {}).dup
125
+ m["metrics"] = metrics if metrics && !metrics.empty?
126
+ m["masked"] = true if masked
127
+ m["error"] = error.to_s[0, 2000] if error
128
+ m["attempts"] = attempts if attempts.to_i > 1
129
+ # The server keeps the classes it knows; the SDK's own "error" (solve
130
+ # raised) is recorded as "client", with the error in meta.
131
+ fc = failure_class == "error" ? "client" : failure_class
132
+ m["sdk_failure_class"] = "error" if failure_class == "error"
133
+ row = { "step" => step, "group" => group.to_s, "index" => index, "sandbox_id" => sandbox_id,
134
+ "reward" => reward, "failure_class" => fc, "exit" => exit_code, "duration_ms" => duration_ms,
135
+ "meta" => m.empty? ? nil : RL.fit_meta(m), "stdout_tail" => (stdout || "")[-ROW_STDOUT_TAIL..-1] || stdout,
136
+ "tokens" => tokens, "cost_usd" => cost_usd }
137
+ row.reject { |_, v| v.nil? }
138
+ end
139
+ end
140
+
141
+ # The results of a map, in input order (task-major, group_size per task).
142
+ class Rollouts < Array
143
+ # Each reward, nil where masked.
144
+ def rewards
145
+ map(&:reward)
146
+ end
147
+
148
+ # true where the rollout should train (not masked).
149
+ def mask
150
+ map { |r| !r.masked }
151
+ end
152
+
153
+ def mean_reward
154
+ vals = map(&:reward).compact
155
+ vals.empty? ? nil : vals.sum.to_f / vals.size
156
+ end
157
+
158
+ def by_class
159
+ each_with_object(Hash.new(0)) { |r, h| h[r.failure_class] += 1 }
160
+ end
161
+
162
+ # The rollouts of each task together, for group-relative advantages (GRPO).
163
+ def groups
164
+ group_by(&:group).sort_by { |k, _| k }.map { |_, v| v }
165
+ end
166
+ end
167
+
168
+ # Drop the largest meta values until it fits in +limit+ bytes as JSON.
169
+ def self.fit_meta(meta, limit = META_MAX)
170
+ m = meta.dup
171
+ while JSON.generate(m).bytesize > limit && !m.empty?
172
+ k = m.max_by { |_, v| JSON.generate(v).bytesize }[0]
173
+ m.delete(k)
174
+ m["truncated"] = true
175
+ end
176
+ m
177
+ end
178
+
179
+ # The hidden grader files a task carries: task["files"] (or "hidden_files").
180
+ def self.task_files(task)
181
+ return nil unless task.is_a?(Hash)
182
+
183
+ %w[files hidden_files].each do |k|
184
+ v = task[k] || task[k.to_sym]
185
+ return v if v.is_a?(Hash)
186
+ end
187
+ nil
188
+ end
189
+
190
+ def self.task_id(task)
191
+ return nil unless task.is_a?(Hash)
192
+
193
+ %w[id task_id instance_id].each do |k|
194
+ v = task[k] || task[k.to_sym]
195
+ return v unless v.nil?
196
+ end
197
+ nil
198
+ end
199
+
200
+ # A grade that answered 200 but whose command did not finish on a
201
+ # retryable failure: raised so the retry loop grades again (a new
202
+ # Idempotency-Key, since a replay would give the same answer).
203
+ class GradeDidNotFinish < Error
204
+ attr_reader :grade
205
+
206
+ def initialize(grade)
207
+ super(grade.message || grade.error || "the grader did not finish",
208
+ body: { "failure_class" => grade.failure_class, "retryable" => true })
209
+ @grade = grade
210
+ end
211
+ end
212
+
213
+ # One RL training run on kosa8 Cloud.
214
+ #
215
+ # Kosa8::RL::Run.open(cloud, "my-grpo-run") do |run|
216
+ # base = cloud.sandboxes.create(template: "python")
217
+ # results = run.map(base, tasks, grade_cmd: ["python", "/grader/test.py"]) do |box, task|
218
+ # box.exec(["python", "solve.py", task["prompt"]])
219
+ # end
220
+ # end
221
+ #
222
+ # Starting it creates the run (or attaches to run_id:) and starts a Lease:
223
+ # every sandbox this cloud makes while the run is open is labelled
224
+ # kosa8.run=<id> and leased for lease_s, heartbeats keep them alive, and
225
+ # finishing records what is left, deletes the run's sandboxes
226
+ # (drain_on_exit) and marks the run finished or failed.
227
+ class Run
228
+ attr_reader :cloud, :name, :id, :project, :config, :lease_s, :recorded, :status, :info, :lease
229
+
230
+ def self.open(cloud, name = nil, **kw)
231
+ run = new(cloud, name, **kw).start
232
+ return run unless block_given?
233
+
234
+ begin
235
+ r = yield run
236
+ rescue Exception # rubocop:disable Lint/RescueException (Ctrl-C too: drain, then re-raise)
237
+ run.finish("failed")
238
+ raise
239
+ end
240
+ run.finish("finished")
241
+ r
242
+ end
243
+
244
+ # A Run for an existing run (to keep recording after a restart).
245
+ def self.attach(cloud, run_id, **kw)
246
+ new(cloud, nil, run_id: run_id, **kw)
247
+ end
248
+
249
+ # The org's runs, newest first, each with a short summary.
250
+ def self.list(cloud, project: nil, status: nil, name: nil, limit: nil)
251
+ q = [["project", project], ["status", status], ["name", name], ["limit", limit]].reject { |_, v| v.nil? }
252
+ r = cloud.request("GET", "/v1/rl/runs" + (q.empty? ? "" : "?#{URI.encode_www_form(q.map { |k, v| [k, v.to_s] })}"))
253
+ r.is_a?(Hash) ? (r["runs"] || []) : []
254
+ end
255
+
256
+ def initialize(cloud, name = nil, run_id: nil, project: nil, config: nil, lease_s: DEFAULT_LEASE_S,
257
+ drain_on_exit: true, flush_every: 100, heartbeat_s: nil)
258
+ raise ArgumentError, "give the run a name, or run_id: to attach to one" if (name.nil? || name.to_s.empty?) && run_id.nil?
259
+ unless flush_every.is_a?(Integer) && flush_every.between?(1, MAX_ROWS_PER_CALL)
260
+ raise ArgumentError, "flush_every must be from 1 to #{MAX_ROWS_PER_CALL}"
261
+ end
262
+
263
+ Cloud.check_lease(lease_s)
264
+ @cloud = cloud
265
+ @name = name
266
+ @id = run_id
267
+ @project = project
268
+ @config = config
269
+ @lease_s = lease_s
270
+ @drain_on_exit = drain_on_exit
271
+ @flush_every = flush_every
272
+ @heartbeat_s = heartbeat_s
273
+ @info = {}
274
+ @recorded = 0
275
+ @status = nil
276
+ @buf = []
277
+ @buf_lock = Mutex.new
278
+ @flush_lock = Mutex.new
279
+ @lease = nil
280
+ @prev_defaults = nil
281
+ @step = 0
282
+ @open = false
283
+ end
284
+
285
+ def inspect
286
+ "#<Kosa8::RL::Run id=#{@id.inspect} name=#{@name.inspect}>"
287
+ end
288
+
289
+ def open?
290
+ @open
291
+ end
292
+
293
+ # Create (or attach to) the run and start its lease.
294
+ def start
295
+ return self if @open
296
+
297
+ if @id.nil?
298
+ body = { "name" => @name.to_s }
299
+ body["project"] = @project.to_s unless @project.nil?
300
+ body["config"] = @config unless @config.nil?
301
+ @info = run_of(@cloud.request("POST", "/v1/rl/runs", body))
302
+ @id = @info["id"]
303
+ raise Error, "kosa8 Cloud answered no run id" if @id.nil?
304
+ end
305
+ @status = "running"
306
+ @prev_defaults = @cloud.run_defaults
307
+ @cloud.run_defaults = { "run_id" => @id, "lease_s" => @lease_s }
308
+ @lease = Lease.new(@cloud, run_id: @id, lease_s: @lease_s, drain: @drain_on_exit, interval_s: @heartbeat_s,
309
+ on_tick: -> { tick })
310
+ @lease.start
311
+ @open = true
312
+ self
313
+ end
314
+
315
+ # Record what is buffered, drain the run's sandboxes (drain_on_exit)
316
+ # and mark the run finished (or failed). Safe to call twice.
317
+ def finish(status = "finished")
318
+ raise ArgumentError, "status is finished or failed" unless %w[finished failed].include?(status)
319
+ return unless @open
320
+
321
+ @open = false
322
+ lease = @lease
323
+ @lease = nil
324
+ lease ? lease.close : tick
325
+ @cloud.run_defaults = @prev_defaults
326
+ begin
327
+ update(status: status)
328
+ rescue StandardError => e
329
+ warn "kosa8: could not mark run #{@id} #{status}: #{e.message}"
330
+ end
331
+ @status = status
332
+ end
333
+
334
+ # Buffer one rollout or many (a RolloutResult or a Hash with step,
335
+ # group, index, reward, failure_class, exit, duration_ms, tokens,
336
+ # cost_usd, meta, stdout_tail). They are sent in batches of
337
+ # flush_every (at most 500 a call), every heartbeat, and at finish.
338
+ def record(rollouts, flush: nil)
339
+ list = rollouts.is_a?(Hash) || rollouts.is_a?(RolloutResult) ? [rollouts] : rollouts.to_a
340
+ rows = list.map { |r| r.is_a?(RolloutResult) ? r.to_row : r.map { |k, v| [k.to_s, v] }.to_h }
341
+ full = @buf_lock.synchronize do
342
+ @buf.concat(rows)
343
+ @buf.size >= @flush_every
344
+ end
345
+ self.flush if flush || (flush.nil? && full)
346
+ nil
347
+ end
348
+
349
+ # Send every buffered rollout now; returns how many were recorded. On
350
+ # an error the unsent rows stay buffered and the error is raised.
351
+ def flush
352
+ sent = 0
353
+ @flush_lock.synchronize do
354
+ loop do
355
+ chunk = @buf_lock.synchronize { @buf.shift(MAX_ROWS_PER_CALL) }
356
+ return sent if chunk.empty?
357
+
358
+ begin
359
+ r = @cloud.request("POST", path("/rollouts"), { "rollouts" => chunk })
360
+ rescue Exception # rubocop:disable Lint/RescueException
361
+ @buf_lock.synchronize { @buf.unshift(*chunk) }
362
+ raise
363
+ end
364
+ n = r.is_a?(Hash) && r["recorded"].is_a?(Integer) ? r["recorded"] : chunk.size
365
+ sent += n
366
+ @recorded += n
367
+ end
368
+ end
369
+ end
370
+
371
+ # Rollouts buffered, not yet sent.
372
+ def pending
373
+ @buf_lock.synchronize { @buf.size }
374
+ end
375
+
376
+ # The run with its summary (rewards, failure classes, live sandboxes,
377
+ # cost) and recommendations.
378
+ def summary
379
+ r = @cloud.request("GET", path)
380
+ @info = run_of(r) unless run_of(r).empty?
381
+ r
382
+ end
383
+
384
+ def update(status: nil, name: nil)
385
+ body = {}
386
+ body["status"] = status unless status.nil?
387
+ body["name"] = name unless name.nil?
388
+ raise ArgumentError, "give status: or name:" if body.empty?
389
+
390
+ i = run_of(@cloud.request("PATCH", path, body))
391
+ @info = i unless i.empty?
392
+ @info
393
+ end
394
+
395
+ # One page of recorded rollouts: {"rollouts" => [...], "next_cursor" => ...}.
396
+ def rollouts(step: nil, failure_class: nil, min_reward: nil, max_reward: nil, sandbox_id: nil, limit: nil,
397
+ cursor: nil)
398
+ q = [["step", step], ["failure_class", failure_class], ["min_reward", min_reward], ["max_reward", max_reward],
399
+ ["sandbox_id", sandbox_id], ["limit", limit], ["cursor", cursor]].reject { |_, v| v.nil? }
400
+ @cloud.request("GET", path("/rollouts" + (q.empty? ? "" : "?#{URI.encode_www_form(q.map { |k, v| [k, v.to_s] })}")))
401
+ end
402
+
403
+ # Every rollout as JSON lines (binary String); written to +file+ when given.
404
+ def export(file = nil)
405
+ data = @cloud.request_bytes("GET", path("/export?format=jsonl"), raw: true)
406
+ File.binwrite(file, data) unless file.nil?
407
+ data
408
+ end
409
+
410
+ # Delete the run's sandboxes now (the run stays open).
411
+ def drain
412
+ @cloud.sandboxes.drain(run_id: @id)
413
+ end
414
+
415
+ # One training step: the block (sandbox, task) for every task
416
+ # (group_size samples each, e.g. GRPO's G), +concurrency+ at a time.
417
+ #
418
+ # For each rollout: fork +base+ (a CloudSandbox; or a Hash of create
419
+ # options, or a Proc(task) returning a sandbox), run the block in it,
420
+ # grade it in a sealed fork with grade_cmd: and the task's hidden files
421
+ # (task["files"], or files: a Hash or Proc(task)), record it on the run,
422
+ # delete the sandbox. Without grade_cmd:, reward: Proc(sandbox, task,
423
+ # output) or the block's own return (a number, or {"reward" => x})
424
+ # is the reward.
425
+ #
426
+ # Infra failures and rate limits are retried +retries+ times on a fresh
427
+ # sandbox with backoff and jitter (a failed grade is retried alone
428
+ # first). What still fails in +mask+ comes back masked with reward nil,
429
+ # never 0. timeout_s: caps the block. step: defaults to this run's
430
+ # count of maps. Results in task order: Rollouts.
431
+ def map(base, tasks, grade_cmd: nil, files: nil, grade_timeout_s: nil, grade_env: nil, reward: nil,
432
+ concurrency: 16, group_size: 1, step: nil, retries: 2, timeout_s: nil, mask: DEFAULT_MASK,
433
+ keep: false, meta: nil, &solve)
434
+ raise ArgumentError, "the run is not open: use Run.open(...) or run.start" unless @open
435
+ raise ArgumentError, "map needs a block (sandbox, task)" if solve.nil?
436
+ raise ArgumentError, "group_size must be a whole number of at least 1" unless group_size.is_a?(Integer) && group_size >= 1
437
+ raise ArgumentError, "retries must be a whole number of at least 0" unless retries.is_a?(Integer) && retries >= 0
438
+
439
+ mask = mask.map(&:to_s)
440
+ unknown = mask - MASKABLE
441
+ raise ArgumentError, "unknown failure classes in mask: #{unknown.join(', ')}" unless unknown.empty?
442
+
443
+ if step.nil?
444
+ step = @step
445
+ @step += 1
446
+ end
447
+ tasks = tasks.to_a
448
+ n = tasks.size * group_size
449
+ policy = RetryPolicy.new(attempts: retries + 1)
450
+ pool = if base.is_a?(CloudSandbox)
451
+ ForkMap::ChildPool.new(@cloud, base: base, run_id: @id, lease_s: @lease_s)
452
+ else
453
+ ForkMap::ChildPool.new(@cloud, make: maker(base))
454
+ end
455
+ stop = { stopped: false }
456
+ files_for = lambda do |task|
457
+ next files.call(task) if files.respond_to?(:call)
458
+ next files unless files.nil?
459
+
460
+ RL.task_files(task)
461
+ end
462
+ worker = lambda do |i|
463
+ ti, g = i.divmod(group_size)
464
+ task = tasks[ti]
465
+ res = RolloutResult.new(task: task, group: ti, index: g, step: step, failure_class: "ok", masked: false,
466
+ metrics: {}, stdout: "", stderr: "", attempts: 0, recorded: false, meta: {})
467
+ tid = RL.task_id(task)
468
+ res.meta["task"] = tid unless tid.nil?
469
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
470
+ out = nil
471
+ (1..(retries + 1)).each do |attempt|
472
+ res.attempts = attempt
473
+ if stop[:stopped]
474
+ res.failure_class = "error"
475
+ res.error = "cancelled before it ran"
476
+ break
477
+ end
478
+ child = nil
479
+ begin
480
+ child = pool.take(task)
481
+ res.sandbox_id = child.id
482
+ c = child
483
+ out = ForkMap.call_with_timeout(timeout_s, -> { pool.release(c) }, child, task, &solve)
484
+ res.output = out
485
+ res.failure_class = "ok"
486
+ res.error = nil
487
+ gave = RL.from_output(res, out)
488
+ if !grade_cmd.nil?
489
+ info = { "group" => res.group, "index" => res.index, "step" => res.step }
490
+ info["meta"] = res.meta.dup unless res.meta.empty?
491
+ gc = child
492
+ gr = begin
493
+ Kosa8.with_retry(policy, sleeper: ->(s) { @cloud.sleeper.call(s) unless stop[:stopped] }) do
494
+ r = gc.grade(grade_cmd, files: files_for.call(task), timeout_s: grade_timeout_s, env: grade_env,
495
+ run_id: @id, rollout: info)
496
+ raise GradeDidNotFinish, r if r.reward.nil? && r.retryable
497
+
498
+ r
499
+ end
500
+ rescue GradeDidNotFinish => e
501
+ e.grade # still not finished: masked below
502
+ end
503
+ RL.apply_grade(res, gr)
504
+ elsif !reward.nil?
505
+ raise TypeError, "reward: must return a number or {\"reward\" => x}" unless RL.from_output(res, reward.call(child, task, out))
506
+ elsif !gave
507
+ raise ArgumentError, "no reward: pass grade_cmd: (a sealed grader), reward: ->(sandbox, task, output) { }, " \
508
+ "or return a number or {\"reward\" => x} from the block"
509
+ end
510
+ break
511
+ rescue StandardError => e
512
+ fc, retryable = Kosa8.classify_failure(e)
513
+ res.failure_class = fc
514
+ res.error = "#{e.class}: #{e.message}"
515
+ res.reward = nil
516
+ break if !retryable || attempt > retries
517
+
518
+ pool.release(child) unless child.nil?
519
+ child = nil
520
+ ForkMap.backoff(@cloud, policy, e, attempt, stop)
521
+ ensure
522
+ unless child.nil?
523
+ if keep && res.failure_class != "infra"
524
+ pool.forget(child)
525
+ else
526
+ pool.release(child)
527
+ end
528
+ end
529
+ end
530
+ end
531
+ res.duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).to_i
532
+ res.meta.update((meta.call(task, out) || {}).map { |k, v| [k.to_s, v] }.to_h) unless meta.nil?
533
+ res.masked = mask.include?(res.failure_class)
534
+ res.reward = nil if res.masked
535
+ unless res.recorded
536
+ begin
537
+ record(res)
538
+ rescue StandardError
539
+ nil # recording never fails a rollout
540
+ end
541
+ end
542
+ res
543
+ end
544
+ begin
545
+ pool.prefork([n, concurrency].min) if n.positive?
546
+ rescue Exception # rubocop:disable Lint/RescueException
547
+ pool.close
548
+ raise
549
+ end
550
+ Rollouts.new(ForkMap.run_pool(n, concurrency, stop, -> { pool.close }, &worker))
551
+ end
552
+
553
+ private
554
+
555
+ def tick
556
+ flush
557
+ rescue StandardError => e
558
+ warn "kosa8: recording rollouts of run #{@id} failed, will retry: #{e.message}"
559
+ end
560
+
561
+ def path(suffix = "")
562
+ raise ArgumentError, "the run has not started: use Run.open(...) or run.start" if @id.nil?
563
+
564
+ "/v1/rl/runs/#{Kosa8.enc(@id)}#{suffix}"
565
+ end
566
+
567
+ def run_of(answer)
568
+ return answer["run"] if answer.is_a?(Hash) && answer["run"].is_a?(Hash)
569
+
570
+ answer.is_a?(Hash) ? answer : {}
571
+ end
572
+
573
+ # How to make each rollout's sandbox when base is not a sandbox to fork.
574
+ def maker(base)
575
+ return ->(task) { base.call(task) } if base.respond_to?(:call)
576
+ raise ArgumentError, "base is a CloudSandbox to fork, a Hash of create options, or a Proc(task)" unless base.is_a?(Hash)
577
+
578
+ opts = base.map { |k, v| [k.to_sym, v] }.to_h
579
+ ->(_task) { @cloud.sandboxes.create(**opts.merge(run_id: @id, lease_s: @lease_s)) }
580
+ end
581
+ end
582
+
583
+ # Take reward/metrics/tokens/meta from what solve returned; true if it gave a reward.
584
+ def self.from_output(res, out)
585
+ return false if out == true || out == false
586
+ if out.is_a?(Numeric)
587
+ res.reward = out.to_f
588
+ return true
589
+ end
590
+ return false unless out.is_a?(Hash)
591
+
592
+ h = out.map { |k, v| [k.to_s, v] }.to_h
593
+ res.tokens = h["tokens"] if h["tokens"].is_a?(Integer)
594
+ res.cost_usd = h["cost_usd"].to_f if h["cost_usd"].is_a?(Numeric)
595
+ res.meta.update(h["meta"].map { |k, v| [k.to_s, v] }.to_h) if h["meta"].is_a?(Hash)
596
+ r = h["reward"]
597
+ return false unless r.is_a?(Numeric)
598
+
599
+ res.reward = r.to_f
600
+ res.metrics = h["metrics"] if h["metrics"].is_a?(Hash)
601
+ true
602
+ end
603
+
604
+ def self.apply_grade(res, g)
605
+ res.reward = g.reward
606
+ res.metrics = g.metrics
607
+ res.exit_code = g.exit_code
608
+ res.stdout = g.stdout[-STDOUT_TAIL..-1] || g.stdout
609
+ res.stderr = g.stderr[-STDOUT_TAIL..-1] || g.stderr
610
+ res.failure_class = g.failure_class
611
+ res.grader_id = g.grader_id
612
+ res.error = "grader: #{g.error}: #{g.message}".sub(/:\s*\z/, "") if g.reward.nil? && g.error
613
+ # kosa8 Cloud recorded it (source "grade") when given a run: never twice.
614
+ res.recorded = g.recorded == true
615
+ end
616
+ end
617
+ end
data/lib/kosa8/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Kosa8
4
- VERSION = "0.4.0"
4
+ VERSION = "0.5.0"
5
5
  end
data/lib/kosa8.rb CHANGED
@@ -10,3 +10,6 @@ require_relative "kosa8/toolbox"
10
10
  require_relative "kosa8/client"
11
11
  require_relative "kosa8/cloud"
12
12
  require_relative "kosa8/cloud_features"
13
+ require_relative "kosa8/cloud_rl"
14
+ require_relative "kosa8/fork_map"
15
+ require_relative "kosa8/rl"
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kosa8
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - kosa8
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-15 00:00:00.000000000 Z
11
+ date: 2026-11-22 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: 'Typed client for the kosa8 daemon: sandboxes, run/exec streams, snapshots,
14
14
  fork, best-of-N explore and checkpoints shared with the kosa8 CLI, plus the kosa8
@@ -25,7 +25,10 @@ files:
25
25
  - lib/kosa8/client.rb
26
26
  - lib/kosa8/cloud.rb
27
27
  - lib/kosa8/cloud_features.rb
28
+ - lib/kosa8/cloud_rl.rb
28
29
  - lib/kosa8/errors.rb
30
+ - lib/kosa8/fork_map.rb
31
+ - lib/kosa8/rl.rb
29
32
  - lib/kosa8/toolbox.rb
30
33
  - lib/kosa8/transport.rb
31
34
  - lib/kosa8/version.rb