scout-essentials 1.9.1 → 1.9.4

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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +19 -1
  3. data/Rakefile +9 -0
  4. data/VERSION +1 -1
  5. data/doc/Improvements.md +20 -0
  6. data/doc/StartHere.md +7 -4
  7. data/doc/developer/AnnotationSystem.md +10 -15
  8. data/doc/developer/Configuration.md +20 -30
  9. data/doc/developer/CoreUtilities.md +52 -22
  10. data/doc/developer/DesignPrinciples.md +7 -9
  11. data/doc/developer/DocumentationPractices.md +476 -0
  12. data/doc/developer/ErrorHandling.md +11 -20
  13. data/doc/developer/LockingAndConcurrency.md +20 -13
  14. data/doc/developer/StreamingModel.md +13 -14
  15. data/doc/developer/Testing.md +389 -0
  16. data/doc/user/AnnotatingData.md +9 -13
  17. data/doc/user/CommandLineOptions.md +9 -12
  18. data/doc/user/Cookbook.md +7 -10
  19. data/doc/user/HandlingStreams.md +22 -29
  20. data/doc/user/LoggingAndProgress.md +9 -11
  21. data/doc/user/ProducingResources.md +0 -1
  22. data/doc/user/RemoteData.md +10 -13
  23. data/doc/user/RunningCommands.md +12 -17
  24. data/doc/user/WorkingWithFiles.md +10 -2
  25. data/lib/scout/config.rb +1 -0
  26. data/lib/scout/indiferent_hash/json.rb +5 -0
  27. data/lib/scout/indiferent_hash.rb +10 -3
  28. data/lib/scout/log/fingerprint.rb +1 -1
  29. data/lib/scout/misc/digest.rb +11 -6
  30. data/lib/scout/named_array.rb +4 -0
  31. data/lib/scout/open/final.rb +1 -1
  32. data/lib/scout/open/stream.rb +14 -13
  33. data/lib/scout/path/util.rb +1 -1
  34. data/lib/scout/testing/availability.rb +264 -0
  35. data/lib/scout/testing/scout_state.rb +193 -0
  36. data/lib/scout/testing.rb +82 -0
  37. data/research/doc-audit-findings.md +7 -5
  38. data/research/doc-structure.md +89 -0
  39. data/research/lock-namespace-blindness.md +73 -0
  40. data/research/probing-guide.md +311 -0
  41. data/research/testing-availability-scout-ai-handoff.md +235 -0
  42. data/research/testing-availability-scout-rig-handoff.md +355 -0
  43. data/scout-essentials.gemspec +26 -3
  44. data/test/scout/annotation/test_dup_clone.rb +31 -0
  45. data/test/scout/indiferent_hash/test_case_insensitive_staleness.rb +27 -0
  46. data/test/scout/indiferent_hash/test_json.rb +13 -0
  47. data/test/scout/indiferent_hash/test_string2hash_false.rb +13 -0
  48. data/test/scout/misc/test_timespan.rb +30 -0
  49. data/test/scout/open/test_compression_detection.rb +32 -0
  50. data/test/scout/open/test_forced_gzip_broken.rb +25 -0
  51. data/test/scout/test_named_array_resolution.rb +49 -0
  52. data/test/scout/test_testing.rb +195 -0
  53. data/test/scout/test_tmpfile_cleanup.rb +23 -0
  54. data/test/scout/testing/test_availability.rb +222 -0
  55. data/test/scout/testing/test_state_bindings.rb +163 -0
  56. data/test/test_helper.rb +26 -12
  57. metadata +25 -2
