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,487 @@
1
+ # Testing and Packaging
2
+
3
+ This document explains how scout-rig is built, packaged and tested: how the
4
+ Ruby test suite is laid out, what environment it needs, what `rake test`
5
+ actually does today, and how the two artifacts (Ruby gem and Python package)
6
+ are produced.
7
+
8
+ ## Audience
9
+
10
+ This page is intended for:
11
+
12
+ - ✓ Contributors who want to run or extend the test suite
13
+ - ✓ Maintainers cutting a gem or a Python package release
14
+ - ✓ CI authors who need to reproduce a known-good test environment
15
+ - ✗ Users looking for usage instructions (see [User Documentation](../user/))
16
+
17
+ ## When to use this
18
+
19
+ - You cloned the repository and want to check that it works before changing it.
20
+ - `rake test` failed and you need to know whether it is your machine or the
21
+ suite.
22
+ - You want to build the gem, regenerate the gemspec, or produce a Python wheel.
23
+ - You need to know which Python interpreter and packages the tests require.
24
+
25
+ ## Core concepts
26
+
27
+ ### Two packaging systems, one repository
28
+
29
+ scout-rig is dual-packaged:
30
+
31
+ | Side | Manifest | Tooling | Current version |
32
+ |------|----------|---------|-----------------|
33
+ | Ruby | `scout-rig.gemspec` (generated by Juwelier from the `Rakefile`) | `rake` + `juwelier` | `0.2.6` (from `VERSION`) |
34
+ | Python | `python/pyproject.toml` | `pip` / `setuptools` | `0.2.4` (drifted from the gem) |
35
+
36
+ The two version numbers are **not synchronized**: nothing in the repository
37
+ copies the gem `VERSION` into `pyproject.toml` or vice versa. At HEAD the gem
38
+ is `0.2.6` and the Python package says `0.2.4`; every release must be bumped
39
+ manually on both sides. Neither packaging path regenerates or verifies the
40
+ other, and neither regenerates or verifies `python/build/` or
41
+ `python/scout_rig.egg-info/` — those two directories are stale leftovers of an
42
+ earlier build that are byte-identical to `python/scout/` but whose egg-info
43
+ records `Version: 0.2.4`. They are ignored by `python/.gitignore` (`build/`,
44
+ `*.egg-info/`), so git never flags them; delete them before packaging so a
45
+ stale version string cannot leak into an artifact.
46
+
47
+ ### The gem is Juwelier-managed
48
+
49
+ `scout-rig.gemspec` is **generated** from the `Juwelier::Tasks` block in the
50
+ `Rakefile`. The file lists in the gemspec come from `git ls-files` at
51
+ generation time plus the patterns in `.document`. Consequences:
52
+
53
+ - The checked-in gemspec is a snapshot. It currently lists 53 files, which is
54
+ exactly the tracked tree minus `.gitignore`; new files are picked up only
55
+ after `rake gemspec:generate` (or `rake gemspec`) is re-run.
56
+ - The checked-in gemspec is **stale** and will not build as-is: it still lists
57
+ `doc/Python.md` and `doc/PythonWorkflow.md`, which were deleted when the
58
+ documentation was restructured. A plain `gem build scout-rig.gemspec` fails
59
+ with `Gem::InvalidSpecificationException: ["doc/Python.md",
60
+ "doc/PythonWorkflow.md"] are not files`. Running `rake gemspec` regenerates
61
+ the list (and also rewrites `s.rubygems_version` to the local RubyGems
62
+ version), after which the gemspec validates and `rake build` succeeds.
63
+ - The prebuilt `pkg/scout-rig-0.2.6.gem` predates the documentation revamp, so
64
+ it contains the *old* doc tree (`doc/StartHere.md` etc. from before the
65
+ restructure, and no `doc/Python.md`). `pkg/` is git-ignored, so it is never
66
+ in `git status`, but gems there are not refreshed automatically.
67
+
68
+ Runtime dependencies (from the gemspec): `pycall > 0`. Development
69
+ dependency: `juwelier ~> 2.1.0`. Two libraries the code uses are *not*
70
+ declared anywhere: `python-pickle` (required by
71
+ `lib/scout/python/script.rb` when loading pickle results) and `scout` /
72
+ `scout-gear` / `scout-essentials` (required by every entry point). They are
73
+ expected to be present in the development or deployment environment.
74
+
75
+ ### Test suite layout mirrors `lib/`
76
+
77
+ ```
78
+ test/
79
+ ├── test_helper.rb # shared setup: tmpdir, caches, teardown
80
+ │ # + require of the availability helpers
81
+ ├── scout/
82
+ │ ├── test_python.rb # ScoutPython core (mostly disabled, see below)
83
+ │ └── python/
84
+ │ ├── test_run.rb # empty: single test is commented out
85
+ │ ├── test_script.rb # script() facility + TSV round-trip
86
+ │ └── test_util.rb # numpy2ruby, tsv2df/df2tsv
87
+ └── scout/workflow/
88
+ ├── test_python.rb # python_task end-to-end
89
+ └── python/
90
+ └── test_task.rb # read_python_metadata + task behavior (annotation mapping contract incl. unsupported annotations, Optional/Annotated and postponed annotations (end-to-end + loud failure), Path caster, single-view input contracts with behavior, argv semantics incl. empty strings, literal-string flag, six-row refresh reconciliation, multi-task-file tracking, registration validation incl. native-collision refusal)
91
+ ```
92
+
93
+ plus `test/scout-rig/testing/test_availability.rb` for the availability
94
+ helpers described below.
95
+
96
+ `Rake::TestTask` in the `Rakefile` uses `test.pattern = 'test/**/test_*.rb'`
97
+ with `test.libs << 'lib' << 'test'`, so `rake test` runs every file matching
98
+ that pattern in one Ruby process, with the checkout's `lib/` first on
99
+ `$LOAD_PATH`. Individual files can also be run directly:
100
+
101
+ ```bash
102
+ ruby -Ilib:test test/scout/python/test_util.rb
103
+ ```
104
+
105
+ `test_helper.rb` unshifts `../lib` and the `test/` directory onto
106
+ `$LOAD_PATH`, isolates every test under `tmp/test_tmpdir`, and — since the
107
+ availability work — requires the opt-in test probes described below
108
+ (`require 'scout-rig/testing/availability'`) so any test file can gate
109
+ optional prerequisites. State setup and cleanup are detailed in the following
110
+ section. The suite is plain `Test::Unit`; there is no
111
+ interpreter selection in the helper and no `minitest`/`rspec`.
112
+
113
+ ### Shared scout-essentials testing helpers
114
+
115
+ `test/test_helper.rb` opts in to scout-essentials' test-only APIs with
116
+ `require 'scout/testing'` and `require 'scout/testing/scout_state'`. It
117
+ includes `Scout::Testing::Assertions` for `assert_equal_path` and activates
118
+ `Scout::Testing::State` per test. The shared State isolates its built-in
119
+ `TmpFile`, `Persist`, and `Open` settings and prior `Persist::MEMORY_CACHE`
120
+ contents, plus Rig's `Persist.cache_dir`, `Open.remote_cache_dir`, and
121
+ `SchedulerJob.batch_base_dir` through simple accessor bindings. Persist and
122
+ Open intentionally keep the same `var/cache` target. All are restored on
123
+ teardown (including when setup or a test raises).
124
+
125
+ Rig keeps some state local: `Log::ProgressBar.default_severity` is scalar
126
+ policy; `Workflow.directory` is a `Path` setting, and setting an individual
127
+ workflow's directory cascades to task directories; and
128
+ `Entity.entity_property_cache` has `Path` semantics. These are snapshotted
129
+ and restored locally, including prior instance-variable definedness. Task
130
+ memoization is isolated by swapping `Workflow.job_cache` for a new hash and
131
+ restoring the original hash reference; it is not cleared destructively. The
132
+ fixed `tmp/test_tmpdir` cleanup also remains Rig-owned.
133
+
134
+ The generic `Scout::Testing.create_tmpdir`, `remove_tmpdir`, and
135
+ `with_tmpdir(parent:, prefix:)` helpers are available for focused scratch
136
+ directories; `with_tmpdir` yields a String path and ensures it is removed.
137
+ The suite's shared `tmpdir` remains its existing fixed `Path` under
138
+ `tmp/test_tmpdir`, since its framework caches and setup depend on that common
139
+ root. Fixture lookup (`datadir_test` and `datafile_test`) also remains local:
140
+ the essentials fixture helpers use a different `test/fixtures` convention.
141
+
142
+ These are test-only requires, not production requires. The Rakefile declares
143
+ `scout-essentials` as a runtime dependency, and regenerating the Juwelier-managed
144
+ gemspec records it as `> 0`. That open-ended bound does not establish a release
145
+ containing these helper files: the inspected 1.9.1 release lacks them, and no
146
+ compatible released minimum was verified. Do not infer a minimum version from
147
+ the checkout's version number.
148
+
149
+ ### Test names prefixed with `_` are disabled, not skipped
150
+
151
+ Test::Unit discovers tests by method name. In this suite, disabling is done by
152
+ renaming (`def _test_python`, `def __test_run_threaded`), which removes the
153
+ method from the run entirely — it does not report as "omitted" or "pending".
154
+ The visible numbers therefore hide how much is actually untested:
155
+
156
+ - Most of `test/scout/test_python.rb` is `_`-disabled; only `test_binding`
157
+ runs (and it is torch-gated).
158
+ - `test/scout/python/test_run.rb`'s single method is `__`-disabled, so the
159
+ file contributes no tests.
160
+ - The other Ruby files are fully enabled; the count per file grows with the
161
+ code under test, so read the run summary rather than this document.
162
+ - `test/scout-rig/testing/test_availability.rb` covers the availability
163
+ helpers themselves (see below).
164
+ - `test/scout-rig/testing/test_test_support.rb` covers shared test-helper
165
+ setup, bound and local state restoration, and temporary-directory helpers.
166
+
167
+ The authoritative totals are whatever the current `rake test` run reports;
168
+ this document deliberately does not pin them.
169
+
170
+ ### What `rake test` does today
171
+
172
+ On a stock environment (system `python3`, `numpy` and `pandas` installed but
173
+ no `torch`) the suite completes and exits zero, reporting one **omission**:
174
+
175
+ ```
176
+ Omission: torch not importable in the embedded (PyCall) interpreter: <resolved
177
+ python>: missing Python modules: torch (torch: ModuleNotFoundError: No module
178
+ named 'torch'). Install torch or pin SCOUT_TEST_PYTHON to an interpreter that
179
+ has it. [test_binding(TestPython)]
180
+ <N> tests, <A> assertions, 0 failures, 0 errors, 0 pendings, 1 omissions, ...
181
+ ```
182
+
183
+ `<N>`/`<A>` stand for whatever the current run reports; they are shown as
184
+ placeholders because the count grows with the code under test.
185
+
186
+ `test_binding` in `test/scout/test_python.rb` is the only enabled test in that
187
+ file and it hard-requires `torch` (it calls `pyimport :torch` and
188
+ `pyfrom :torch, import: ["nn"]`). `torch` is not a declared dependency of
189
+ anything in the repository, so it is treated as an *optional test
190
+ prerequisite*: the test opens with an availability gate (see
191
+ [Optional-prerequisite gating with the availability helpers](#optional-prerequisite-gating-with-the-availability-helpers))
192
+ that omits with a reason exactly when torch is missing from the interpreter
193
+ the test would embed. Before the gate existed this same environment produced a
194
+ hard `PyCall::PyError` error instead.
195
+
196
+ Run the same suite with a `torch`-bearing interpreter on `PATH` and the test
197
+ runs for real, adding its assertions to the total; the omission disappears.
198
+
199
+ ```
200
+ PATH=/path/to/conda-env/bin:$PATH rake test
201
+ ```
202
+
203
+ The gate omits *only* the gated test: a probe that passes never
204
+ suppresses the `pyimport` that follows, so a broken PyCall binding still
205
+ fails the test.
206
+
207
+ ### Python interpreter selection for the suite
208
+
209
+ The tests exercise both execution routes, and they pick interpreters
210
+ differently — this is the single most confusing part of running the suite.
211
+
212
+ **In-process tests** (`test_util.rb`, `test_python.rb`) go through
213
+ `ScoutPython.run`, which calls `PyCall.init`. PyCall resolves the interpreter
214
+ via `ENV['PYTHON']` if set, otherwise the first `python3`/`python` on `PATH`,
215
+ then `dlopen`s the matching `libpython` into the Ruby process.
216
+
217
+ **Subprocess tests** (`test_script.rb`, `test_task.rb`,
218
+ `workflow/test_python.rb`) go through `ScoutPython.script` and
219
+ `ScoutPython.run_file`, which shell out to the literal command `python` with
220
+ `PYTHONPATH` set to `ScoutPython.paths`. They do **not** consult `ENV['PYTHON']`
221
+ and do not honour `PYTHONHOME`.
222
+
223
+ Because `PyCall.init` **sets** `ENV['PYTHONHOME']` to the home of whatever it
224
+ embedded, the two routes disagree exactly when `PYTHON` points somewhere other
225
+ than the `python` on `PATH`:
226
+
227
+ | Environment | Embedded interpreter | Subprocess `python` | Result |
228
+ |---|---|---|---|
229
+ | default | system 3.13 | system 3.13 | 1 error (`torch` missing) |
230
+ | `PYTHON=conda-python` only | conda 3.12 | system 3.13 under conda `PYTHONHOME` | 5 errors: subprocesses die with `Fatal Python error: Failed to import encodings module` |
231
+ | conda `bin` first on `PATH` | conda 3.12 | conda 3.12 | 9/9 pass |
232
+
233
+ Setting `PYTHON` alone is therefore **not** enough: the subprocess route needs
234
+ the same interpreter's `bin` on `PATH`. The reliable recipe is one line:
235
+
236
+ ```bash
237
+ PATH=/path/to/env/bin:$PATH rake test
238
+ ```
239
+
240
+ This makes both routes use the same interpreter, and it is also the
241
+ configuration `LD_LIBRARY_PATH` advice in
242
+ [Python Environments](PythonEnvironments.md) assumes.
243
+
244
+ ### Python package prerequisites per test file
245
+
246
+ | Test file | Route | Needs |
247
+ |---|---|---|
248
+ | `test/scout-rig/testing/test_availability.rb` | subprocess (probes + fakes) | nothing optional: fakes only; two tests omit when no real interpreter exists |
249
+ | `test/scout/python/test_util.rb` | in-process (`PyCall`) | `numpy`, `pandas` (both via `pyimport`; both optional, gated) |
250
+ | `test/scout/test_python.rb` | in-process | `torch` (only in `test_binding`; optional, gated) |
251
+ | `test/scout/python/test_script.rb` | subprocess | `numpy`, `pandas`, and `python/scout` importable via `PYTHONPATH` (handled automatically) |
252
+ | `test/scout/python/test_task.rb` | subprocess | stdlib only (`typing`) |
253
+ | `test/scout/workflow/test_python.rb` | subprocess | `numpy`, `pandas` (imports `scout`, which imports pandas) |
254
+
255
+ The Python-side package also needs the Ruby CLI (`rbbt`/`rbbt_exec.rb`) on
256
+ `PATH` for workflow execution, but no test in this suite exercises that path —
257
+ the closest thing is `python/test.py`, an ad-hoc script that shells out to the
258
+ `Baking` example workflow and requires it installed. It is not run by any rake
259
+ task.
260
+
261
+ ### Optional-prerequisite gating with the availability helpers
262
+
263
+ `test/test_helper.rb` requires scout-rig's opt-in availability probes, so
264
+ every test file can use them:
265
+
266
+ ```ruby
267
+ require 'scout-rig/testing/availability'
268
+ ```
269
+
270
+ The helpers run real interpreters as subprocesses through
271
+ `Scout::Testing::Availability.run_command`, with a bounded timeout, and decide
272
+ on **exit status** alone. They never download or install anything, never
273
+ initialize PyCall, and never mutate `PYTHON`/`PATH` (the pins below are read
274
+ only). Everything needed for them ships with the gem plus scout-essentials;
275
+ there are no new gem dependencies.
276
+
277
+ The complete surface (module functions on `ScoutRig::Testing::Availability`;
278
+ `ScoutRig::Testing::Helpers` is the same module, for `include`-style use):
279
+
280
+ | Method | Returns |
281
+ |---|---|
282
+ | `python?(executable: nil, route: :subprocess, timeout: nil)` | `true` iff the selected Python exists **and runs** (a sanity probe must exit 0); `false` otherwise. PATH existence alone is not enough. |
283
+ | `python_modules?(*modules, executable: nil, route: :subprocess, timeout: nil)` | `true` iff every named module imports in the selected interpreter. An empty list is vacuously true **once an interpreter was resolved**. |
284
+ | `python_modules_reason(*modules, ...)` | `nil` on success; otherwise one concise string: the resolved executable path, the missing/unloadable module names, and the condensed exception text from stderr. |
285
+ | `rscript?(executable: nil, timeout: nil)` | `true` iff the selected Rscript exists and runs (sanity probe exits 0). |
286
+ | `r_packages?(*packages, executable: nil, timeout: nil)` | `true` iff every named package **loads** (`requireNamespace`), not merely appears in an installation list. |
287
+ | `r_packages_reason(*packages, ...)` | `nil` on success; otherwise the resolved executable path, the missing package names (stdout first), then the stderr tail. |
288
+ | `embedded_python` | The interpreter the embedded route **would** use, without running anything: `ENV['PYTHON']` if set, else the first `python3`/`python` on PATH. `nil` when neither exists. |
289
+ | `subprocess_python` | The interpreter the subprocess route uses: the literal command `python` from PATH (`ENV['PYTHON']` is never consulted there). `nil` when PATH has no `python`. |
290
+ | `python_routes_divergence_reason` | `nil` when both routes resolve to the same interpreter (symlinks canonicalized); otherwise one sentence naming both resolutions, the `ENV['PYTHON']`/PATH cause, and that no probe validates both routes. |
291
+ | `reset!` | Clears all memoized probe results (returns `nil`). |
292
+
293
+ Module and package names travel as **argv** to fixed probe sources; they are
294
+ never interpolated into code, so a name like `sys\nimport os` is treated as one
295
+ literal module name and nothing extra executes. Arguments and symbols are both
296
+ accepted for names (`python_modules?(:torch)`).
297
+
298
+ Selection precedence, first match wins:
299
+
300
+ 1. the `executable:` keyword (explicit, overrides everything);
301
+ 2. `ENV['SCOUT_TEST_PYTHON']` (Python) / `ENV['SCOUT_TEST_RSCRIPT']` (R) —
302
+ **test-only pins defined by this library**; they affect probing only and
303
+ have no production effect;
304
+ 3. the `route:` default — `:subprocess` (the default) resolves
305
+ `subprocess_python`, `:embedded` resolves `embedded_python`.
306
+
307
+ Because resolution re-runs on every call, mid-process `ENV`/`PATH` changes are
308
+ honoured. Definitive outcomes (success / missing module / missing package) are
309
+ memoized on `[resolved executable, sorted names, timeout, route]`; **timeouts
310
+ and launch errors are never memoized**. Call `reset!` when you change
311
+ `SCOUT_TEST_PYTHON`, `SCOUT_TEST_RSCRIPT`, `PATH` or `ENV['PYTHON']` and want
312
+ a provably fresh probe. `python?`/`python_modules?` never inspect output, only
313
+ exit status. An unknown `route:` raises `ArgumentError`.
314
+
315
+ **Route semantics.** The two production routes select interpreters
316
+ independently, and a probe validates only the route it ran:
317
+
318
+ - `:embedded` mirrors `PyCall.init` — `ENV['PYTHON']` if set, else the first
319
+ `python3`/`python` on PATH. It is a **prediction**: probing it runs that
320
+ interpreter as a subprocess; it does not prove that `libpython` can be
321
+ `dlopen`ed into the Ruby process.
322
+ - `:subprocess` mirrors `ScoutPython.script`/`run_file`/`python_task` — the
323
+ literal `python` from PATH, ignoring `ENV['PYTHON']`.
324
+ - Consequently a passing `:subprocess` probe says nothing about the embedded
325
+ route and vice versa. `python_routes_divergence_reason` reports the
326
+ disagreement (and deliberately ignores the `SCOUT_TEST_PYTHON` pin, which
327
+ hides divergences from probes).
328
+
329
+ Because `PyCall.init` **sets** `ENV['PYTHONHOME']` to the home of whatever it
330
+ embedded, setting `PYTHON` alone can leave the subprocess route broken. The
331
+ recommended practice is unchanged from the section above: put the chosen
332
+ environment's `bin` first on `PATH` (and unset `PYTHON`), optionally pinning
333
+ `SCOUT_TEST_PYTHON` for probe-only reproducibility.
334
+
335
+ **Module availability is not PyCall validation.** `python_modules?('torch',
336
+ route: :embedded)` answers "does torch import in the interpreter the embedded
337
+ route would pick, run as a subprocess". It does not exercise the in-process
338
+ bridge, so a pass cannot cover a broken native binding. That is exactly why
339
+ the gate pattern below puts the probe in the `omit` condition only:
340
+
341
+ ```ruby
342
+ def test_binding
343
+ # torch is OPTIONAL (no lib/ code and no manifest requires it).
344
+ omit(
345
+ "torch not importable in the embedded (PyCall) interpreter: " \
346
+ "#{ScoutRig::Testing::Availability.python_modules_reason('torch', route: :embedded)}. " \
347
+ 'Install torch or pin SCOUT_TEST_PYTHON to an interpreter that has it.'
348
+ ) unless ScoutRig::Testing::Availability.python_modules?('torch', route: :embedded)
349
+
350
+ ScoutPython.binding_run do
351
+ pyimport :torch # unconditional: still fails if the probe lied
352
+ end
353
+ end
354
+ ```
355
+
356
+ **Gating recipe for dependent packages:**
357
+
358
+ 1. Classify the prerequisite. If scout-rig's documented functionality
359
+ *requires* it (for example the `scout` Python package, which is scout-rig's
360
+ own packaged code, or pandas, which `python/pyproject.toml` declares), do
361
+ **not** gate it — a missing required dependency is a failure worth seeing.
362
+ 2. If it is optional (required by no `lib/` code and no manifest, like `torch`
363
+ or `numpy` in the tests above), put the gate at the **top of the test
364
+ method** and let the body run unconditionally when the probe passes.
365
+ 3. Pick the route that matches how the test uses the interpreter:
366
+ `route: :embedded` for in-process PyCall tests, the default `:subprocess`
367
+ for `script()`/`run_file`/`python_task` tests.
368
+ 4. Include the reason string in the `omit` message; it already names the
369
+ module, the resolved executable and a remedy.
370
+
371
+ The helpers themselves are tested by `test/scout-rig/testing/test_availability.rb`
372
+ (fakes only; two tests additionally omit on machines with no real
373
+ interpreter at all, which keeps the file green everywhere).
374
+
375
+ ### Coverage of the two routes (verified at HEAD)
376
+
377
+ There is **no Python-side test infrastructure at all**: no `[tool.pytest]`
378
+ section in `pyproject.toml`, no `tests/` directory under `python/`, and no rake
379
+ task that runs Python tests.
380
+
381
+ On the Ruby side, the round-trip coverage picture that `doc/Improvements.md`
382
+ item M3 describes as missing is now partially present:
383
+
384
+ - Ruby → Python → Ruby through a **Python workflow task** *is* covered:
385
+ `test/scout/workflow/test_python.rb#test_file` writes a `scout.task`
386
+ function to a temp file, registers it with `python_task`, runs the job and
387
+ asserts on the returned string.
388
+ - **TSV → DataFrame → TSV** *is* covered: `test/scout/python/test_util.rb`
389
+ round-trips a list-type TSV through `tsv2df`/`df2tsv` and asserts equality.
390
+ - **`script()` with a returned value** *is* covered, including the TSV
391
+ injection case (`test_script.rb`).
392
+ - Still missing: multi-function files, the remote workflow client, threaded
393
+ execution combined with GC, and the `run_direct`/`run_threaded`/`iterate`
394
+ families, which are all `_`-disabled.
395
+
396
+ ### Ruby dependencies for running the suite
397
+
398
+ There is no `Gemfile`; dependencies come from the installed gem set:
399
+
400
+ - `pycall` (runtime, provides `PyCall`)
401
+ - `python-pickle` (undocumented, used by `script()` result loading)
402
+ - `scout-gear` and `scout-essentials` (provide `scout`, `TSV`, `CMD`, `TmpFile`,
403
+ `Workflow`)
404
+ - `rake` and `juwelier` for the rake tasks (`check_dependencies` will complain
405
+ about the `juwelier ~> 2.1.0` pin even when a newer juwelier is installed,
406
+ since the installed 2.4.9 does not satisfy it — a false alarm)
407
+
408
+ The `Rakefile` also defines a `rake simplecov` task, but it only sets
409
+ `ENV['COVERAGE']` and re-runs `:test`; no `simplecov` gem is required anywhere,
410
+ so the task is a no-op wrapper.
411
+
412
+ ## Rake task reference
413
+
414
+ From `rake -T` at HEAD:
415
+
416
+ | Task | Effect (verified) |
417
+ |------|-------------------|
418
+ | `rake test` | Runs the suite in one process; exits non-zero if any test errors (see above). |
419
+ | `rake simplecov` | Sets `COVERAGE=true` and executes `:test`; no coverage report is produced. |
420
+ | `rake build` | Regenerates nothing; builds `pkg/scout-rig-<VERSION>.gem` from the gemspec. Fails while the gemspec is stale. |
421
+ | `rake gemspec` | Regenerates `scout-rig.gemspec` from the `Rakefile` + `git ls-files` and validates it. |
422
+ | `rake gemspec:generate` | Regenerate only. |
423
+ | `rake gemspec:validate` | Validate the on-disk gemspec (currently **passes**, despite listing deleted files, because that check is not part of validation). |
424
+ | `rake gemspec:debug` | Print the gemspec Juwelier would generate. |
425
+ | `rake gemspec:release` | Regenerate, validate, commit and push — do not use casually. |
426
+ | `rake version` | Print the version from `VERSION` (`0.2.6`). |
427
+ | `rake version:bump:{major,minor,patch}` | Bump `VERSION` and regenerate the gemspec. |
428
+ | `rake version:write` | Write an explicit version. |
429
+ | `rake rdoc` / `rerdoc` / `rdoc:coverage` | Build RDoc HTML into `rdoc/` from `README*` + `lib/**/*.rb` (per `.document`). At HEAD: 58 methods, 0.00% documented. `rdoc/` is **not** git-ignored. |
430
+ | `rake clean` / `rake clobber` | Remove `rdoc/` and the built gems in `pkg/`; `pkg/` itself stays (it is ignored). |
431
+ | `rake check_dependencies` | Reports missing/unsatisfied dev dependencies. |
432
+
433
+ ## Workflow
434
+
435
+ ### Run the whole suite
436
+
437
+ ```bash
438
+ PATH=/path/to/python-env/bin:$PATH rake test
439
+ ```
440
+
441
+ On a machine without `torch` the summary shows `1 omissions` (the gated
442
+ `test_binding`, with a reason naming torch and the resolved interpreter)
443
+ rather than an error; with `torch` present it runs for real and a broken
444
+ binding still fails. Take the reported totals from the run, not from this
445
+ document.
446
+
447
+ The interpreter-selection divergence and its one-line remedy are described in
448
+ [Python interpreter selection for the suite](#python-interpreter-selection-for-the-suite)
449
+ and
450
+ [Optional-prerequisite gating with the availability helpers](#optional-prerequisite-gating-with-the-availability-helpers).
451
+
452
+ ### Run one file
453
+
454
+ ```bash
455
+ ruby -Ilib:test test/scout/python/test_util.rb
456
+ ```
457
+
458
+ ### Before building a gem
459
+
460
+ ```bash
461
+ rake gemspec # regenerate the file list; the checked-in one is stale
462
+ rake build # writes pkg/scout-rig-<VERSION>.gem
463
+ ```
464
+
465
+ ### Before packaging the Python side
466
+
467
+ ```bash
468
+ rm -rf python/build python/scout_rig.egg-info # stale, records 0.2.4
469
+ # then, from python/:
470
+ pip install -e . # or python -m build
471
+ ```
472
+
473
+ ## See also
474
+
475
+ - [Python Environments](PythonEnvironments.md) — how interpreter selection,
476
+ `PYTHON`, `PATH` and `LD_LIBRARY_PATH` interact; why an environment that
477
+ works standalone can still break when embedded.
478
+ - [Running Python from Ruby](RunningPythonFromRuby.md) — the in-process
479
+ execution modes the suite exercises.
480
+ - [Scripting Python](ScriptingPython.md) — the subprocess `script()` facility.
481
+ - [Architecture](../developer/Architecture.md) — module map and dependencies.
482
+
483
+ ---
484
+ *Verified with Ruby 3.3.1, pycall 1.5.2, Python 3.13.3 (system) on a
485
+ torch-less machine. Suite totals are intentionally not pinned here — read
486
+ them from the run. The availability helpers are at
487
+ `lib/scout-rig/testing/availability.rb`.*
@@ -1,3 +1,5 @@
1
+ require 'shellwords'
2
+
1
3
  module ScoutPython
2
4
  def self.ruby2python(object)
3
5
  case object
@@ -108,8 +110,15 @@ if result is not None:
108
110
  end
109
111
  end
110
112
 
111
- def self.run_file(file, arg_str)
113
+ def self.run_file(file, arg_str, env: {})
112
114
  path_env = ScoutPython.paths * ":"
113
- CMD.cmd("env PYTHONPATH=#{path_env} python '#{file}' #{arg_str}")
115
+ # Non-Step calls must not inherit a stale sidecar from the parent process.
116
+ env_assignments = env.map { |name, value| "#{name}=#{Shellwords.escape(value.to_s)}" }.join(' ')
117
+ command = 'env'
118
+ command << ' -u SCOUT_JOB_FILES_DIR'
119
+ command << " PYTHONPATH=#{Shellwords.escape(path_env)}"
120
+ command << " #{env_assignments}" unless env_assignments.empty?
121
+ command << " python #{Shellwords.escape(file.to_s)} #{arg_str}"
122
+ CMD.cmd(command)
114
123
  end
115
124
  end
@@ -1,4 +1,14 @@
1
1
  module PythonWorkflow
2
+ # Build the Python CLI argv for one invocation.
3
+ #
4
+ # Contract (see doc/user/DefiningPythonTasks.md):
5
+ # - Array values stay one argv word per element; a String value for a list
6
+ # parameter is split on commas ONLY. Existing files are never silently
7
+ # read: pass File.readlines(path, chomp: true) yourself when you want
8
+ # that, or use a Scout :array input whose file semantics are explicit.
9
+ # - Scalar values are passed as written. An empty string is a real value:
10
+ # `--x ''` is ALWAYS emitted so '' is distinguishable from a missing
11
+ # input. Only nil is skipped (nil means "not provided").
2
12
  def self.build_python_argv(py_params, values)
3
13
  argv = []
4
14
  py_params.each do |p|
@@ -15,26 +25,7 @@ module PythonWorkflow
15
25
 
16
26
  flag = "--#{name}"
17
27
  if ptype.start_with?('list[')
18
- # Accept several input formats for lists:
19
- # - Ruby Array
20
- # - Comma-separated string: "a,b,c"
21
- # - Path to a file: "file.txt" -> read lines
22
- items = []
23
- if val.is_a?(String)
24
- # If file exists, read lines
25
- if File.exist?(val)
26
- items = File.readlines(val, chomp: true)
27
- elsif val.include?(',')
28
- items = val.split(',').map(&:strip)
29
- else
30
- items = [val]
31
- end
32
- elsif val.respond_to?(:to_ary)
33
- items = Array(val).map(&:to_s)
34
- else
35
- items = [val.to_s]
36
- end
37
-
28
+ items = python_list_items(val)
38
29
  # pass flag once followed by all items (argparse with nargs='+' expects this)
39
30
  argv << flag
40
31
  items.each do |x|
@@ -47,13 +38,32 @@ module PythonWorkflow
47
38
  argv << flag if val
48
39
  end
49
40
  else
50
- # For scalar inputs: if given a file path and the file exists, pass the path
51
- # as-is (the Python side can decide how to handle it). Keep quoting to
52
- # preserve spaces when later shell-joining.
41
+ # Scalar: always emit the flag, including for '' — an empty string is
42
+ # a real value and must stay distinguishable from a missing input.
43
+ # Only nil (skipped above) means "not provided".
53
44
  argv << flag
54
45
  argv << val.to_s
55
46
  end
56
47
  end
57
48
  argv
58
49
  end
50
+
51
+ # A list parameter accepts an Array (one argv word per element, literal) or
52
+ # a String (split on commas, or a single item). Filenames are never
53
+ # reinterpreted as file contents at the bridge.
54
+ def self.python_list_items(val)
55
+ items = []
56
+ if val.is_a?(String)
57
+ if val.include?(',')
58
+ items = val.split(',').map(&:strip)
59
+ else
60
+ items = [val]
61
+ end
62
+ elsif val.respond_to?(:to_ary)
63
+ items = Array(val).map(&:to_s)
64
+ else
65
+ items = [val.to_s]
66
+ end
67
+ items
68
+ end
59
69
  end