scout-rig 0.2.6 → 0.2.7

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 (51) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +31 -13
  3. data/README.md +27 -4
  4. data/Rakefile +1 -0
  5. data/VERSION +1 -1
  6. data/doc/Improvements.md +396 -0
  7. data/doc/StartHere.md +95 -0
  8. data/doc/developer/Architecture.md +232 -0
  9. data/doc/developer/DataConversionInternals.md +407 -0
  10. data/doc/developer/DesignPrinciples.md +254 -0
  11. data/doc/developer/PythonTaskRunnerInternals.md +371 -0
  12. data/doc/developer/PythonWorkflowInternals.md +539 -0
  13. data/doc/developer/ScoutPythonInternals.md +504 -0
  14. data/doc/user/Cookbook.md +337 -0
  15. data/doc/user/DefiningPythonTasks.md +708 -0
  16. data/doc/user/DrivingWorkflowsFromPython.md +418 -0
  17. data/doc/user/IteratingPythonData.md +142 -0
  18. data/doc/user/PassingDataToPython.md +223 -0
  19. data/doc/user/PythonEnvironments.md +197 -0
  20. data/doc/user/RunningPythonFromRuby.md +267 -0
  21. data/doc/user/ScriptingPython.md +281 -0
  22. data/doc/user/TestingAndPackaging.md +487 -0
  23. data/lib/scout/python/script.rb +11 -2
  24. data/lib/scout/workflow/python/inputs.rb +33 -23
  25. data/lib/scout/workflow/python/task.rb +219 -22
  26. data/lib/scout/workflow/python.rb +236 -9
  27. data/lib/scout-rig/testing/availability.rb +608 -0
  28. data/python/README.md +51 -0
  29. data/python/scout/__init__.py +2 -0
  30. data/python/scout/runner.py +193 -29
  31. data/python/scout/task_errors.py +6 -0
  32. data/research/00_scope_and_themes.md +131 -0
  33. data/research/data-conversion-and-scripting-analysis.md +209 -0
  34. data/research/design-philosophy-analysis.md +246 -0
  35. data/research/python-helper-package-analysis.md +272 -0
  36. data/research/pythonworkflow-analysis.md +199 -0
  37. data/research/scoutpython-bridge-analysis.md +185 -0
  38. data/research/synthesis-report.md +109 -0
  39. data/research/testing-availability-baseline.md +1625 -0
  40. data/research/testing-availability-final-report.md +500 -0
  41. data/research/validation-report.md +149 -0
  42. data/scout-rig.gemspec +35 -5
  43. data/test/scout/python/test_util.rb +13 -0
  44. data/test/scout/test_python.rb +10 -0
  45. data/test/scout/workflow/python/test_task.rb +1119 -1
  46. data/test/scout-rig/testing/test_availability.rb +495 -0
  47. data/test/scout-rig/testing/test_test_support.rb +166 -0
  48. data/test/test_helper.rb +96 -19
  49. metadata +47 -4
  50. data/doc/Python.md +0 -482
  51. data/doc/PythonWorkflow.md +0 -163