@@ -0,0 +1,235 @@
1
+ # Testing availability handoff — scout-ai
2
+
3
+ Provenance: salvage packet produced during the scout-essentials layering
4
+ cleanup (2026-10). scout-ai keeps the model/accelerator/endpoint probes that
5
+ were incorrectly drafted into scout-essentials. This note is self-contained:
6
+ verified call-site inventory, retention list, the 7-defect list with the
7
+ correction for each, a delegation example, the compat-adapter option, and
8
+ constraints.
9
+
10
+ ## Verified call-site inventory (read-only pass over /home/mvazque2/git/scout-ai)
11
+
12
+ - `python_modules?`
13
+ - `test/scout/model/python/test_torch.rb`
14
+ - `test/scout/model/python/huggingface/test_classification.rb`
15
+ - `test/scout/model/python/huggingface/causal/test_next_token.rb`
16
+ - `cuda?`
17
+ - `test/scout/model/python/torch/test_helpers.rb`
18
+ - `hf_model_cached?`
19
+ - `test/scout/model/python/huggingface/test_causal.rb`
20
+ - `test/scout/model/python/huggingface/test_classification.rb`
21
+ - `test/scout/model/python/huggingface/causal/test_next_token.rb`
22
+ - `hf_model_reason` — same three files as `hf_model_cached?` (omit messages).
23
+ - `rscript?`, `r_packages?`, `endpoint_reachable?` — **zero** call sites
24
+ outside `test/support/availability.rb` itself.
25
+ - `endpoint_configured?('test')` — `test/integration/scout/llm/test_infrastructure.rb:30`.
26
+ - `test/support/infrastructure_probes.rb` — used by
27
+ `test/integration/scout/llm/backends/test_endpoints.rb` and
28
+ `test/integration/scout/llm/test_infrastructure.rb`;
29
+ `test/integration/scout/model/test_base.rb` also uses `Availability`
30
+ (specifically `r_packages?('e1071')` / `r_packages_reason`).
31
+ - `SCOUT_TEST_PYTHON` appears **only** inside `availability.rb`.
32
+ - `test/test_helper.rb` requires `support/fixtures` and `support/mock_backend`
33
+ but **not** `support/availability`; each test file that needs it requires it
34
+ directly (e.g. `test_causal.rb` documents the dependency).
35
+
36
+ ## Layer table (what stays where)
37
+
38
+ | Probe / method | Layer | Destination |
39
+ |---|---|---|
40
+ | `executable?`, `run_command`, `tcp_reachable?` | scout-essentials | `Scout::Testing::Availability` (delivered, stdlib-only) |
41
+ | `cuda?` | scout-ai | `test/support/availability.rb` |
42
+ | `hf_model_cached?` / `hf_model_reason` (must honor `HF_HUB_CACHE`) | scout-ai | same |
43
+ | `endpoint_reachable?`, `endpoint_configured?`, `endpoint_reason`, `configured_endpoints`, `real_endpoints`, `endpoint_available?` | scout-ai | same |
44
+ | `InfrastructureProbes` | scout-ai | `test/support/infrastructure_probes.rb` — unchanged |
45
+ | `python?`, `python_modules?`(+reason), `rscript?`, `r_packages?`(+reason) | scout-rig | see `testing-availability-scout-rig-handoff.md`; scout-ai may still call them until its own suite stops depending on them (see note on `test_base.rb`) |
46
+
47
+ ## Retention list (do not delete in scout-ai)
48
+
49
+ - `cuda?` — one live call site.
50
+ - `hf_model_cached?` + `hf_model_reason` — three live call sites; must honor
51
+ `HF_HUB_CACHE`.
52
+ - `endpoint_reachable?`, `endpoint_configured?`, `endpoint_reason`,
53
+ `configured_endpoints`, `real_endpoints`, `endpoint_available?` — endpoint
54
+ family; memoization must key on the timeout argument.
55
+ - `InfrastructureProbes` — used by two integration suites; keep unchanged.
56
+
57
+ `rscript?`/`r_packages?` have exactly one live consumer
58
+ (`test/integration/scout/model/test_base.rb:12`, e1071) and no R integration
59
+ in scout-rig; keep them (reference-only, as in the rig handoff) until that
60
+ call site is either guarded by an R-availability decision or removed.
61
+
62
+ ## The 7-item defect list with corrections
63
+
64
+ 1. **`python?` ignores subprocess exit status.** A broken interpreter can
65
+ still print. Decide on `exit_status == 0`, not on output presence.
66
+ 2. **`python_modules_reason` reads stdout.** Import tracebacks go to stderr;
67
+ read `result.stderr`, falling back to a synthesized reason when it is
68
+ empty.
69
+ 3. **`memo` rescues `Exception`.** Rescue `StandardError` only; timeout and
70
+ launch failure are handled deliberately (recorded on the result), never
71
+ swallowed. Never cache a `SignalException` as "unavailable".
72
+ 4. **`run_bounded` drains stdout before stderr** (pipe deadlock with chatty
73
+ children), **spawns before its rescue** (launch failure escapes), and the
74
+ **`capture:false` path drains neither pipe**. Corrected shape: spawn inside
75
+ the rescue scope; drain both pipes concurrently (reader threads) with a
76
+ deadline; on timeout TERM the process group, wait a grace, then KILL;
77
+ report launch failure as a structured result.
78
+ 5. **`endpoint_reachable?` memoization ignores the timeout argument.** Key the
79
+ memo on `(endpoint_or_host, port, timeout)` — a 2s probe and a 30s probe
80
+ must not share an entry.
81
+ 6. **HF cache lookup ignores `HF_HUB_CACHE`.** Resolve the cache root as
82
+ `ENV['HF_HUB_CACHE']` (if set) else the default
83
+ `~/.cache/huggingface/hub`, then check for the model directory
84
+ (`models--<org>--<name>` with a snapshots dir) beneath it.
85
+ 7. **Module/package names interpolated unsafely into Python/R source.** Pass
86
+ them as argv to a fixed probe script, or use `Shellwords.escape` when a
87
+ source string is unavoidable.
88
+
89
+ The corrected generic primitives (`executable?`, `run_command`,
90
+ `tcp_reachable?`) now live in scout-essentials'
91
+ `Scout::Testing::Availability`; defects 3 and 4 are already fixed there, so
92
+ the cheapest correct move for scout-ai is delegation (below) rather than a
93
+ local `run_bounded`.
94
+
95
+ ## Delegation example
96
+
97
+ Reimplement scout-ai's internals on the primitives; keep behavior, drop the
98
+ local runner:
99
+
100
+ ```ruby
101
+ # scout-ai test/support/availability.rb (revised)
102
+ require 'scout/testing/availability' # scout-essentials primitives
103
+
104
+ module Availability
105
+ PROBE_TIMEOUT = 30
106
+ CACHE_TIMEOUT = 300
107
+
108
+ class << self
109
+ # defect 3: StandardError only; explicit reset.
110
+ def reset!
111
+ @memo = {}
112
+ end
113
+
114
+ def memoized(key)
115
+ @memo ||= {}
116
+ return @memo[key] if @memo.key?(key)
117
+
118
+ @memo[key] = yield
119
+ rescue StandardError => e
120
+ "probe error: #{e.class}: #{e.message}"
121
+ end
122
+
123
+ # defect 1 + 7: exit status decides; module names as argv.
124
+ def python_modules?(*modules)
125
+ !python_modules_reason(*modules)
126
+ end
127
+
128
+ def python_modules_reason(*modules)
129
+ python = ENV['SCOUT_TEST_PYTHON'].to_s.strip
130
+ python = 'python3' if python.empty? &&
131
+ Scout::Testing::Availability.executable?('python3')
132
+ return 'no python executable found' if python.nil? || python.empty?
133
+
134
+ probe = <<~PY
135
+ import importlib, sys
136
+ missing = []
137
+ for name in sys.argv[1:]:
138
+ try:
139
+ importlib.import_module(name)
140
+ except Exception as e:
141
+ missing.append("%s: %s: %s" % (name, type(e).__name__, e))
142
+ if missing:
143
+ sys.stderr.write("; ".join(missing))
144
+ sys.exit(1)
145
+ PY
146
+ result = Scout::Testing::Availability.run_command(
147
+ [python, '-c', probe, *modules], timeout: PROBE_TIMEOUT
148
+ )
149
+ return nil if result.success? && result.exit_status == 0
150
+
151
+ # Launch failure and timeout are the concrete reasons; otherwise the
152
+ # trimmed stderr (defect 2), else the exit status.
153
+ detail = result.launch_error
154
+ detail ||= "timed out after #{PROBE_TIMEOUT}s" if result.timed_out
155
+ detail ||=
156
+ if result.stderr.to_s.strip.empty?
157
+ "python exited #{result.exit_status}"
158
+ else
159
+ result.stderr.to_s.strip
160
+ end
161
+ detail
162
+ end
163
+
164
+ # defect 5: memo key includes the timeout.
165
+ def endpoint_reachable?(name, timeout: PROBE_TIMEOUT)
166
+ endpoint = configured_endpoints[name]
167
+ return "no endpoint '#{name}' configured" unless endpoint
168
+
169
+ host, port = endpoint[:host], endpoint[:port]
170
+ key = [:tcp, host, port, timeout] # <-- timeout in the key
171
+ hit = memoized(key) { Scout::Testing::Availability.tcp_reachable?(host, port, timeout: timeout) }
172
+ hit ? nil : "endpoint '#{name}' (#{host}:#{port}) not reachable within #{timeout}s"
173
+ end
174
+
175
+ # defect 6: honor HF_HUB_CACHE.
176
+ def hf_model_cached?(model)
177
+ !hf_model_reason(model)
178
+ end
179
+
180
+ def hf_model_reason(model)
181
+ cache = ENV['HF_HUB_CACHE'].to_s.strip
182
+ cache = File.join(ENV['HOME'].to_s, '.cache', 'huggingface', 'hub') if cache.empty?
183
+ dir = File.join(cache, 'models--' + model.tr('/', '--'))
184
+ return "model #{model} not in cache (#{dir})" unless File.directory?(dir)
185
+
186
+ snapshots = File.join(dir, 'snapshots')
187
+ return "model #{model} cached but empty" unless File.directory?(snapshots) &&
188
+ Dir.children(snapshots).any?
189
+
190
+ nil
191
+ end
192
+ end
193
+ end
194
+ ```
195
+
196
+ The reason-selection block in `python_modules_reason` picks, in order: the
197
+ launch error, the timeout note, the trimmed stderr, and finally the exit
198
+ status.
199
+
200
+ ## Compat-adapter option
201
+
202
+ If touching call sites is out of scope for the first pass, keep the existing
203
+ public method names and reimplement the internals:
204
+
205
+ ```ruby
206
+ module Availability
207
+ def self.endpoint_reachable?(endpoint_name, timeout: PROBE_TIMEOUT)
208
+ host, port = resolve(endpoint_name)
209
+ key = [:tcp, host, port, timeout]
210
+ memoized(key) { Scout::Testing::Availability.tcp_reachable?(host, port, timeout: timeout) }
211
+ end
212
+ # same for any local bounded execution: delegate to
213
+ # Scout::Testing::Availability.run_command
214
+ end
215
+ ```
216
+
217
+ The four files with `python_modules?`/`cuda?`/`hf_model_cached?` call sites
218
+ keep working unchanged; the internals become the fixed primitives.
219
+
220
+ ## Constraints
221
+
222
+ - **Never download models**: `hf_model_cached?` inspects the local cache only;
223
+ absence reports a reason, it never fetches.
224
+ - Ordinary unit tests stay **offline**; integration tests may probe
225
+ **configured** endpoints (that is their purpose).
226
+ - Product-failure assertions must never become skips: probes omit only on
227
+ genuinely absent optional dependencies.
228
+ - Do not reintroduce interpreter/package probes into scout-essentials; the
229
+ Python/R probes belong to scout-rig (see its handoff note), and the
230
+ primitives layer is frozen at `executable?`/`run_command`/`tcp_reachable?`.
231
+ - scout-ai's `test/support/availability.rb` must keep the same public surface
232
+ (`python?`, `python_modules?`/`_reason`, `cuda?`, `hf_model_cached?`/
233
+ `_reason`, `endpoint_reachable?`, `endpoint_configured?`, `endpoint_reason`,
234
+ `configured_endpoints`, `real_endpoints`, `endpoint_available?`,
235
+ `InfrastructureProbes` unchanged) so the seven call-site files need no edits.
@@ -0,0 +1,355 @@
1
+ # Testing availability handoff — scout-rig
2
+
3
+ Provenance: salvage packet produced during the scout-essentials layering cleanup
4
+ (2026-10). The interrupted draft in scout-essentials contained Python/R probes
5
+ that belong to scout-rig. This note is self-contained: layer table, corrected
6
+ reference implementations, interpreter-selection matrix, motivation, and
7
+ constraints. Nothing here needs to be re-derived from scout-essentials.
8
+
9
+ ## Scope for scout-rig
10
+
11
+ scout-rig owns **runtime-availability probes for interpreters and their
12
+ packages**: `python?`, `python_modules?`/`python_modules_reason`,
13
+ `rscript?`, `r_packages?`/`r_packages_reason` (R: reference code only — there
14
+ are no live R call sites today).
15
+
16
+ ## Layer table
17
+
18
+ | Probe / method | Layer | Destination |
19
+ |---|---|---|
20
+ | `executable?(name)` — PATH lookup, no shell | scout-essentials | `lib/scout/testing/availability.rb` (already delivered: `Scout::Testing::Availability.executable?`) |
21
+ | `run_command(argv, timeout:)` — bounded, both streams, TERM→KILL | scout-essentials | same file, `Scout::Testing::Availability.run_command` |
22
+ | `tcp_reachable?(host, port, timeout:)` | scout-essentials | same file, `Scout::Testing::Availability.tcp_reachable?` |
23
+ | `python?` | scout-rig | scout-rig test-support module (suggested `test/support/availability.rb` equivalent, e.g. `ScoutRig::Testing::Availability`) |
24
+ | `python_modules?(mods)` + `python_modules_reason(mods)` | scout-rig | same module |
25
+ | `rscript?` | scout-rig (reference only) | same module |
26
+ | `r_packages?(pkgs)` + `r_packages_reason(pkgs)` | scout-rig (reference only) | same module |
27
+ | `cuda?` | scout-ai | scout-ai `test/support/availability.rb` (see testing-availability-scout-ai-handoff.md) |
28
+ | `hf_model_cached?` / `hf_model_reason` | scout-ai | same |
29
+ | `endpoint_reachable?`, `endpoint_configured?`, `endpoint_reason`, `configured_endpoints`, `real_endpoints`, `endpoint_available?` | scout-ai | same |
30
+ | `InfrastructureProbes` | scout-ai | scout-ai `test/support/infrastructure_probes.rb`, unchanged |
31
+
32
+ ## Defect list relevant to scout-rig
33
+
34
+ The interrupted draft (and the scout-ai support file it came from) had 7 known
35
+ defects. The ones that apply to the Python/R probes:
36
+
37
+ 1. **`python?` ignored the subprocess exit status.** `python -c 'import sys'`
38
+ can fail at startup (broken interpreter, missing stdlib) while still writing
39
+ output; only the exit status proves the interpreter works. Fixed in the
40
+ reference below.
41
+ 2. **`python_modules_reason` read stdout.** Python import tracebacks go to
42
+ **stderr**; reading stdout yields an empty, useless reason. Fixed below.
43
+ 3. **`memo` rescued `Exception`.** That swallows `SignalException`,
44
+ `NoMemoryError`, and friends. Rescue `StandardError` only; treat timeout and
45
+ launch failure deliberately (they are recorded facts, not surprises).
46
+ 4. **`run_bounded` drained stdout before stderr** (pipe-deadlock risk with a
47
+ chatty child), spawned **before** its rescue (a launch failure could escape
48
+ the method), and the `capture:false` path drained **neither** pipe. Either
49
+ delegate to `Scout::Testing::Availability.run_command` (preferred — it
50
+ drains concurrently with a deadline and reports launch failure as a result,
51
+ not an exception) or apply the corrected runner included below.
52
+ 5. (memoization ignoring an argument) — scout-rig has no endpoint probes; the
53
+ analogous rule is applied: memoize keyed on **executable + env + timeout**,
54
+ with an explicit `reset!`.
55
+ 6. (HF cache ignoring `HF_HUB_CACHE`) — scout-ai only, not applicable here.
56
+ 7. **Module/package names were interpolated unsafely** into Python/R source.
57
+ A name containing a quote escapes the source string. Pass names as **argv**
58
+ to a fixed probe script (Python: `sys.argv`; R: `commandArgs(TRUE)`), or
59
+ fall back to `Shellwords.escape` only if a source string is unavoidable.
60
+
61
+ ## Corrected reference implementations
62
+
63
+ Assumes scout-essentials ≥ the version providing
64
+ `Scout::Testing::Availability` (`require 'scout/testing/availability'`). The
65
+ module is deliberately opt-in and stdlib-only; scout-rig adds the interpreter
66
+ knowledge on top of it.
67
+
68
+ ```ruby
69
+ # scout-rig test support: interpreter/package availability probes.
70
+ # Ordinary unit tests must stay OFFLINE: these probes only run local
71
+ # executables. Product-failure assertions must never become skips.
72
+ require 'scout/testing/availability'
73
+ require 'shellwords' # only used by the *_reason fallbacks
74
+
75
+ module ScoutRig
76
+ module Testing
77
+ module Availability
78
+ PROBE_TIMEOUT = 30
79
+
80
+ class << self
81
+ # --- memoization: keyed on the probe inputs, StandardError only ---
82
+
83
+ def memo
84
+ @memo ||= {}
85
+ key = yield.to_s # caller builds the full key first
86
+ return @memo[key] if @memo.key?(key)
87
+
88
+ @memo[key] = yield # NOTE: see each probe; key is passed explicitly
89
+ end
90
+
91
+ def reset!
92
+ @memo = {}
93
+ end
94
+
95
+ def [](key)
96
+ @memo ||= {}
97
+ @memo[key]
98
+ end
99
+
100
+ def []=(key, value)
101
+ @memo ||= {}
102
+ @memo[key] = value
103
+ end
104
+
105
+ def memoized(key)
106
+ @memo ||= {}
107
+ return @memo[key] if @memo.key?(key)
108
+
109
+ @memo[key] = yield
110
+ rescue StandardError => e # defect 3: never rescue Exception
111
+ "probe error: #{e.class}: #{e.message}"
112
+ end
113
+ private :memoized
114
+
115
+ # --- executable selection ---
116
+
117
+ # SCOUT_TEST_PYTHON wins; else PATH lookup in order python3, python.
118
+ # Return is an absolute-or-PATH executable name, nil when absent.
119
+ def python_executable
120
+ configured = ENV['SCOUT_TEST_PYTHON'].to_s.strip
121
+ return configured unless configured.empty?
122
+ return 'python3' if Scout::Testing::Availability.executable?('python3')
123
+ return 'python' if Scout::Testing::Availability.executable?('python')
124
+
125
+ nil
126
+ end
127
+
128
+ def rscript_executable
129
+ configured = ENV['SCOUT_TEST_RSCRIPT'].to_s.strip
130
+ return configured unless configured.empty?
131
+ return 'Rscript' if Scout::Testing::Availability.executable?('Rscript')
132
+
133
+ nil
134
+ end
135
+
136
+ # --- Python probes ---
137
+
138
+ # defect 1: the exit status, not the output, decides.
139
+ def python?
140
+ executable = python_executable
141
+ return false unless executable
142
+
143
+ result = Scout::Testing::Availability.run_command(
144
+ [executable, '-c', 'import sys'], timeout: PROBE_TIMEOUT
145
+ )
146
+ result.success? && result.exit_status == 0
147
+ end
148
+
149
+ # defect 7: module names travel as argv, never interpolated.
150
+ # defect 2: the reason comes from stderr, where tracebacks go.
151
+ def python_modules?(*modules)
152
+ !python_modules_reason(*modules)
153
+ end
154
+
155
+ def python_modules_reason(*modules)
156
+ executable = python_executable
157
+ return 'no python executable found' unless executable
158
+ return nil if modules.empty?
159
+
160
+ # Fixed probe source; names arrive as argv so quoting is moot.
161
+ probe = <<~PY
162
+ import importlib, sys
163
+ missing = []
164
+ for name in sys.argv[1:]:
165
+ try:
166
+ importlib.import_module(name)
167
+ except Exception as e:
168
+ missing.append("%s: %s: %s" % (name, type(e).__name__, e))
169
+ if missing:
170
+ sys.stderr.write("; ".join(missing))
171
+ sys.exit(1)
172
+ PY
173
+
174
+ result = Scout::Testing::Availability.run_command(
175
+ [executable, '-c', probe, *modules], timeout: PROBE_TIMEOUT
176
+ )
177
+ return nil if result.success? && result.exit_status == 0
178
+
179
+ detail = result.stderr.to_s.strip
180
+ detail = "python exited #{result.exit_status}" if detail.empty?
181
+ detail = "python timed out after #{PROBE_TIMEOUT}s" if result.timed_out
182
+ detail = result.launch_error if result.launch_error
183
+ detail
184
+ end
185
+
186
+ # --- R probes: REFERENCE ONLY ---
187
+ # No live call sites in scout-rig today. Keep the code, do not wire
188
+ # it into unit tests until an R integration exists.
189
+
190
+ def rscript?
191
+ executable = rscript_executable
192
+ return false unless executable
193
+
194
+ result = Scout::Testing::Availability.run_command(
195
+ [executable, '--vanilla', '-e', 'cat("ok")'], timeout: PROBE_TIMEOUT
196
+ )
197
+ result.success? && result.exit_status == 0
198
+ end
199
+
200
+ # defect 7: package names as argv via commandArgs(TRUE).
201
+ def r_packages?(*packages)
202
+ !r_packages_reason(*packages)
203
+ end
204
+
205
+ def r_packages_reason(*packages)
206
+ executable = rscript_executable
207
+ return 'no Rscript executable found' unless executable
208
+ return nil if packages.empty?
209
+
210
+ probe = <<~R
211
+ args <- commandArgs(TRUE)
212
+ # `--args` itself is retained as the first element when the
213
+ # interpreter is invoked as `Rscript -e ... --args pkg1 pkg2`.
214
+ pkgs <- args[args != "--args"]
215
+ missing <- character(0)
216
+ for (p in pkgs) {
217
+ if (!requireNamespace(p, quietly = TRUE)) missing <- c(missing, p)
218
+ }
219
+ if (length(missing) > 0) {
220
+ cat(paste(missing, collapse = ", "))
221
+ quit(status = 1)
222
+ }
223
+ R
224
+
225
+ result = Scout::Testing::Availability.run_command(
226
+ [executable, '--vanilla', '-e', probe, '--args', *packages],
227
+ timeout: PROBE_TIMEOUT
228
+ )
229
+ return nil if result.success? && result.exit_status == 0
230
+
231
+ detail = result.stderr.to_s.strip
232
+ detail = result.stdout.to_s.strip if detail.empty? # R writes to stdout here
233
+ detail = "Rscript exited #{result.exit_status}" if detail.empty?
234
+ detail = "Rscript timed out after #{PROBE_TIMEOUT}s" if result.timed_out
235
+ detail = result.launch_error if result.launch_error
236
+ detail
237
+ end
238
+ end
239
+ end
240
+ end
241
+ end
242
+ ```
243
+
244
+ ### If scout-essentials cannot be a dependency
245
+
246
+ Apply the same four corrections in a local bounded runner (this is the shape
247
+ `Scout::Testing::Availability.run_command` implements; reproduce only what is
248
+ needed):
249
+
250
+ ```ruby
251
+ def run_bounded(argv, timeout: 30)
252
+ out_r, out_w = IO.pipe
253
+ err_r, err_w = IO.pipe
254
+ stdout = +''
255
+ stderr = +''
256
+ # defect 4a/4c: drain BOTH pipes concurrently, always, including when the
257
+ # caller does not want the output captured.
258
+ readers = {
259
+ out_r => stdout, err_r => stderr
260
+ }
261
+ pid = nil
262
+ begin # defect 4b: spawn INSIDE the rescue scope
263
+ pid = Process.spawn(*argv, out: out_w, err: err_w, pgroup: true)
264
+ rescue StandardError => e # launch failure is a fact, not an exception
265
+ [out_r, out_w, err_r, err_w].each { |io| io.close rescue nil }
266
+ return Struct.new(:success, :exit_status, :stdout, :stderr, :launch_error, :timed_out)
267
+ .new(false, nil, '', '', "#{e.class}: #{e.message}", false)
268
+ ensure
269
+ out_w.close rescue nil
270
+ err_w.close rescue nil
271
+ end
272
+
273
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
274
+ threads = readers.map do |io, buf|
275
+ Thread.new { io.each_line { |l| buf << l } }
276
+ end
277
+ timed_out = false
278
+ status = nil
279
+ until status
280
+ _w, st = Process.waitpid2(pid, Process::WNOHANG)
281
+ if st
282
+ status = st
283
+ break
284
+ end
285
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
286
+ timed_out = true
287
+ Process.kill('TERM', -pid) rescue nil
288
+ sleep 0.1
289
+ Process.kill('KILL', -pid) rescue nil
290
+ status = Process.waitpid2(pid).last
291
+ break
292
+ end
293
+ sleep 0.05
294
+ end
295
+ threads.each(&:join)
296
+ [out_r, err_r].each { |io| io.close rescue nil }
297
+ Struct.new(:success, :exit_status, :stdout, :stderr, :launch_error, :timed_out)
298
+ .new(!timed_out && status.exitstatus == 0, status.exitstatus,
299
+ stdout, stderr, nil, timed_out)
300
+ end
301
+ ```
302
+
303
+ ### Memoization discipline
304
+
305
+ Memoize each probe keyed on its full input set — for these probes that is
306
+ `(executable, modules/packages, timeout)`, since `SCOUT_TEST_PYTHON` or `PATH`
307
+ can change between calls in one process. Provide an explicit
308
+ `ScoutRig::Testing::Availability.reset!` and call it from test setup when the
309
+ environment is manipulated. Rescue `StandardError`, never `Exception`
310
+ (defect 3): a `SignalException` must not be cached as "unavailable".
311
+
312
+ ## Interpreter-selection matrix
313
+
314
+ scout-rig has **two Python routes** (per `user/PythonEnvironments.md`):
315
+
316
+ | Route | How the interpreter is chosen | Notes |
317
+ |---|---|---|
318
+ | Embedded (PyCall) | `ScoutPython.run*` reads `ENV['PYTHON']`, else PATH `python3`/`python`; `PyCall.init` **sets `ENV['PYTHONHOME']`** | Mutates process env; affects everything spawned afterwards |
319
+ | Subprocess (`ScoutPython.script` / `run_file` / `python_task`) | literal `'python'` from PATH + `PYTHONPATH` augmentation; **ignores `ENV['PYTHON']`** | Splits from the embedded route: the two can silently use different interpreters |
320
+
321
+ **Setting `ENV['PYTHON']` alone breaks subprocesses** ("Failed to import
322
+ encodings"): the subprocess gets a `PYTHONHOME` pointing at the embedded
323
+ interpreter while running a different one. The reliable recipe, which the
324
+ reference probes inherit for free by resolving one executable name and passing
325
+ it as argv:
326
+
327
+ > Put the chosen environment's `bin` directory **first on PATH**, and let each
328
+ > route resolve the same interpreter from PATH; set `SCOUT_TEST_PYTHON` (or
329
+ > `SCOUT_TEST_RSCRIPT`) to pin an absolute interpreter for tests.
330
+
331
+ Never export `PYTHONHOME` from test setup.
332
+
333
+ ## Motivation: the torch `test_binding` failure
334
+
335
+ scout-rig's suite is currently 9 tests, and `test_binding` hard-fails on stock
336
+ environments because it requires **torch**, which is not a declared dependency.
337
+ This is exactly the case a `python_modules?(:torch)` guard exists for: the test
338
+ should omit with `python_modules_reason(:torch)` when torch is absent, instead
339
+ of erroring. Its `test_helper.rb` has no interpreter selection or skip logic
340
+ today — add the `SCOUT_TEST_PYTHON`/PATH recipe above plus the guard.
341
+
342
+ "Guarded with `python_modules?`" means adding the omit and the reason message,
343
+ **not** adding torch to the gemspec or the README prerequisites.
344
+
345
+ ## Constraints
346
+
347
+ - Ordinary unit tests stay **offline**; these probes only execute local
348
+ interpreters and never touch the network.
349
+ - **Product-failure assertions must never become skips**: a probe may omit a
350
+ test when an optional dependency is genuinely absent; it must not convert a
351
+ regression in shipped code into a quiet omission. `rscript?`/`r_packages?`
352
+ are reference-only until an R integration exists — do not wire them into
353
+ unit tests.
354
+ - Keep the layer boundary: no endpoint/model/accelerator probes in scout-rig;
355
+ those live in scout-ai (see `testing-availability-scout-ai-handoff.md`).