scout-rig 0.2.5 → 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 (52) 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/python/util.rb +9 -0
  25. data/lib/scout/workflow/python/inputs.rb +33 -23
  26. data/lib/scout/workflow/python/task.rb +219 -18
  27. data/lib/scout/workflow/python.rb +236 -9
  28. data/lib/scout-rig/testing/availability.rb +608 -0
  29. data/python/README.md +51 -0
  30. data/python/scout/__init__.py +2 -0
  31. data/python/scout/runner.py +193 -29
  32. data/python/scout/task_errors.py +6 -0
  33. data/research/00_scope_and_themes.md +131 -0
  34. data/research/data-conversion-and-scripting-analysis.md +209 -0
  35. data/research/design-philosophy-analysis.md +246 -0
  36. data/research/python-helper-package-analysis.md +272 -0
  37. data/research/pythonworkflow-analysis.md +199 -0
  38. data/research/scoutpython-bridge-analysis.md +185 -0
  39. data/research/synthesis-report.md +109 -0
  40. data/research/testing-availability-baseline.md +1625 -0
  41. data/research/testing-availability-final-report.md +500 -0
  42. data/research/validation-report.md +149 -0
  43. data/scout-rig.gemspec +35 -5
  44. data/test/scout/python/test_util.rb +13 -0
  45. data/test/scout/test_python.rb +10 -0
  46. data/test/scout/workflow/python/test_task.rb +1119 -1
  47. data/test/scout-rig/testing/test_availability.rb +495 -0
  48. data/test/scout-rig/testing/test_test_support.rb +166 -0
  49. data/test/test_helper.rb +96 -19
  50. metadata +47 -4
  51. data/doc/Python.md +0 -482
  52. data/doc/PythonWorkflow.md +0 -163