@@ -0,0 +1,608 @@
1
+ # Opt-in runtime-availability probes for scout-rig test suites (step 2 of
2
+ # the testing-availability plan; see research/testing-availability-baseline.md
3
+ # and the scout-essentials handoff note it references).
4
+ #
5
+ # Layering contract: scout-essentials owns the generic primitives (PATH
6
+ # lookup, bounded child execution, bounded TCP connect); scout-rig owns the
7
+ # interpreter knowledge layered on top. This file adds only that knowledge:
8
+ #
9
+ # python? / python_modules? / python_modules_reason
10
+ # rscript? / r_packages? / r_packages_reason (reference probes only; no
11
+ # scout-rig R runtime is
12
+ # implied or validated)
13
+ # embedded_python / subprocess_python / python_routes_divergence_reason
14
+ # reset!
15
+ #
16
+ # It is strictly opt-in: requiring it loads 'scout/testing/availability'
17
+ # and nothing else of consequence - no scout-rig production code, no
18
+ # ScoutPython, no embedded-Python bridge - and no production or entry file
19
+ # may require it back. Tests require it explicitly:
20
+ #
21
+ # require 'scout-rig/testing/availability'
22
+ #
23
+ # Process discipline, delegated to the primitive: every check launches a
24
+ # child through Scout::Testing::Availability.run_command (bounded timeout,
25
+ # both output streams drained concurrently, launch failure and timeout
26
+ # reported on the returned result instead of raised) and decides on the
27
+ # REAL exit status, never on output and never on mere PATH existence.
28
+ # Module and package names always travel as process arguments to a fixed
29
+ # probe source; they are never interpolated into Python or R source, so no
30
+ # name can escape a string literal. Nothing here rescues Exception, and the
31
+ # only rescue in the file is a StandardError-scoped guard around a
32
+ # filesystem resolution race: no SignalException or NoMemoryError can be
33
+ # swallowed and cached as "unavailable" - unexpected exceptions propagate
34
+ # to the caller.
35
+
36
+ require 'scout/testing/availability'
37
+
38
+ module ScoutRig
39
+ module Testing
40
+ module Availability
41
+
42
+ # Bounded timeout, in seconds, for every probe. Aligned with
43
+ # Scout::Testing::Availability::DEFAULT_TIMEOUT. Importing a large
44
+ # package (numpy, pandas, torch, ...) is slower than a stdlib import,
45
+ # so every helper takes a `timeout:` keyword (nil means this default)
46
+ # that is cheap to raise; the timeout is part of every memo key, so
47
+ # raising it never replays a stale verdict.
48
+ DEFAULT_TIMEOUT = 30
49
+
50
+ # Default execution route probed. :subprocess is what
51
+ # ScoutPython.script, ScoutPython.run_file and python_task actually
52
+ # run today (a literal `python` resolved from PATH; see
53
+ # lib/scout/python/script.rb), so it is the honest default for gating
54
+ # tests. :embedded predicts the interpreter the in-process bridge
55
+ # would pick instead; see embedded_python for exactly what that
56
+ # prediction does and does not promise.
57
+ DEFAULT_ROUTE = :subprocess
58
+
59
+ # Routes a Python probe accepts.
60
+ ROUTES = [:subprocess, :embedded].freeze
61
+
62
+ # Longest tail of captured child output kept in a reason string, so
63
+ # reasons stay concise and human-actable.
64
+ REASON_TAIL = 400
65
+
66
+ # Shared memo store for definitive probe results, and its lock. A
67
+ # constant rather than a module ivar so that the mixin form (include
68
+ # ScoutRig::Testing::Availability, or its Helpers alias) and the
69
+ # module-function form share one cache: an instance-method call would
70
+ # otherwise write ivars on the including object instead of the
71
+ # module. reset! clears it in place; never reassign it.
72
+ MEMO = {}
73
+ MEMO_MUTEX = Mutex.new
74
+
75
+ # Sanity probe for a Python interpreter: it must start and exit 0.
76
+ # Output is irrelevant; the exit status is the verdict.
77
+ PYTHON_SANITY_SOURCE = 'import sys'.freeze
78
+
79
+ # Fixed import probe (frozen source; module names arrive as argv and
80
+ # are never interpolated into this text). Missing modules, with the
81
+ # exception type and message, are written to stderr - where Python
82
+ # tracebacks belong - and any miss exits 1. The in-source rescue
83
+ # keeps stderr condensed to one line per missing module, so reasons
84
+ # never need traceback surgery. Names are passed as trailing argv
85
+ # after `-c <source>`: everything following `-c <source>` lands in
86
+ # sys.argv verbatim (verified: even names like '-c' or '--version'
87
+ # are not re-parsed as interpreter options), so no name can be
88
+ # swallowed as an option or executed as code.
89
+ PYTHON_MODULES_PROBE = <<~'PY'.freeze
90
+ import importlib
91
+ import sys
92
+
93
+ missing = []
94
+ for name in sys.argv[1:]:
95
+ try:
96
+ importlib.import_module(name)
97
+ except Exception as exc:
98
+ missing.append("%s: %s: %s" % (name, type(exc).__name__, exc))
99
+ if missing:
100
+ sys.stderr.write("; ".join(missing) + "\n")
101
+ sys.exit(1)
102
+ PY
103
+
104
+ # Sanity probe for an Rscript executable: starts, writes, exits 0.
105
+ RSCRIPT_SANITY_SOURCE = 'cat("ok")'.freeze
106
+
107
+ # Fixed namespace probe (frozen source; package names arrive through
108
+ # commandArgs(TRUE), never interpolated). Availability means
109
+ # requireNamespace() LOADS the package - not that its name appears in
110
+ # an installation list. Missing names are printed to stdout (R's cat
111
+ # writes there) and any miss quits with status 1.
112
+ #
113
+ # commandArgs(TRUE) RETAINS the literal '--args' element when Rscript
114
+ # is invoked as `Rscript -e <src> --args pkg...`, so the probe filters
115
+ # it explicitly.
116
+ R_PACKAGES_PROBE = <<~'R'.freeze
117
+ args <- commandArgs(TRUE)
118
+ pkgs <- args[args != "--args"]
119
+ absent <- character(0)
120
+ for (pkg in pkgs) {
121
+ if (!requireNamespace(pkg, quietly = TRUE)) {
122
+ absent <- c(absent, pkg)
123
+ }
124
+ }
125
+ if (length(absent) > 0) {
126
+ cat(paste(absent, collapse = ", "), "\n")
127
+ quit(status = 1)
128
+ }
129
+ R
130
+
131
+ # --- Python interpreter and module probes --------------------------------
132
+
133
+ # True iff the selected Python executable exists AND runs: the sanity
134
+ # probe is executed and must exit 0. PATH existence alone proves
135
+ # nothing (a broken interpreter or a missing stdlib still shows up on
136
+ # PATH), and output is never consulted.
137
+ #
138
+ # Selection precedence, first match wins (see python_target):
139
+ # 1. the `executable:` keyword (explicit, overrides everything)
140
+ # 2. ENV['SCOUT_TEST_PYTHON'] (test-only pin, see below)
141
+ # 3. the default for `route:` - :subprocess (the default) resolves
142
+ # subprocess_python, :embedded resolves embedded_python
143
+ def python?(executable: nil, route: DEFAULT_ROUTE, timeout: nil)
144
+ python_runtime_reason(executable: executable, route: route, timeout: timeout).nil?
145
+ end
146
+
147
+ # True iff every named module imports under the selected interpreter.
148
+ # Exactly `python_modules_reason(...).nil?`. Symbols are accepted and
149
+ # normalized to strings, so `python_modules?(:torch)` works. An empty
150
+ # module list is vacuously available - but only after an interpreter
151
+ # was actually selected: with no executable resolved, the absent-
152
+ # interpreter reason wins, so an empty ask never masks a missing
153
+ # interpreter.
154
+ def python_modules?(*modules, executable: nil, route: DEFAULT_ROUTE, timeout: nil)
155
+ python_modules_reason(*modules, executable: executable, route: route, timeout: timeout).nil?
156
+ end
157
+
158
+ # nil when every named module imports under the selected interpreter;
159
+ # otherwise one concise diagnostic string that includes the resolved
160
+ # executable path, the failing module name(s) and the useful stderr
161
+ # tail - enough for a human to act on. Use it as an omit message when
162
+ # an optional dependency is genuinely absent; never use it to swallow
163
+ # a regression in shipped code.
164
+ def python_modules_reason(*modules, executable: nil, route: DEFAULT_ROUTE, timeout: nil)
165
+ seconds = probe_timeout(timeout)
166
+ target, source = python_target(executable, route)
167
+ return absent_interpreter_reason('Python', 'SCOUT_TEST_PYTHON', source) if target.nil?
168
+ return nil if modules.empty?
169
+
170
+ names = modules.map(&:to_s)
171
+ display = resolved_path_or_name(target)
172
+ memoized([:python_modules, display, names.sort, seconds, route]) do
173
+ result = Scout::Testing::Availability.run_command(
174
+ [target, '-c', PYTHON_MODULES_PROBE, *names], timeout: seconds
175
+ )
176
+ if result.success? && result.exit_status == 0
177
+ reason = nil
178
+ else
179
+ reason = python_modules_failure_reason(result, display, names, seconds)
180
+ end
181
+ [reason, definitive?(result)]
182
+ end
183
+ end
184
+
185
+ # --- R interpreter and package probes (reference code) -------------------
186
+ #
187
+ # scout-rig has no R execution runtime. These probes report whether an
188
+ # R installation is usable from a test (Rscript runs, packages load);
189
+ # they imply nothing about how scout-rig would execute R, because it
190
+ # does not. There is no `route:` dimension for the same reason.
191
+
192
+ # True iff the selected Rscript exists AND runs: the sanity probe is
193
+ # executed and must exit 0. Selection precedence: the `executable:`
194
+ # keyword, then ENV['SCOUT_TEST_RSCRIPT'], then `Rscript` from PATH.
195
+ def rscript?(executable: nil, timeout: nil)
196
+ rscript_runtime_reason(executable: executable, timeout: timeout).nil?
197
+ end
198
+
199
+ # True iff every named package loads (requireNamespace, not an
200
+ # installation-list lookup) under the selected Rscript. Exactly
201
+ # `r_packages_reason(...).nil?`; an empty list is vacuously available
202
+ # once an interpreter was actually selected (see python_modules?).
203
+ def r_packages?(*packages, executable: nil, timeout: nil)
204
+ r_packages_reason(*packages, executable: executable, timeout: timeout).nil?
205
+ end
206
+
207
+ # nil when every named package loads; otherwise one concise diagnostic
208
+ # string built stdout-first (the probe's missing-package list) and then
209
+ # the stderr tail, prefixed by the resolved executable path.
210
+ def r_packages_reason(*packages, executable: nil, timeout: nil)
211
+ seconds = probe_timeout(timeout)
212
+ target = rscript_target(executable)
213
+ if target.nil?
214
+ return absent_interpreter_reason('R', 'SCOUT_TEST_RSCRIPT',
215
+ 'Rscript default (Rscript from PATH)')
216
+ end
217
+ return nil if packages.empty?
218
+
219
+ names = packages.map(&:to_s)
220
+ display = resolved_path_or_name(target)
221
+ memoized([:r_packages, display, names.sort, seconds]) do
222
+ result = Scout::Testing::Availability.run_command(
223
+ [target, '--vanilla', '-e', R_PACKAGES_PROBE, '--args', *names],
224
+ timeout: seconds
225
+ )
226
+ if result.success? && result.exit_status == 0
227
+ reason = nil
228
+ else
229
+ reason = r_packages_failure_reason(result, display, names, seconds)
230
+ end
231
+ [reason, definitive?(result)]
232
+ end
233
+ end
234
+
235
+ # --- Route accessors and divergence ---------------------------------------
236
+
237
+ # The interpreter the EMBEDDED route would use, computed WITHOUT
238
+ # initializing the embedded bridge: ENV['PYTHON'] when set (a blank
239
+ # value counts as unset), else the first of python3/python found on
240
+ # PATH. This mirrors the documented choice of the in-process bridge:
241
+ # PyCall.init reads ENV['PYTHON'] and otherwise investigates python3
242
+ # then python from PATH.
243
+ #
244
+ # This is a PREDICTION of that choice, never a validation. It does not
245
+ # prove that the matching native library loads into the Ruby process,
246
+ # it does not run the interpreter at all, and it deliberately does not
247
+ # reproduce the process-environment mutation the real initialization
248
+ # performs (it would export PYTHONHOME; this accessor never touches
249
+ # the environment). Probing route :embedded therefore checks that the
250
+ # predicted interpreter and its modules work as a subprocess - it
251
+ # cannot certify the in-process binding. Returns nil when nothing
252
+ # matches. Unaffected by SCOUT_TEST_PYTHON, which pins probes only.
253
+ #
254
+ # ScoutCoder: the embedded bridge's PATH candidate order (python3
255
+ # before python) is not documented in scout-rig's user docs; it had to
256
+ # be read from the pycall gem (LibPython::Finder::DEFAULT_PYTHON).
257
+ # doc/user/PythonEnvironments.md only says "PATH resolution when PYTHON
258
+ # is unset".
259
+ def embedded_python
260
+ pinned = ENV['PYTHON'].to_s.strip
261
+ return pinned unless pinned.empty?
262
+
263
+ %w[python3 python].each do |candidate|
264
+ return candidate if Scout::Testing::Availability.executable?(candidate)
265
+ end
266
+ nil
267
+ end
268
+
269
+ # The interpreter the SUBPROCESS route uses today: the literal command
270
+ # `python` resolved from PATH, exactly what ScoutPython.script,
271
+ # ScoutPython.run_file and python_task spawn (ENV['PYTHON'] is never
272
+ # consulted on that route). Returns nil when PATH has no python, which
273
+ # means the route cannot run anything at all. Unaffected by
274
+ # SCOUT_TEST_PYTHON, which pins probes only.
275
+ def subprocess_python
276
+ 'python' if Scout::Testing::Availability.executable?('python')
277
+ end
278
+
279
+ # nil when both execution routes resolve to the same interpreter;
280
+ # otherwise a short message naming both resolutions, the cause and the
281
+ # limit of what any single probe can tell you. Resolution here is a
282
+ # PATH lookup canonicalized to an absolute real path (symlinks
283
+ # followed), so python3 and python aliasing one binary do not count as
284
+ # divergent.
285
+ #
286
+ # The comparison is between PREDICTED selections: it never initializes
287
+ # the embedded bridge, so it cannot validate that the native binding
288
+ # loads. SCOUT_TEST_PYTHON is deliberately ignored here: a pin
289
+ # overrides probing only, and a pinned probe silently hiding a real
290
+ # production divergence is exactly what this reporter exists to
291
+ # expose.
292
+ def python_routes_divergence_reason
293
+ embedded = embedded_python
294
+ subprocess = subprocess_python
295
+ embedded_path = resolve_interpreter(embedded)
296
+ subprocess_path = resolve_interpreter(subprocess)
297
+
298
+ return nil if embedded_path && subprocess_path && embedded_path == subprocess_path
299
+
300
+ embedded_description =
301
+ if embedded.nil?
302
+ 'nothing (PYTHON is unset and neither python3 nor python is on PATH)'
303
+ else
304
+ "#{embedded} -> #{embedded_path || 'unresolvable'}"
305
+ end
306
+ subprocess_description =
307
+ if subprocess.nil?
308
+ "nothing (no 'python' on PATH, so the subprocess route cannot run at all)"
309
+ else
310
+ "#{subprocess} -> #{subprocess_path || 'unresolvable'}"
311
+ end
312
+
313
+ "Python routes diverge: the embedded route would initialize " \
314
+ "#{embedded_description}, while the subprocess route spawns the literal " \
315
+ "'python' from PATH (#{subprocess_description}). Cause: ENV['PYTHON'] " \
316
+ "selects only the embedded route and PATH selects only the subprocess " \
317
+ "route, so the two can silently point at different interpreters; put the " \
318
+ "intended interpreter's bin directory first on PATH (and unset PYTHON) so " \
319
+ "both resolve it. Note that no probe validates both routes: probing one " \
320
+ "route exercises only that route's interpreter and says nothing about the " \
321
+ "other."
322
+ end
323
+
324
+ # --- Memoization control ---------------------------------------------------
325
+
326
+ # Drop every memoized probe result. Probe keys are built from inputs
327
+ # that are re-resolved on every call (the executable is resolved
328
+ # through the CURRENT SCOUT_TEST_*/PYTHON/PATH before each probe, so a
329
+ # changed environment naturally produces a new key), and reset! is the
330
+ # explicit hygiene hook for test setups that manipulate the
331
+ # environment: call it whenever you change SCOUT_TEST_PYTHON,
332
+ # SCOUT_TEST_RSCRIPT, PATH or ENV['PYTHON'] and want a provably fresh
333
+ # probe. Returns nil.
334
+ def reset!
335
+ MEMO_MUTEX.synchronize { MEMO.clear }
336
+ nil
337
+ end
338
+
339
+ # Both call styles are supported and share one implementation and one
340
+ # MEMO store: module functions
341
+ # (ScoutRig::Testing::Availability.python_modules?(:torch)) and an
342
+ # optional mixin, where a test class includes the module (or its
343
+ # Helpers alias below) and calls the helpers directly from test
344
+ # bodies. The helpers above are ordinary instance methods and the
345
+ # module extends itself; the helpers below stay private in both
346
+ # styles.
347
+ extend self
348
+
349
+ private
350
+
351
+ # SCOUT_TEST_PYTHON / SCOUT_TEST_RSCRIPT versus PYTHON and PATH:
352
+ #
353
+ # - PYTHON (read by the embedded bridge's initialization) and PATH
354
+ # (used by the literal `python` subprocess spawn) are PRODUCTION
355
+ # inputs. This module never sets, unsets or otherwise mutates them.
356
+ # - SCOUT_TEST_PYTHON / SCOUT_TEST_RSCRIPT are TEST-ONLY pins. When
357
+ # set, they OVERRIDE route resolution for probing: every Python
358
+ # helper probes exactly that interpreter whichever `route:` is
359
+ # asked for, so a pinned probe cannot detect a route divergence -
360
+ # ask python_routes_divergence_reason (which ignores the pin) for
361
+ # that.
362
+ # - They do not change production code: ScoutPython.script / run_file
363
+ # / python_task keep spawning `python` from PATH and the embedded
364
+ # bridge keeps reading PYTHON. The reliable environment recipe
365
+ # remains "put the intended environment's bin directory first on
366
+ # PATH so both routes resolve the same interpreter"; the pins exist
367
+ # for suites that must probe one absolute interpreter, and for R,
368
+ # where no scout-rig route exists at all.
369
+ def python_target(executable, route)
370
+ unless ROUTES.include?(route)
371
+ raise ArgumentError, "unknown route #{route.inspect}; expected :subprocess or :embedded"
372
+ end
373
+
374
+ explicit = executable.to_s.strip
375
+ return [explicit, 'executable: keyword'] unless explicit.empty?
376
+
377
+ pinned = ENV['SCOUT_TEST_PYTHON'].to_s.strip
378
+ return [pinned, "ENV['SCOUT_TEST_PYTHON']"] unless pinned.empty?
379
+
380
+ case route
381
+ when :subprocess
382
+ [subprocess_python, 'route :subprocess default (literal python from PATH)']
383
+ when :embedded
384
+ [embedded_python, 'route :embedded default (PYTHON else python3/python from PATH)']
385
+ end
386
+ end
387
+
388
+ def rscript_target(executable)
389
+ explicit = executable.to_s.strip
390
+ return explicit unless explicit.empty?
391
+
392
+ pinned = ENV['SCOUT_TEST_RSCRIPT'].to_s.strip
393
+ return pinned unless pinned.empty?
394
+
395
+ 'Rscript' if Scout::Testing::Availability.executable?('Rscript')
396
+ end
397
+
398
+ # nil (or omitted) timeout means DEFAULT_TIMEOUT. The normalized value
399
+ # is used for the launch, the memo key and every reason string, so an
400
+ # explicit `timeout: nil` and an omitted timeout can never diverge.
401
+ def probe_timeout(timeout)
402
+ timeout.nil? ? DEFAULT_TIMEOUT : timeout
403
+ end
404
+
405
+ # A run is definitive when the child actually reached an exit status.
406
+ # Success and exit-status failures (missing module, missing package,
407
+ # broken interpreter) say something durable about the selected
408
+ # interpreter and MAY be memoized. A launch error or a timeout says
409
+ # nothing durable - the executable may appear on PATH a moment later,
410
+ # or the import may simply be slow - so those verdicts are returned to
411
+ # the caller but NEVER memoized; an identical later call re-runs the
412
+ # probe. This is the rule that keeps a transient condition from being
413
+ # cached as "unavailable" for the rest of the process.
414
+ #
415
+ # ScoutCoder: whether CommandResult offers a timed_out? predicate had
416
+ # to be probed by hand; the struct exposes the plain `timed_out`
417
+ # member (and `reason`) but no predicate, and the scout-essentials
418
+ # source is the only place that says so.
419
+ def definitive?(result)
420
+ !result.launch_error && !result.timed_out
421
+ end
422
+
423
+ def python_runtime_reason(executable: nil, route: DEFAULT_ROUTE, timeout: nil)
424
+ seconds = probe_timeout(timeout)
425
+ target, source = python_target(executable, route)
426
+ return absent_interpreter_reason('Python', 'SCOUT_TEST_PYTHON', source) if target.nil?
427
+
428
+ display = resolved_path_or_name(target)
429
+ memoized([:python_runtime, display, seconds, route]) do
430
+ result = Scout::Testing::Availability.run_command(
431
+ [target, '-c', PYTHON_SANITY_SOURCE], timeout: seconds
432
+ )
433
+ if definitive?(result) && result.exit_status == 0
434
+ reason = nil
435
+ elsif result.launch_error
436
+ reason = "#{display}: Python interpreter could not start: #{result.launch_error}"
437
+ elsif result.timed_out
438
+ reason = "#{display}: Python interpreter probe timed out after #{seconds}s; " \
439
+ 'raise the timeout: keyword if startup is legitimately slow'
440
+ else
441
+ detail = [result.stderr, result.stdout].map { |stream| stream.to_s.strip }
442
+ .reject(&:empty?).first
443
+ reason = if detail
444
+ "#{display}: python exited #{result.exit_status} (#{tail(detail)})"
445
+ else
446
+ "#{display}: python exited #{result.exit_status}"
447
+ end
448
+ end
449
+ [reason, definitive?(result)]
450
+ end
451
+ end
452
+
453
+ def python_modules_failure_reason(result, display, names, seconds)
454
+ if result.launch_error
455
+ "#{display}: Python probe could not start: #{result.launch_error} " \
456
+ "(modules: #{names.join(', ')})"
457
+ elsif result.timed_out
458
+ "#{display}: Python import probe timed out after #{seconds}s " \
459
+ "(modules: #{names.join(', ')}); raise the timeout: keyword for slow imports"
460
+ else
461
+ detail = result.stderr.to_s.strip
462
+ if detail.empty?
463
+ "#{display}: python exited #{result.exit_status} probing modules: #{names.join(', ')}"
464
+ else
465
+ missing = missing_python_names(detail, names)
466
+ "#{display}: missing Python modules: #{missing.join(', ')} (#{tail(detail)})"
467
+ end
468
+ end
469
+ end
470
+
471
+ def rscript_runtime_reason(executable: nil, timeout: nil)
472
+ seconds = probe_timeout(timeout)
473
+ target = rscript_target(executable)
474
+ if target.nil?
475
+ return absent_interpreter_reason('R', 'SCOUT_TEST_RSCRIPT',
476
+ 'Rscript default (Rscript from PATH)')
477
+ end
478
+
479
+ display = resolved_path_or_name(target)
480
+ memoized([:rscript_runtime, display, seconds]) do
481
+ result = Scout::Testing::Availability.run_command(
482
+ [target, '--vanilla', '-e', RSCRIPT_SANITY_SOURCE], timeout: seconds
483
+ )
484
+ if definitive?(result) && result.exit_status == 0
485
+ reason = nil
486
+ elsif result.launch_error
487
+ reason = "#{display}: Rscript could not start: #{result.launch_error}"
488
+ elsif result.timed_out
489
+ reason = "#{display}: Rscript probe timed out after #{seconds}s; " \
490
+ 'raise the timeout: keyword if startup is legitimately slow'
491
+ else
492
+ detail = [result.stderr, result.stdout].map { |stream| stream.to_s.strip }
493
+ .reject(&:empty?).first
494
+ reason = if detail
495
+ "#{display}: Rscript exited #{result.exit_status} (#{tail(detail)})"
496
+ else
497
+ "#{display}: Rscript exited #{result.exit_status}"
498
+ end
499
+ end
500
+ [reason, definitive?(result)]
501
+ end
502
+ end
503
+
504
+ def r_packages_failure_reason(result, display, names, seconds)
505
+ if result.launch_error
506
+ "#{display}: Rscript probe could not start: #{result.launch_error} " \
507
+ "(packages: #{names.join(', ')})"
508
+ elsif result.timed_out
509
+ "#{display}: R package probe timed out after #{seconds}s " \
510
+ "(packages: #{names.join(', ')}); raise the timeout: keyword for slow loads"
511
+ else
512
+ missing = result.stdout.to_s.strip
513
+ detail = result.stderr.to_s.strip
514
+ parts = []
515
+ parts << "missing R packages: #{missing}" unless missing.empty?
516
+ parts << tail(detail) unless detail.empty?
517
+ parts << "Rscript exited #{result.exit_status}" if parts.empty?
518
+ "#{display}: #{parts.join('; ')}"
519
+ end
520
+ end
521
+
522
+ # Store and return the block's verdict. The block returns
523
+ # [reason_or_nil, definitive]; only definitive verdicts are stored, so
524
+ # a timeout or launch error is recomputed on the next identical call
525
+ # (never cached as unavailability). An exception raised by the probe
526
+ # propagates to the caller and is never cached either. The lock is
527
+ # held across the probe so concurrent test threads do not spawn
528
+ # duplicate children for one key.
529
+ def memoized(key)
530
+ MEMO_MUTEX.synchronize do
531
+ return MEMO[key] if MEMO.key?(key)
532
+
533
+ value, definitive = yield
534
+ MEMO[key] = value if definitive
535
+ value
536
+ end
537
+ end
538
+
539
+ def absent_interpreter_reason(language, env_var, source)
540
+ "#{language} interpreter not found (#{source}); " \
541
+ "pin one with #{env_var} or the executable: keyword, or fix PATH"
542
+ end
543
+
544
+ # The probe writes "name: ExceptionType: message" per missing module,
545
+ # joined by "; ". Recover the names; when anything fails to parse,
546
+ # fall back to the requested list (a superset of the missing ones, so
547
+ # the reason never understates what was asked for).
548
+ def missing_python_names(detail, requested)
549
+ parsed = detail.split('; ').map do |entry|
550
+ match = entry.match(/\A([^:]+): /)
551
+ match && match[1].strip
552
+ end.compact
553
+ parsed.empty? ? requested : parsed
554
+ end
555
+
556
+ # Canonical absolute path for an executable name: the file itself when
557
+ # the candidate carries a path separator, else the first PATH hit;
558
+ # symlinks are resolved so aliases of one binary compare equal. nil
559
+ # when nothing resolves. Re-run on every call (never memoized) so a
560
+ # mid-process PATH change re-resolves and produces fresh probe keys.
561
+ # The rescue only covers the race between the existence check and
562
+ # realpath (the file disappearing or a path component turning into a
563
+ # file); it is StandardError-scoped by design and returns nil, the
564
+ # honest answer for a candidate that cannot be resolved.
565
+ def resolve_interpreter(name)
566
+ candidate = name.to_s
567
+ return nil if candidate.strip.empty?
568
+
569
+ begin
570
+ if candidate.include?(File::SEPARATOR)
571
+ return File.realpath(candidate) if File.file?(candidate) && File.executable?(candidate)
572
+ return nil
573
+ end
574
+
575
+ ENV['PATH'].to_s.split(File::PATH_SEPARATOR).each do |directory|
576
+ next if directory.to_s.empty?
577
+
578
+ path = File.join(directory, candidate)
579
+ return File.realpath(path) if File.file?(path) && File.executable?(path)
580
+ end
581
+ rescue StandardError
582
+ nil
583
+ end
584
+ end
585
+
586
+ # The resolved absolute path when the name resolves, else the name
587
+ # itself: used both for human-facing reasons and for memo keys.
588
+ def resolved_path_or_name(name)
589
+ resolve_interpreter(name) || name.to_s
590
+ end
591
+
592
+ def tail(text)
593
+ string = text.to_s
594
+ return string if string.length <= REASON_TAIL
595
+
596
+ '...' + string[-REASON_TAIL..]
597
+ end
598
+ end
599
+
600
+ # Optional mixin spelling of the same surface: a test class may either
601
+ # call the module functions or `include ScoutRig::Testing::Helpers`.
602
+ # This is the very same module object (Availability extends itself, so
603
+ # including it mixes in the public helpers), not a second
604
+ # implementation; both spellings therefore share one MEMO store and one
605
+ # code path.
606
+ Helpers = Availability
607
+ end
608
+ end