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,209 @@
1
+ # Data Conversion and Scripting Analysis
2
+
3
+ > **Non-normative.** Investigation artifact.
4
+ >
5
+ > **Status note (2026-09-12):** written before the verification campaign.
6
+ > The authoritative account of `script()` error reporting (last traceback
7
+ > line included, full traceback at DEBUG) and the pickle/JSON result
8
+ > loading is `doc/user/ScriptingPython.md` and
9
+ > `doc/developer/DataConversionInternals.md`, with evidence in the Cortex
10
+ > artifact `scout-rig/subsys/data-conversion.md`. Notably this analysis
11
+ > predates two verified findings: the `python-pickle` gem fails on
12
+ > integers >= 256 and on negatives, and `script()`/`run_file` clobber
13
+ > `PYTHONPATH`.
14
+
15
+ ## Overview
16
+
17
+ This analysis covers two related subsystems:
18
+
19
+ 1. **ruby2python serialization** (`script.rb`) — How Ruby values are turned
20
+ into Python literal strings for the `script()` facility.
21
+ 2. **Data conversion helpers** (`util.rb`) — How PyCall objects are
22
+ converted back to Ruby types.
23
+ 3. **The `script()` facility** — Running ad-hoc Python text in a subprocess
24
+ and returning the result.
25
+
26
+ ## ruby2python (script.rb)
27
+
28
+ `ScoutPython.ruby2python(object)` converts Ruby objects to Python literal
29
+ strings. This is used by `script()` to inject Ruby variables into Python
30
+ source code.
31
+
32
+ ### Type mapping
33
+
34
+ | Ruby type | Python literal |
35
+ |------------------|-------------------------------------|
36
+ | `Float::INFINITY`| `inf` |
37
+ | `nil` | `None` |
38
+ | `":NA"` (Symbol) | `None` |
39
+ | `Symbol` | Quoted string: `"symbol"` |
40
+ | `String` | Quoted string (re escapes escaped) |
41
+ | `Numeric` | Literal number |
42
+ | `true` | `True` |
43
+ | `false` | `False` |
44
+ | `Array` | `[ruby2python(e1), ...]` |
45
+ | `Hash` | `{k: v, ...}` (keys are symbols) |
46
+ | `TSV` | Written to temp file, loaded via `scout.tsv(file)` → pandas DataFrame |
47
+
48
+ ### TSV handling in ruby2python
49
+
50
+ When a TSV is passed as a variable to `script()`:
51
+
52
+ 1. A temporary file is created with the TSV content.
53
+ 2. The Python code is prepended with `import scout; df = scout.tsv(file)`.
54
+ 3. The variable name in the Python script refers to the DataFrame.
55
+
56
+ This means the script body can operate on the DataFrame directly:
57
+
58
+ ```ruby
59
+ ScoutPython.script <<~PY, df: tsv
60
+ result = df.loc["k2", "ValueB"]
61
+ PY
62
+ ```
63
+
64
+ ## script() facility
65
+
66
+ `ScoutPython.script(text, variables = {})`:
67
+
68
+ 1. Serializes each key-value in `variables` into a Python assignment line.
69
+ 2. For TSV values, writes them to a temp file and inserts a `scout.tsv()`
70
+ loading line.
71
+ 3. Appends a "save result" snippet to persist the Python variable `result`
72
+ to a temp file (pickle by default).
73
+ 4. Sets `PYTHONPATH` from `ScoutPython.paths`.
74
+ 5. Executes the script via `CMD.cmd_log("env PYTHONPATH=... python3 ...")`.
75
+ 6. Loads the result back (pickle via `python/pickle` gem by default).
76
+
77
+ ### Result persistence alternatives
78
+
79
+ Default uses pickle:
80
+ - `save_script_result_pickle(file)` → `pickle.dump(result, file)`
81
+ - `load_pickle(file)` → Ruby reads via `python/pickle` gem
82
+
83
+ JSON alternative:
84
+ - `save_script_result_json(file)` → `json.dump(result, file)`
85
+ - `load_json(file)` → Ruby reads and parses JSON
86
+
87
+ The aliases `save_script_result` and `load_result` can be re-pointed:
88
+
89
+ ```ruby
90
+ class << ScoutPython
91
+ alias save_script_result save_script_result_json
92
+ alias load_result load_json
93
+ end
94
+ ```
95
+
96
+ ### run_file
97
+
98
+ `ScoutPython.run_file(file, arg_str)` — Executes a Python file as a
99
+ subprocess with `PYTHONPATH` set from `ScoutPython.paths`:
100
+
101
+ ```ruby
102
+ CMD.cmd("env PYTHONPATH=#{path_env} python '#{file}' #{arg_str}")
103
+ ```
104
+
105
+ Returns a `ConcurrentStream` that responds to `.exit_status`, `.read`.
106
+
107
+ ## Data conversion helpers (util.rb)
108
+
109
+ These convert PyCall-wrapped Python objects back into Ruby types:
110
+
111
+ ### py2ruby_a / to_a
112
+
113
+ ```ruby
114
+ ScoutPython.py2ruby_a(array_like) # PyCall::List → Ruby Array
115
+ ScoutPython.to_a(array_like) # alias
116
+ ```
117
+
118
+ Uses `PyCall::List.(array).to_a`. Note: this is `PyCall::List` as a callable
119
+ (`call` method), not a constructor call with `new`.
120
+
121
+ ### list2ruby
122
+
123
+ ```ruby
124
+ ScoutPython.list2ruby(list)
125
+ ```
126
+
127
+ Deeply converts nested PyCall::List objects to Ruby arrays. Only recurses
128
+ if the element is a `PyCall::List`.
129
+
130
+ ### numpy2ruby
131
+
132
+ ```ruby
133
+ ScoutPython.numpy2ruby(numpy_array)
134
+ ```
135
+
136
+ Calls `numpy_array.tolist` (Python-side conversion to nested lists), then
137
+ passes through `list2ruby`.
138
+
139
+ ### obj2hash
140
+
141
+ ```ruby
142
+ ScoutPython.obj2hash(mapping_object)
143
+ ```
144
+
145
+ Builds a Ruby Hash by iterating `mapping_object.keys` (using
146
+ `ScoutPython.iterate`) and reading `mapping_object[key]`. Works with any
147
+ Python object that has `.keys` and `[]` access (dicts, pandas DataFrames,
148
+ etc.).
149
+
150
+ ### dict2hash
151
+
152
+ ```ruby
153
+ ScoutPython.dict2hash(dict)
154
+ ```
155
+
156
+ Similar to `obj2hash` but uses `py2ruby_a(obj.keys)` and `obj.get(k)` for
157
+ key extraction. Uses the PyCall `.get()` method instead of `[]`.
158
+
159
+ ### tsv2df
160
+
161
+ ```ruby
162
+ ScoutPython.tsv2df(tsv)
163
+ ```
164
+
165
+ Converts a Ruby TSV to a pandas DataFrame:
166
+
167
+ ```python
168
+ pandas.DataFrame.new(tsv.values, columns: tsv.fields, index: tsv.keys)
169
+ df.columns.name = tsv.key_field
170
+ ```
171
+
172
+ Requires Python pandas to be available.
173
+
174
+ ### df2tsv
175
+
176
+ ```ruby
177
+ ScoutPython.df2tsv(dataframe, options = {})
178
+ ```
179
+
180
+ Converts a pandas DataFrame back to a Ruby TSV:
181
+
182
+ 1. Default `options[:type] = :list`
183
+ 2. Key field: `dataframe.columns.name`
184
+ 3. Fields: `py2ruby_a(dataframe.columns.values)`
185
+ 4. Keys: `py2ruby_a(dataframe.index.values)`
186
+ 5. Iterates rows with `PyCall.len(tuple.index)` and `tuple.values[i]`.
187
+
188
+ ## Key findings
189
+
190
+ 1. **The script() facility is powerful but subprocess-based** — Each call
191
+ spawns a new Python process. This is clean (no GIL issues) but slow for
192
+ repeated calls. For frequent calls, use `run`/`run_direct` instead.
193
+
194
+ 2. **The TSV↔DataFrame conversion is bidirectional and tested** —
195
+ `df2tsv(tsv2df(tsv)) == tsv` is verified by tests.
196
+
197
+ 3. **ruby2python string escaping is minimal** — Uses `value.inspect` for
198
+ strings, which handles Ruby string escaping but may not perfectly match
199
+ Python string semantics for all edge cases (e.g., Python-specific escape
200
+ sequences).
201
+
202
+ 4. **obj2hash vs dict2hash** — Two very similar methods with subtle
203
+ differences. `obj2hash` uses `ScoutPython.iterate` and `obj[k]`; `dict2hash`
204
+ uses `py2ruby_a` and `obj.get(k)`. The existence of both suggests an
205
+ evolution that wasn't fully consolidated.
206
+
207
+ 5. **pickle dependency** — The default `load_pickle` depends on the
208
+ `python/pickle` Ruby gem. If not installed, `script()` will fail unless
209
+ aliases are re-pointed to JSON.
@@ -0,0 +1,246 @@
1
+ # Design Philosophy and Patterns Analysis
2
+
3
+ > **Non-normative.** Investigation artifact.
4
+ >
5
+ > **Status note (2026-09-12):** written before the verification campaign.
6
+ > Its anti-pattern list (unused `err`, dead code, ignored `binding`
7
+ > parameter, `sys.path` duplication) was confirmed and reconciled in
8
+ > `doc/Improvements.md` (items B1, B4, B3, O2); the normative pattern
9
+ > catalogue is `doc/developer/DesignPrinciples.md`.
10
+
11
+ ## Overview
12
+
13
+ Scout-rig follows the established Scout/Rbbt design philosophy. This
14
+ analysis identifies the key principles and patterns that make the code
15
+ expressive and elegant, and contrasts them with common anti-patterns.
16
+
17
+ ## Core design principles
18
+
19
+ ### 1. Thin wrappers over powerful primitives
20
+
21
+ ScoutPython doesn't reimplement PyCall — it wraps it ergonomically. Each
22
+ execution mode adds one layer of concern:
23
+
24
+ - `run_direct`: raw PyCall eval, no sync, no init.
25
+ - `run_simple`: synchronization + module_eval.
26
+ - `run`: init + run_simple + GC.
27
+ - `run_threaded`: queue + dedicated thread + init.
28
+ - `run_log`: run + stderr/stdout capture.
29
+
30
+ Each layer composes the previous. This is idiomatic Scout: build complexity
31
+ by layering thin wrappers.
32
+
33
+ **Idiomatic:**
34
+ ```ruby
35
+ # Each mode composes the one below it
36
+ def run(mod = nil, imports = nil, &block)
37
+ init_scout
38
+ res = run_simple(mod, imports, &block)
39
+ GC.start
40
+ res
41
+ end
42
+ ```
43
+
44
+ **Non-idiomatic:**
45
+ ```ruby
46
+ # Reimplementing everything from scratch for each mode
47
+ def run(mod, imports)
48
+ PyCall.init
49
+ # ... 20 lines of sync logic ...
50
+ # ... 10 lines of import logic ...
51
+ # ... 5 lines of GC logic ...
52
+ end
53
+
54
+ def run_threaded(mod, imports)
55
+ PyCall.init
56
+ # ... 20 lines of sync logic ...
57
+ # ... 10 lines of import logic ...
58
+ # ... 15 lines of thread management ...
59
+ end
60
+ ```
61
+
62
+ ### 2. Metadata-driven task definition
63
+
64
+ PythonWorkflow doesn't require the user to declare inputs manually — it
65
+ discovers them from the Python function's signature. This is the Scout
66
+ convention of "convention over configuration" applied to cross-language
67
+ interop.
68
+
69
+ **Idiomatic (scout-rig style):**
70
+ ```ruby
71
+ # python_task discovers everything from the Python function
72
+ python_task :hello
73
+
74
+ # In hello.py:
75
+ # def hello(name: str, excited: bool = False) -> str: ...
76
+ ```
77
+
78
+ **Non-idiomatic:**
79
+ ```ruby
80
+ # Manually declaring every input on the Ruby side
81
+ input :name, :string, "Name"
82
+ input :excited, :boolean, "Excited?", default: false
83
+ task :hello => :string do |name, excited|
84
+ # run python manually
85
+ end
86
+ ```
87
+
88
+ ### 2b. The decorator as cross-language glue
89
+
90
+ The `scout.task` decorator is a beautiful example of Scout philosophy: the
91
+ Python function's docstring and type hints become the source of truth for
92
+ metadata, CLI help, and Scout task declaration. One function definition
93
+ serves three audiences (Ruby, Python CLI, LLM tool schemas).
94
+
95
+ ### 3. Execution at the right level of isolation
96
+
97
+ Scout-rig provides multiple execution strategies, each appropriate for
98
+ different isolation requirements:
99
+
100
+ | Need | Mechanism | Tradeoff |
101
+ |-----------------------------|---------------------|-----------------------|
102
+ | Quick one-liner | `run_direct` | No sync, no GC |
103
+ | General purpose | `run` | Safe, slightly slower |
104
+ | Background work | `run_threaded` | Isolated thread |
105
+ | Full script with variables | `script()` | New process, clean |
106
+ | Scout task | `python_task` | New process per run |
107
+
108
+ The philosophy is: let the user choose the isolation level. Don't force a
109
+ single execution strategy.
110
+
111
+ ### 4. Subprocess for clean isolation
112
+
113
+ When the Python code is complex, untrusted, or needs to be run repeatedly
114
+ with different inputs, scout-rig spawns a subprocess. This avoids GIL
115
+ contention, memory leaks, and state contamination. The `script()` facility
116
+ and `python_task` execution both use subprocesses.
117
+
118
+ ### 5. The "setup" pattern
119
+
120
+ Like other Scout modules, ScoutPython uses class-level setup that happens
121
+ lazily on first use:
122
+
123
+ ```ruby
124
+ def self.init_scout
125
+ return if @@__init_scout_python
126
+ PyCall.init
127
+ # ...
128
+ @@__init_scout_python = true
129
+ end
130
+ ```
131
+
132
+ This is the same pattern used by `Persist`, `CMD`, and other Scout modules:
133
+ expensive initialization happens once, on demand, and is guarded by a
134
+ class variable.
135
+
136
+ ### 6. Fluent, block-based API
137
+
138
+ The execution APIs accept a block that is `instance_exec`'d in a context
139
+ where PyCall imports are available as local methods:
140
+
141
+ ```ruby
142
+ ScoutPython.run :numpy, as: :np do
143
+ np.array([1,2,3]).sum
144
+ end
145
+ ```
146
+
147
+ The `as:` alias makes the code read naturally. This is similar to how
148
+ Scout workflows use blocks for task definitions.
149
+
150
+ ### 7. Data flows through files, not memory
151
+
152
+ For cross-process communication (script() and python_task), data flows
153
+ through files: TSV values are written to temp files, results are pickled/
154
+ JSON'd to temp files. This is the Unix philosophy applied to cross-language
155
+ interop: use files as the universal interface.
156
+
157
+ ## Anti-patterns observed
158
+
159
+ ### A1. Unused `err` variable in error handling
160
+
161
+ In `task.rb`, `read_python_metadata`:
162
+ ```ruby
163
+ raise "Error getting metadata for #{File.basename(file)}: #{err}"
164
+ ```
165
+ The variable `err` is never assigned. The error message will always show
166
+ empty/nil for the error detail. This is a bug.
167
+
168
+ ### A2. Dead code: `save_inputs` in workflow.py
169
+
170
+ ```python
171
+ def save_inputs(directory, inputs, types):
172
+ return
173
+ ```
174
+ This is a stub that was never implemented. It should either be implemented
175
+ or removed.
176
+
177
+ ### A3. `binding_run` ignores its parameter
178
+
179
+ ```ruby
180
+ def self.binding_run(binding = nil, *args, &block)
181
+ binding = new_binding # always creates new, ignores parameter
182
+ binding.instance_exec *args, &block
183
+ end
184
+ ```
185
+ The `binding` parameter is overwritten immediately. This is misleading.
186
+
187
+ ### A4. Path duplication in sys.path
188
+
189
+ `process_paths` appends paths without deduplication. Called multiple times
190
+ during initialization, it can add the same paths repeatedly.
191
+
192
+ ### A5. Hardcoded command names
193
+
194
+ The Python `scout` package hardcodes `rbbt` and `rbbt_exec.rb`. In Scout
195
+ installs, these may be `scout` or `scout_exec`.
196
+
197
+ ### A6. The `at_exit` hook kills ALL non-main threads
198
+
199
+ ```ruby
200
+ at_exit do
201
+ Thread.list.each do |thread|
202
+ next if thread == Thread.main
203
+ thread.kill
204
+ thread.join rescue nil
205
+ end
206
+ GC.start
207
+ # ...
208
+ end
209
+ ```
210
+ This kills threads not related to Python, which could interfere with other
211
+ threading code.
212
+
213
+ ## Comparison with scout-essentials conventions
214
+
215
+ Scout-rig follows the same conventions as scout-essentials:
216
+
217
+ - **Annotations:** ScoutPython uses class variables (`@@__init_scout_python`)
218
+ for one-time initialization, similar to how scout-essentials modules use
219
+ class-level state.
220
+ - **Paths:** Uses `Path.add_path` and `Path.caller_lib_dir` from
221
+ scout-essentials.
222
+ - **Commands:** Uses `CMD.cmd` and `CMD.cmd_log` from scout-essentials.
223
+ - **Logging:** Uses `Log.trap_std`, `Log.trap_stderr`, and `Log::ProgressBar`
224
+ from scout-essentials.
225
+ - **Streams:** Uses `ConcurrentStreamProcessFailed` from scout-essentials.
226
+ - **TSV:** Uses `TSV.setup`, `TSV.open` from scout-essentials.
227
+ - **TmpFile:** Uses `TmpFile.with_file` from scout-essentials.
228
+
229
+ For understanding these foundational concepts, see the
230
+ [scout-essentials documentation](https://github.com/mikisvaz/scout-essentials/blob/main/doc/user/WorkingWithFiles.md).
231
+
232
+ ## Summary
233
+
234
+ Scout-rig embodies the Scout philosophy through:
235
+
236
+ 1. **Layered thin wrappers** over PyCall.
237
+ 2. **Metadata-driven design** that eliminates boilerplate.
238
+ 3. **Multiple isolation levels** for different use cases.
239
+ 4. **Files as the universal interface** for cross-process communication.
240
+ 5. **Block-based, fluent APIs** that read naturally.
241
+ 6. **Lazy initialization** guarded by class variables.
242
+
243
+ The code is compact (710 Ruby lines, 946 Python lines) and expressive.
244
+ The main areas for improvement are the anti-patterns identified above,
245
+ particularly the unused error variable (A1), dead code (A2), and the
246
+ ignored parameter (A3).