@@ -0,0 +1,272 @@
1
+ # Python `scout` Package Analysis
2
+
3
+ > **Non-normative.** Investigation artifact.
4
+ >
5
+ > **Status note (2026-09-12):** written before the verification campaign.
6
+ > The authoritative account of the package is `python/README.md`,
7
+ > `doc/user/DrivingWorkflowsFromPython.md` and
8
+ > `doc/developer/PythonTaskRunnerInternals.md`, with evidence in the
9
+ > Cortex artifact `scout-rig/subsys/python-package.md`. This analysis
10
+ > predates the verified finding that `python/scout/workflow.py` shadows
11
+ > the `python/scout/workflow/` package, which breaks the remote client
12
+ > import on Python 3.12/3.13.
13
+
14
+ ## Overview
15
+
16
+ The Python `scout` package (`python/scout/`) is the Python-side companion
17
+ to scout-rig. It provides:
18
+
19
+ 1. **TSV I/O** — Read and write Scout-style TSV files as pandas DataFrames.
20
+ 2. **Workflow execution** — Run Scout workflows from Python via the CLI.
21
+ 3. **Task definition** — Register Python functions as Scout-compatible tasks
22
+ via `scout.task`.
23
+ 4. **Remote workflows** — Interact with Scout REST workflow servers.
24
+
25
+ ## Module layout
26
+
27
+ ```
28
+ scout/
29
+ ├── __init__.py (231 lines) # TSV I/O, cmd, run_job
30
+ ├── runner.py (536 lines) # scout.task, describe_function, CLI dispatch
31
+ ├── workflow.py (64 lines) # Workflow, Step (local)
32
+ └── workflow/
33
+ └── remote.py (103 lines) # RemoteWorkflow, RemoteStep (HTTP)
34
+ ```
35
+
36
+ ## scout/__init__.py — Core utilities
37
+
38
+ ### cmd(ruby_string)
39
+
40
+ Executes Ruby code via `rbbt_exec.rb`:
41
+
42
+ ```python
43
+ def cmd(cmd=None):
44
+ return subprocess.run('rbbt_exec.rb', input=cmd.encode('utf-8'),
45
+ capture_output=True).stdout.decode()
46
+ ```
47
+
48
+ This is the foundational bridge: the entire `scout` Python package shells out
49
+ to the Ruby Scout CLI. Used by `libdir()`, `path()`, `Workflow.tasks()`,
50
+ `Step.info()`, etc.
51
+
52
+ **Note:** The command is hardcoded as `rbbt_exec.rb`. In Scout-based
53
+ installs, the binary may be named `scout` or `scout_exec`. This is a
54
+ potential portability issue (see Improvements).
55
+
56
+ ### libdir()
57
+
58
+ ```python
59
+ def libdir():
60
+ return cmd('puts Rbbt.find(:lib)').rstrip()
61
+ ```
62
+
63
+ Returns the Ruby library directory via the `Rbbt.find(:lib)` Path lookup.
64
+
65
+ ### add_libdir()
66
+
67
+ Prepends `libdir() + '/python'` to `sys.path`, making the `scout` Python
68
+ package discoverable when running from Python scripts that aren't already
69
+ in the path.
70
+
71
+ ### path / read
72
+
73
+ `path(subdir, base_dir)` resolves paths using Scout's `Rbbt` conventions:
74
+ - `base_dir='base'` → `~/.rbbt`
75
+ - `base_dir='lib'` → `libdir()`
76
+ - default: tries `lib` first, then `base`
77
+
78
+ `read(subdir, base_dir)` reads a file at the resolved path.
79
+
80
+ ### TSV I/O
81
+
82
+ The TSV reading functions parse Scout-style TSV headers:
83
+
84
+ - **Preamble line** (`#:key=value#...`): Parsed into a dict (e.g., type, sep).
85
+ - **Header line** (`#Key\tField1\tField2`): Extracts field names and key field.
86
+ - **Flat TSV**: Single-column files with custom separator.
87
+
88
+ Functions:
89
+ - `tsv_header(filename)` — Parse header metadata.
90
+ - `tsv_preamble(line)` — Parse preamble key=value entries.
91
+ - `tsv_pandas(filename, **kwargs)` — Read TSV into pandas DataFrame, respecting
92
+ header metadata.
93
+ - `tsv(*args, **kwargs)` — Alias for `tsv_pandas`.
94
+ - `save_tsv(filename, df, key=None)` — Write DataFrame to Scout-style TSV.
95
+
96
+ **Header format example:**
97
+ ```
98
+ #:type=:list#:sep=:
99
+ #Key Field1 Field2
100
+ k1 v1 v2
101
+ ```
102
+
103
+ ### save_job_inputs(data)
104
+
105
+ Materializes Python values into files in a temp directory, suitable for
106
+ Scout's `--load_inputs` CLI option:
107
+
108
+ | Python type | File extension | Format |
109
+ |-------------------|----------------|----------------------------|
110
+ | `str` | `.txt` | Raw string |
111
+ | `bool` | (none) | `true` or `false` |
112
+ | `int` / `float` | (none) | String representation |
113
+ | `pandas.DataFrame`| `.tsv` | Scout-style TSV (via save_tsv) |
114
+ | `list` / `ndarray`| `.list` | Newline-separated |
115
+
116
+ **Observation:** The file naming uses the input name directly (e.g., input
117
+ `add_blueberries` becomes file `add_blueberries` with no extension for bool,
118
+ `.txt` for str). Scout's `--load_inputs` expects this convention.
119
+
120
+ ### run_job(workflow, task, ...)
121
+
122
+ Shells out to the Scout CLI:
123
+
124
+ ```python
125
+ cmd = ['rbbt', 'workflow', 'task', workflow, task,
126
+ '--jobname', jobname, '--load_inputs', inputs_dir, '--nocolor']
127
+ ```
128
+
129
+ Options:
130
+ - `fork=True` → `--fork --detach` (async execution).
131
+ - `exec=True` → `--exec`.
132
+ - `clean` → `--clean` or `--recursive_clean`.
133
+
134
+ Returns `proc.stdout.strip()`. On error, raises `RuntimeError` with stderr.
135
+
136
+ **Note:** Hardcoded as `rbbt` command. See portability note above.
137
+
138
+ ## scout/runner.py — Task definition
139
+
140
+ This is the largest and most complex file (536 lines). It provides:
141
+
142
+ ### describe_function(func)
143
+
144
+ Introspects a Python function's signature and docstring to produce a
145
+ metadata dict:
146
+
147
+ ```json
148
+ {
149
+ "name": "hello",
150
+ "description": "Greet a user.",
151
+ "returns": "string",
152
+ "params": [...]
153
+ }
154
+ ```
155
+
156
+ Key logic:
157
+ - `_python_type_to_string(ann)` — Maps Python type annotations to Scout type strings.
158
+ - `_parse_numpy_params(doc)` — Parses Google-style `Args:` sections (preferred)
159
+ or NumPy-style `Parameters` sections (fallback).
160
+ - `_extract_description(docstring)` — Extracts the docstring preamble (everything
161
+ before `Args:`/`Parameters`/etc.).
162
+ - `_required_from_default(default, ann)` — Determines if a parameter is required
163
+ (no default, not `Optional[T]`).
164
+
165
+ ### Type annotation mapping
166
+
167
+ | Python annotation | Scout type string |
168
+ |--------------------------|-------------------|
169
+ | `str` / `bytes` | `string` / `binary` |
170
+ | `int` | `integer` |
171
+ | `float` | `float` |
172
+ | `bool` | `boolean` |
173
+ | `pathlib.Path` | `path` |
174
+ | `List[str]` | `list[string]` |
175
+ | `List[int]` | `list[integer]` |
176
+ | `Optional[T]` (= `T | None`) | Type of `T` (required=False) |
177
+ | No annotation | `string` |
178
+
179
+ ### scout.task(func)
180
+
181
+ The `task` function serves two purposes:
182
+ 1. Introspects the function and stores metadata via `func.__scout_meta__`.
183
+ 2. Registers the function in `_SCOUT_TASK_REGISTRY`.
184
+
185
+ If the defining module is `__main__` (the file is run as a script), it
186
+ registers an `atexit` handler that handles CLI dispatch.
187
+
188
+ ### CLI dispatch (_scout_run_deferred)
189
+
190
+ When a Python file with `scout.task` is run as a script:
191
+
192
+ 1. If `--scout-metadata` in argv: print JSON of all registered metas and exit.
193
+ 2. If `-h`/`--help`: show argparse help for the selected function.
194
+ 3. Otherwise: parse args via argparse and call the function.
195
+
196
+ For multi-function files, the first positional argument selects the function.
197
+ If no positional arg is given, the last registered task is used as default.
198
+
199
+ ### Output serialization (_run_cli)
200
+
201
+ The function's return value is serialized to stdout:
202
+ - `bytes` → raw to stdout.buffer.
203
+ - `str/int/float/bool/None` → `print()`.
204
+ - `list/tuple` → newline-separated items.
205
+ - Other → JSON dump (`json.dumps(result, default=str)`).
206
+
207
+ This serialization is what the Ruby side decodes in `python_task` execution.
208
+
209
+ ## scout/workflow.py — Local workflow wrapper
210
+
211
+ ### Workflow(name)
212
+
213
+ - `tasks()` → list of task names (via Ruby `Workflow.require_workflow(name).tasks.keys`).
214
+ - `task_info(name)` → JSON string from Ruby.
215
+ - `run(task, **kwargs)` → calls `run_job`, returns stdout.
216
+ - `fork(task, **kwargs)` → calls `run_job` with `fork=True`, returns `Step(path)`.
217
+
218
+ ### Step(path)
219
+
220
+ - `info()` → Ruby `Step.load(path).info.to_json`.
221
+ - `status()`, `done()`, `error()`, `aborted()` → convenience accessors.
222
+ - `join()` → poll until done/error/aborted (1s sleep).
223
+ - `load()` → Ruby `Step.load(path).load.to_json` → JSON parse.
224
+
225
+ ## scout/workflow/remote.py — HTTP workflow client
226
+
227
+ ### RemoteWorkflow(url)
228
+
229
+ - `init_remote_tasks()` → GET the workflow URL, parse task list.
230
+ - `task_info(name)` → GET `url/name/info`.
231
+ - `job(task, **kwargs)` → POST `url/task` with params, returns `RemoteStep`.
232
+
233
+ ### RemoteStep(url)
234
+
235
+ - `info()` → GET `url/info` as JSON.
236
+ - `status()`, `done()`, `error()`, `running()`, `wait()`.
237
+ - `raw()` → GET result as raw bytes.
238
+ - `json()` → GET result as JSON.
239
+
240
+ Uses the `_format` query parameter (`json` or `raw`) to control response format.
241
+
242
+ ## Key findings
243
+
244
+ 1. **The `scout` package is a thin CLI wrapper** — It shells out to `rbbt` /
245
+ `rbbt_exec.rb` for all Ruby-side operations. No persistent Ruby process
246
+ is kept alive.
247
+
248
+ 2. **`scout.task` is both a decorator and a registration mechanism** — It
249
+ works as `@scout.task` (decorator) or `scout.task(func)`. The metadata
250
+ extraction is the same either way.
251
+
252
+ 3. **Multi-function CLI dispatch is deferred to atexit** — This ensures all
253
+ functions in the file are registered before dispatch. Clever but
254
+ potentially confusing for debugging.
255
+
256
+ 4. **Hardcoded command names** — `rbbt_exec.rb` and `rbbt` are hardcoded.
257
+ Scout installs may use `scout` or `scout_exec` instead. This is a
258
+ portability concern.
259
+
260
+ 5. **`save_job_inputs` is a bridge for `--load_inputs`** — It materializes
261
+ Python values into the file format Scout expects for inputs. This is
262
+ essential for the Python-side `run_job` to work correctly.
263
+
264
+ 6. **RemoteWorkflow is minimal** — It's a thin HTTP client that speaks the
265
+ Scout REST API. No authentication, no retry, no timeout configuration.
266
+
267
+ 7. **Google-style docstrings preferred** — The metadata extractor prefers
268
+ Google-style `Args:` sections over NumPy-style `Parameters`. This is for
269
+ better interoperability with LLM tool schemas.
270
+
271
+ 8. **`save_inputs` in workflow.py is a no-op** — `def save_inputs(directory,
272
+ inputs, types): return`. This is dead code that was never implemented.
@@ -0,0 +1,199 @@
1
+ # PythonWorkflow Analysis
2
+
3
+ > **Non-normative.** Investigation artifact.
4
+ >
5
+ > **Status note (2026-09-12):** written before the verification campaign;
6
+ > its `err`-variable observation corresponds to Improvements B1 (verified:
7
+ > the `raise` is unreachable because `ProcessFailed` fires first). The
8
+ > authoritative account of metadata discovery, type mapping and CLI
9
+ > generation is `doc/developer/PythonWorkflowInternals.md`, with evidence
10
+ > in the Cortex artifact `scout-rig/subsys/pythonworkflow.md`.
11
+
12
+ ## Overview
13
+
14
+ PythonWorkflow (`lib/scout/workflow/python.rb` + sub-files) is a Ruby module
15
+ that lets workflow authors define Scout tasks whose logic is implemented in
16
+ Python. The Python function's signature (type hints, defaults, docstring)
17
+ is introspected at workflow definition time to automatically create the
18
+ corresponding Scout inputs and task declarations.
19
+
20
+ ## Architecture
21
+
22
+ ```
23
+ PythonWorkflow (lib/scout/workflow/python.rb)
24
+ ├── load_directory # Load all .py files from a directory
25
+ ├── inputs.rb
26
+ │ └── build_python_argv # Build CLI args from Ruby values
27
+ └── task.rb
28
+ ├── read_python_metadata # Run python file --scout-metadata
29
+ ├── map_returns # Python return type → Scout return type
30
+ ├── map_param # Python param → Scout input
31
+ └── python_task # Define a Scout task from a Python file
32
+ ```
33
+
34
+ ## Lifecycle: From Python function to Scout task
35
+
36
+ ### Phase 1: Metadata discovery (workflow definition time)
37
+
38
+ When you call `python_task :hello`, the following happens:
39
+
40
+ 1. Locate the Python file:
41
+ - If `file:` option is given, use it directly.
42
+ - Otherwise, look in `python_task_dir[task_name].find_with_extension('py')`.
43
+ - `python_task_dir` defaults to `Scout.python.task.find(:lib)`.
44
+
45
+ 2. Run the Python file with `--scout-metadata`:
46
+ ```ruby
47
+ out = ScoutPython.run_file file, '--scout-metadata'
48
+ metas = JSON.parse(out.read)
49
+ ```
50
+
51
+ 3. Parse the metadata JSON. Each metadata object has:
52
+ ```json
53
+ {
54
+ "name": "hello",
55
+ "description": "Greet a user.",
56
+ "returns": "string",
57
+ "params": [
58
+ {"name": "name", "type": "string", "required": true, "default": null, "help": "..."},
59
+ {"name": "excited", "type": "boolean", "required": false, "default": false, "help": "..."}
60
+ ]
61
+ }
62
+ ```
63
+
64
+ 4. For each metadata object (the Python file may define multiple functions):
65
+ - Map the return type via `map_returns`.
66
+ - Map each param via `map_param` to a Scout input declaration.
67
+ - Declare the task via `task(name => return_type) { ... }`.
68
+
69
+ ### Phase 2: Task execution (job run time)
70
+
71
+ When a Python-backed task job is run:
72
+
73
+ 1. Collect input values from the job.
74
+ 2. Build CLI argv via `PythonWorkflow.build_python_argv(meta['params'], values)`.
75
+ 3. Prefix with the function name: `[meta['name']] + argv`.
76
+ 4. Execute: `ScoutPython.run_file(file, Shellwords.shelljoin(full_argv))`.
77
+ 5. Decode the return value:
78
+ - Try `JSON.parse(txt)`.
79
+ - If JSON parse fails and return type is `:array`/`:file_array`, split
80
+ on newlines.
81
+ - Otherwise, return stripped text.
82
+
83
+ ## Type mapping
84
+
85
+ ### Python type → Scout input type (map_param)
86
+
87
+ | Python type string | Scout input type |
88
+ |--------------------|------------------|
89
+ | `string` | `:string` |
90
+ | `integer` | `:integer` |
91
+ | `float` | `:float` |
92
+ | `boolean` | `:boolean` |
93
+ | `binary` | `:binary` |
94
+ | `path` | `:file` |
95
+ | `list[string]` | `:array` |
96
+ | `list[integer]` | `:array` |
97
+ | `list[float]` | `:array` |
98
+ | `list[path]` | `:file_array` |
99
+ | (other) | `:string` |
100
+
101
+ ### Python return type → Scout return type (map_returns)
102
+
103
+ | Python type string | Scout return type |
104
+ |--------------------|-------------------|
105
+ | `nil` / `string` | `:string` |
106
+ | `integer` | `:integer` |
107
+ | `float` | `:float` |
108
+ | `boolean` | `:boolean` |
109
+ | `binary` | `:binary` |
110
+ | `path` | `:string` |
111
+ | `list`, `array` | `:array` |
112
+ | `list[...]` | `:array` |
113
+ | (other) | `:string` |
114
+
115
+ ### build_python_argv (inputs.rb)
116
+
117
+ This method translates Ruby input values into CLI arguments for the Python
118
+ script. Key behaviors:
119
+
120
+ - **nil values**: Skipped (no flag emitted).
121
+ - **booleans**: For boolean params with default `true`, the flag is emitted
122
+ as `--name` or `--no-name`. For default `false`, the flag is `--name` if
123
+ value is true, nothing if false.
124
+ - **list/array values**: If the Ruby value is a String, it is split by comma.
125
+ If it is a file path that exists, the file is read line-by-line. If it
126
+ is an Array, each element is passed as a repeated `--name value`.
127
+ - **path/file types**: Passed as-is (the Python side handles them).
128
+ - **scalars**: Passed as `--name value`.
129
+
130
+ **Observation:** The boolean handling logic is complex. For booleans with
131
+ default `true`, it uses the value directly. For booleans with default
132
+ `false`, it only emits the flag if the value is true. This mimics
133
+ argparse's `BooleanOptionalAction` (for default true) and `store_true`
134
+ (for default false) on the Python side.
135
+
136
+ ## Multi-function files
137
+
138
+ A single Python file can register multiple functions with `scout.task`:
139
+
140
+ ```python
141
+ import scout
142
+
143
+ @scout.task
144
+ def add(a: int, b: int) -> int:
145
+ return a + b
146
+
147
+ @scout.task
148
+ def multiply(a: float, b: float) -> float:
149
+ return a * b
150
+ ```
151
+
152
+ When `python_task :math` is called, `read_python_metadata` returns an array
153
+ of metadata objects (one per function). The Ruby side iterates over all
154
+ metadata objects and creates one Scout task per function. This means a single
155
+ `python_task` call can create multiple tasks.
156
+
157
+ At execution time, the function name is passed as the first positional
158
+ argument to the Python script so the runner knows which function to dispatch
159
+ to.
160
+
161
+ ## Key findings
162
+
163
+ 1. **Metadata-driven design is elegant** — The Python function signature
164
+ fully drives the Scout task declaration. No manual input declarations
165
+ are needed on the Ruby side.
166
+
167
+ 2. **CLI-based execution provides isolation** — Each task run spawns a new
168
+ Python process, avoiding GIL contention and state leakage between tasks.
169
+ This is slower but safer than in-process execution.
170
+
171
+ 3. **Return value decoding is heuristic** — Ruby tries JSON first, then
172
+ falls back to line-splitting for arrays or plain text. This works for
173
+ most cases but could fail for edge cases where a string return value
174
+ happens to be valid JSON.
175
+
176
+ 4. **The `python_task_dir` defaults to `Scout.python.task.find(:lib)`** —
177
+ This uses the Scout Path subsystem to locate Python task files shipped
178
+ with the gem. Override with `self.python_task_dir = path` for custom
179
+ locations.
180
+
181
+ 5. **No caching of metadata** — `read_python_metadata` is called every time
182
+ `python_task` is invoked. Since the Python file must be executed, this
183
+ is a subprocess call per task at definition time. For workflows with
184
+ many tasks, this could be slow.
185
+
186
+ 6. **`load_directory`** (`python.rb`) — Discovers all `.py` files in a
187
+ directory and registers each as a `python_task`. Sets
188
+ `python_task_dir` to the directory. Uses `path.glob_names("*.py")`,
189
+ which requires `path` to be a Scout `Path` object.
190
+
191
+ 7. **Potential issue: string split for list values** — In
192
+ `build_python_argv`, if a list input has a Ruby String value, it is
193
+ split by comma. But if the string value contains commas as part of the
194
+ data (not as delimiters), this would incorrectly split it. Using a file
195
+ or Ruby Array avoids this.
196
+
197
+ 8. **Error messages** — `read_python_metadata` raises with the raw error
198
+ variable `err` which is never assigned. The error message would be
199
+ misleading. See Improvements.
@@ -0,0 +1,185 @@
1
+ # ScoutPython Bridge Analysis
2
+
3
+ > **Non-normative.** Investigation artifact. See `00_scope_and_themes.md` for disclaimer.
4
+ >
5
+ > **Status note (2026-09-12):** written before the verification campaign;
6
+ > several claims have since been refined by probes. The authoritative,
7
+ > probe-backed account of execution modes, threading, `at_exit` and
8
+ > `sys.path` behaviour is
9
+ > [`doc/developer/ScoutPythonInternals.md`](../doc/developer/ScoutPythonInternals.md)
10
+ > (user view: `doc/user/RunningPythonFromRuby.md`), with evidence in the
11
+ > Cortex artifact `scout-rig/subsys/python-bridge.md`. In particular this
12
+ > analysis predates the finding that `run_threaded` never exits cleanly
13
+ > (B2) and that main-thread modes duplicate the Scout directory on every
14
+ > `run` (O2).
15
+
16
+ ## Overview
17
+
18
+ ScoutPython (`lib/scout/python.rb` + sub-files) is the Ruby-facing API for
19
+ interacting with Python via the `pycall` gem. It provides a layered set of
20
+ execution modes, import helpers, binding scopes, iteration utilities, and
21
+ data conversion.
22
+
23
+ ## Architecture
24
+
25
+ ### Module structure
26
+
27
+ ```
28
+ ScoutPython (lib/scout/python.rb)
29
+ extend PyCall::Import # Gives module-level pyimport/pyfrom/etc.
30
+ ├── class ScoutPythonException
31
+ ├── class Binding
32
+ │ include PyCall::Import # Per-instance import scope
33
+ ├── init_scout # One-time PyCall init + at_exit hook
34
+ ├── import helpers # import_method, get_module, get_class, etc.
35
+ ├── iteration # iterate, iterate_index, collect
36
+ └── binding helpers # new_binding, binding_run
37
+ ```
38
+
39
+ Files:
40
+ - `paths.rb` — sys.path management
41
+ - `run.rb` — execution modes and threading
42
+ - `script.rb` — ruby2python serialization, script(), pickle/JSON loading
43
+ - `util.rb` — py2ruby_a, tsv2df, df2tsv, list2ruby, numpy2ruby, obj2hash
44
+
45
+ ### Initialization
46
+
47
+ `ScoutPython.init_scout` is called by `run()` and `run_threaded()` (via
48
+ `init_thread` → `init_scout`). It:
49
+
50
+ 1. Calls `PyCall.init` (once, guarded by `@@__init_scout_python` class variable).
51
+ 2. Calls `ScoutPython.process_paths` to append registered paths to `sys.path`.
52
+ 3. Imports the Python `scout` module via `pyimport("scout")`.
53
+ 4. Sets `@@__init_scout_python = true`.
54
+ 5. Registers an `at_exit` hook that:
55
+ - Kills all non-main threads.
56
+ - Joins killed threads.
57
+ - Calls `GC.start` while Python is still initialized (so PyCall can
58
+ acquire the GIL and finalize Python objects safely).
59
+ - Touches `PyCall.builtins.object` as a GIL health check.
60
+
61
+ **Key insight:** The `at_exit` ordering is critical. GC must happen *before*
62
+ PyCall loses the GIL. If Python's GIL is not available during GC, PyCall
63
+ objects cannot be finalized, leading to segfaults.
64
+
65
+ ## Execution modes
66
+
67
+ | Method | Synchronized? | Thread? | Init? | GC after? | Use case |
68
+ |----------------|---------------|---------|-------|-----------|-----------------------------------|
69
+ | `run` | Yes (via run_simple) | No | Yes | Yes | General-purpose, safe default |
70
+ | `run_simple` | Yes (MUTEX) | No | No | No | Already initialized, want sync |
71
+ | `run_direct` | No | No | No | No | Fastest, no sync, single eval |
72
+ | `run_threaded` | Yes (via run_in_thread) | Yes | Yes (in thread) | No | Background work, isolation |
73
+ | `run_log` | Yes (via run) | No | Yes | Yes | Same as run + capture stdout/stderr |
74
+ | `run_log_stderr` | Yes (via run) | No | Yes | Yes | Same as run + capture stderr only |
75
+
76
+ ### Threading model
77
+
78
+ A dedicated background thread (`@thread`) processes a queue of blocks:
79
+
80
+ ```ruby
81
+ QUEUE_IN = Queue.new # blocks to execute
82
+ QUEUE_OUT = Queue.new # results
83
+ ```
84
+
85
+ - `init_thread` lazily creates the thread. Inside the thread, it calls
86
+ `ScoutPython.init_scout` and `process_paths`, then enters a loop popping
87
+ blocks from `QUEUE_IN`.
88
+ - `run_in_thread` pushes a block to `QUEUE_IN` and waits on `QUEUE_OUT`,
89
+ all under `MUTEX.synchronize`.
90
+ - `stop_thread` pushes `:stop`, joins (timeout 2s) or kills, runs GC, and
91
+ calls `PyCall.finalize` if available.
92
+
93
+ **Observation:** The thread model serializes all Python access through a
94
+ single queue. This is inherently safe for GIL but means concurrent
95
+ `run_threaded` calls block each other.
96
+
97
+ **Warning:** If the thread dies, `init_thread` detects it (`!self.thread.alive?`),
98
+ warns "Reloading ScoutPython thread", joins the dead thread, and creates a
99
+ new one. However, any pending results in `QUEUE_OUT` from the failed thread
100
+ are not drained.
101
+
102
+ ### Binding scopes
103
+
104
+ `ScoutPython::Binding` includes `PyCall::Import`, giving it its own import
105
+ namespace. This is useful for isolating imports:
106
+
107
+ ```ruby
108
+ ScoutPython.binding_run do
109
+ pyimport :torch # torch available here
110
+ end
111
+ # torch is NOT available outside
112
+ ```
113
+
114
+ `binding_run` always creates a *new* binding (the parameter is ignored in
115
+ the current implementation — see Improvements).
116
+
117
+ ## Import helpers
118
+
119
+ | Method | Description |
120
+ |--------|-------------|
121
+ | `import_method(module_name, method_name, as=nil)` | Import a single method; returns Ruby `Method` |
122
+ | `call_method(module_name, method_name, *args)` | Import and call in one step |
123
+ | `get_module(module_name)` | Import module, alias with underscores (e.g., `torch.nn` → `torch_nn`) |
124
+ | `get_class(module_name, class_name)` | Get a class from a module |
125
+ | `class_new_obj(module_name, class_name, args={})` | Instantiate with keyword args |
126
+ | `exec(script)` | `PyCall.exec(script)` one-liner |
127
+
128
+ **Note:** `get_module` uses `pyimport(module_name, as: save_module_name)` and
129
+ then `ScoutPython.send(save_module_name)`. This means the module is accessible
130
+ as `ScoutPython.torch_nn` after importing `torch.nn`. This could pollute the
131
+ ScoutPython namespace with many dynamically-created methods.
132
+
133
+ ## Path management (paths.rb)
134
+
135
+ - `ScoutPython.paths` — lazy-initialized array.
136
+ - `ScoutPython.add_path(path)` — append a path.
137
+ - `ScoutPython.add_paths(paths)` — append multiple.
138
+ - `ScoutPython.process_paths` — appends all registered paths to `sys.path`
139
+ inside a `run_direct 'sys'` block.
140
+ - At load time: `add_paths(Scout.python.find_all)` adds all Python
141
+ directories registered via the Scout Path subsystem.
142
+
143
+ **Observation:** `process_paths` is called multiple times: once in
144
+ `init_scout`, once in `run_simple`, and once in `init_thread`. Since it
145
+ appends without deduplication, paths may accumulate duplicates in `sys.path`.
146
+
147
+ ## Iteration utilities
148
+
149
+ Three methods for traversing Python iterables from Ruby:
150
+
151
+ 1. `iterate(iterator, options={})` — Handles both `__iter__`/`__next__`
152
+ iterators and indexable sequences (falls back to `iterate_index`).
153
+ Detects `StopIteration` via `PyCall::PyError` type string matching.
154
+
155
+ 2. `iterate_index(elem, options={})` — Index-based loop using `PyCall.len`
156
+ and `elem[i]`.
157
+
158
+ 3. `collect(iterator, options={})` — Maps Python iterables to Ruby arrays.
159
+
160
+ All three support optional progress bars (`bar: true` for default, `bar:
161
+ "Description"` for custom). They call `Log::ProgressBar` from scout-essentials.
162
+
163
+ **StopIteration detection:** Uses string comparison `$!.type.to_s ==
164
+ "<class 'StopIteration'>"`. This is fragile but necessary because PyCall
165
+ wraps Python exceptions.
166
+
167
+ ## Key findings
168
+
169
+ 1. **The execution mode hierarchy is well-designed** but could use better
170
+ documentation of when to use which mode.
171
+
172
+ 2. **The threading model is sound** but serializes all access. The at_exit
173
+ hook is critical for avoiding segfaults during shutdown.
174
+
175
+ 3. **Binding isolation works** but `binding_run` ignores its `binding`
176
+ parameter — it always creates a new one.
177
+
178
+ 4. **Path deduplication is missing** — `process_paths` can append
179
+ duplicates to `sys.path`.
180
+
181
+ 5. **StopIteration detection via string matching** is fragile but may be
182
+ the only reliable way with PyCall.
183
+
184
+ 6. **The at_exit hook kills ALL non-main threads**, not just the Python
185
+ thread. This could interfere with other threading code in the process.