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,254 @@
1
+ # Design Principles
2
+
3
+ This document explains the coding philosophy and idiomatic patterns behind
4
+ scout-rig. Scout-rig is part of the Scout ecosystem and follows its
5
+ conventions, but has its own emphasis because of its unique role bridging
6
+ Ruby and Python.
7
+
8
+ ## Audience
9
+
10
+ This page is intended for:
11
+
12
+ - ✓ Framework contributors
13
+ - ✓ Advanced workflow authors who want to write idiomatic code
14
+ - ✗ Users looking for usage instructions (see [User Documentation](../user/))
15
+
16
+ ## Core philosophy
17
+
18
+ Scout-rig bridges two language runtimes. The hardest part of a bridge is not
19
+ the mechanics of crossing the boundary — it's deciding where the abstraction
20
+ boundaries go and keeping them clean.
21
+
22
+ The Scout philosophy is:
23
+
24
+ 1. **Thin wrappers, not thick abstractions** — Wrap existing tools (PyCall,
25
+ CLI, pandas) ergonomically without hiding them behind layers of indirection.
26
+ 2. **Unix philosophy** — Text, files, and processes as universal interfaces.
27
+ 3. **Explicit over implicit** — Make the user say what they mean (e.g.,
28
+ explicit converters) rather than guessing.
29
+
30
+ ## Key patterns
31
+
32
+ ### 1. Layered execution modes
33
+
34
+ Each mode adds exactly one concern to the layer below. This is the Scout
35
+ "setup pattern" applied to execution semantics:
36
+
37
+ ```ruby
38
+ # run_direct: raw PyCall.eval
39
+ # run_simple: + MUTEX.synchronize
40
+ # run: + init_scout + GC
41
+ # run_threaded: + dedicated thread + queue
42
+ # run_log: + Log trapping
43
+ ```
44
+
45
+ This is idiomatic Scout: compose by layering, not by branching. The user
46
+ picks the layer that matches their isolation/overhead needs.
47
+
48
+ **Anti-pattern:** A single `run` method with flags (`run(threads: true,
49
+ log: true, direct: true)`) would be harder to read and test.
50
+
51
+ ### 2. The `script()` facility as a Unix pipe
52
+
53
+ `script()` treats the Ruby→Python boundary like a Unix pipe:
54
+
55
+ 1. Ruby variables are serialized (Ruby → Python literals or temp files).
56
+ 2. A Python script is assembled (assignments + body + save result).
57
+ 3. Python runs in a subprocess.
58
+ 4. The result is read back from a file.
59
+
60
+ This follows the Unix principle of using text/files as the universal
61
+ interface. The advantage is complete isolation (no GIL, no state leakage).
62
+ The tradeoff is process startup overhead.
63
+
64
+ ### 3. Metadata-driven task definition
65
+
66
+ `python_task` discovers a Python function's inputs from its type hints and
67
+ docstring, automatically declaring the Scout task:
68
+
69
+ ```ruby
70
+ python_task :hello
71
+ # Discovers: name (str), excited (bool, default=False), returns str
72
+ ```
73
+
74
+ This eliminates double-declaration and keeps the Python function as the
75
+ single source of truth. It follows the Scout principle of **annotated
76
+ objects**: metadata is attached to the object itself, not declared
77
+ elsewhere.
78
+
79
+ ### 4. CLI-first cross-language communication
80
+
81
+ For PythonWorkflow, Ruby and Python communicate via CLI arguments and
82
+ stdout:
83
+
84
+ ```
85
+ Ruby task input → CLI argument → Python function parameter
86
+ Python return value → stdout → Ruby result decoding
87
+ ```
88
+
89
+ This mirrors how Scout itself operates: tasks are CLI-callable. Python
90
+ tasks are first-class Scout citizens.
91
+
92
+ ### 5. Explicit converters, not transparent proxies
93
+
94
+ PyCall wraps Python objects in Ruby proxies. Scout-rig does not try to make
95
+ these proxies transparent. Instead, it provides explicit converters:
96
+
97
+ ```ruby
98
+ # Idiomatic: explicit conversion
99
+ arr = ScoutPython.numpy2ruby(na)
100
+ hash = ScoutPython.obj2hash(dict)
101
+ list = ScoutPython.py2ruby_a(pylist)
102
+ ```
103
+
104
+ **Anti-pattern:** Making PyCall proxies automatically respond to `each`,
105
+ `[]`, etc. This would require heavy `method_missing` usage and would hide
106
+ the cross-language boundary from the user.
107
+
108
+ ### 6. Threading model: dedicated thread + queue
109
+
110
+ `run_threaded` uses a dedicated background thread with input/output queues.
111
+ All threaded access is serialized through the queue. This is simpler and
112
+ safer than trying to allow concurrent Python execution (which would require
113
+ managing GIL acquisition patterns beyond PyCall's capabilities).
114
+
115
+ ### 7. The `scout` Python package as a thin CLI wrapper
116
+
117
+ The Python `scout` package does not embed the Ruby runtime. It shells out
118
+ to the Ruby CLI for all operations:
119
+
120
+ ```python
121
+ # scout.workflow.Workflow.run() →
122
+ # subprocess.run(['rbbt', 'workflow', 'task', ...])
123
+ ```
124
+
125
+ This follows the Unix philosophy: compose processes, don't embed runtimes.
126
+ The tradeoff is CLI startup overhead per call.
127
+
128
+ ## Idiomatic vs non-idiomatic examples
129
+
130
+ ### Creating a Python task
131
+
132
+ **Idiomatic:**
133
+ ```ruby
134
+ module MyWF
135
+ extend Workflow
136
+ extend PythonWorkflow
137
+ self.name = 'MyWF'
138
+
139
+ python_task :greet # metadata-driven, zero boilerplate
140
+ end
141
+ ```
142
+
143
+ **Non-idiomatic:**
144
+ ```ruby
145
+ module MyWF
146
+ extend Workflow
147
+ self.name = 'MyWF'
148
+
149
+ # Redundant declaration
150
+ input :name, :string, "Name"
151
+ input :excited, :boolean, "Excited?", false
152
+ task :greet => :string do |name, excited|
153
+ # Manual subprocess management
154
+ cmd = "python greet.py --name #{name}"
155
+ cmd += " --excited" if excited
156
+ `#{cmd}`.strip
157
+ end
158
+ self.input :name # Bookkeeping
159
+ self.input :excited
160
+ end
161
+ ```
162
+
163
+ ### Running Python from Ruby
164
+
165
+ **Idiomatic:**
166
+ ```ruby
167
+ # Import + execute in one call, use the right mode for the job
168
+ result = ScoutPython.run :numpy, as: :np do
169
+ np.array([1, 2, 3]).mean()
170
+ end
171
+ ```
172
+
173
+ **Non-idiomatic:**
174
+ ```ruby
175
+ # Manual PyCall management
176
+ require 'pycall/import'
177
+ include PyCall::Import
178
+ pyimport :numpy, as: :np
179
+ # No mutex, no GC, no error handling
180
+ result = np.array([1, 2, 3]).mean()
181
+ ```
182
+
183
+ ### Converting data
184
+
185
+ **Idiomatic:**
186
+ ```ruby
187
+ # Explicit conversion, clear intent
188
+ df = ScoutPython.tsv2df(tsv)
189
+ result = ScoutPython.run do
190
+ df.shape
191
+ end
192
+ rows = ScoutPython.py2ruby_a(result[0])
193
+ ```
194
+
195
+ **Non-idiomatic:**
196
+ ```ruby
197
+ # Trying to use the PyCall proxy as a native Ruby object
198
+ df = ScoutPython.run do
199
+ pandas.DataFrame.new(tsv.values)
200
+ end
201
+ df.each { |row| ... } # Doesn't work — PyCall proxy
202
+ df.shape[0] # Works but opaque
203
+ ``
204
+
205
+ ### Passing data to script()
206
+
207
+ **Idiomatic:**
208
+ ```ruby
209
+ # Let ruby2python handle serialization
210
+ result = ScoutPython.script <<~PY, numbers: [1, 2, 3]
211
+ result = sum(numbers)
212
+ PY
213
+ ```
214
+
215
+ **Non-idiomatic:**
216
+ ```ruby
217
+ # Manual serialization
218
+ json_str = JSON.generate([1, 2, 3])
219
+ result = ScoutPython.script <<~PY, numbers_json: json_str
220
+ import json
221
+ numbers = json.loads(numbers_json)
222
+ result = sum(numbers)
223
+ PY
224
+ ```
225
+
226
+ ## Extension points
227
+
228
+ If you need to extend scout-rig, here are the natural extension points:
229
+
230
+ | Extension | Where | How |
231
+ |-----------|-------|-----|
232
+ | New execution mode | `lib/scout/python/run.rb` | Compose on top of existing modes |
233
+ | New data converter | `lib/scout/python/util.rb` | Add a class method to ScoutPython |
234
+ | New serialization format | `lib/scout/python/script.rb` | Re-point aliases |
235
+ | New type mapping | `lib/scout/workflow/python/task.rb` | Extend map_param / map_returns |
236
+ | New Python-side helper | `python/scout/` | Add module + `scout.task` |
237
+ | New remote client | `python/scout/workflow/remote.py` | Add class + HTTP methods |
238
+
239
+ ## Principles summary
240
+
241
+ 1. **Layering over branching.** Compose by stacking modes, not by flags.
242
+ 2. **Files and text as universal interfaces.** Cross-process
243
+ communication uses files and CLI.
244
+ 3. **Metadata as single source of truth.** Type hints + docstrings drive
245
+ task definition.
246
+ 4. **Explicit over implicit.** Users call converters explicitly.
247
+ 5. **Thin wrappers over thick abstractions.** ScoutPython wraps PyCall
248
+ ergonomically; the Python package wraps the CLI ergonomically.
249
+
250
+ ## See also
251
+
252
+ - [Architecture](Architecture.md) — Overall module map.
253
+ - [Scout-essentials Design Principles](https://github.com/mikisvaz/scout-essentials/blob/main/doc/developer/DesignPrinciples.md)
254
+ - [Scout-ai Design Principles](https://github.com/mikisvaz/scout-ai/blob/main/doc/developer/DesignPrinciples.md)
@@ -0,0 +1,371 @@
1
+ # Python Task Runner Internals
2
+
3
+ ## Audience
4
+
5
+ This page is for scout-rig contributors who need to know exactly how
6
+ `python/scout/runner.py` turns a Python function into Scout metadata and a
7
+ CLI. Everything here is verified by probes against HEAD 290ee22 unless
8
+ marked otherwise.
9
+
10
+ - ✓ Framework contributors working on the Python side of the bridge
11
+ - ✓ Agents that must predict `--scout-metadata` or CLI output exactly
12
+ - ✗ Users who just want to write Python tasks (see
13
+ [Defining Python Tasks](../user/DefiningPythonTasks.md))
14
+
15
+ ## The two roles of runner.py
16
+
17
+ `runner.py` serves both sides of the bridge:
18
+
19
+ 1. **Metadata producer.** `scout.task(func)` computes the attribute
20
+ `func.__scout_meta__` via `describe_function(func)` and registers the
21
+ function in a module-global registry.
22
+ 2. **CLI dispatcher.** On `atexit`, if `sys.argv` is not empty, it parses
23
+ argv, dispatches to one registered function, prints the result, and
24
+ exits.
25
+
26
+ The Ruby side never imports the module; it runs the file as a program and
27
+ reads the `--scout-metadata` output. See
28
+ [PythonWorkflow Internals](PythonWorkflowInternals.md).
29
+
30
+ `describe_function` adds an `extension` metadata key only when the function
31
+ docstring declares a standalone `Extension: suffix` field. It extracts the
32
+ field before parsing description and parameter help, preserving those strings.
33
+ The field is optional for backward-compatible metadata; duplicates and empty
34
+ or whitespace-containing suffix values raise `ValueError` during metadata
35
+ discovery.
36
+
37
+ ## Type mapping
38
+
39
+ `_python_type_to_string(ann, kind="parameter", name="?")` maps a type hint
40
+ to one of the Scout input type strings `map_param` on the Ruby side
41
+ understands; `kind`/`name` only feed the error text when a hint is
42
+ unsupported. Annotations are resolved eagerly in `describe_function` with
43
+ `inspect.signature(func, eval_str=True)`, so **postponed annotations**
44
+ (`from __future__ import annotations`) and quoted forward references are
45
+ evaluated against the module namespace and map exactly like plain ones
46
+ (`str→"string"`, `Path→"path"`, `list[Path]→"list[path]"`, `Path | None→"path"`,
47
+ `Annotated[Path, …]→"path"` with the annotation text preserved). A name that
48
+ does not resolve stays a string and fails loudly here — never a silent
49
+ `"string"` mapping — and `_unsupported_annotation_error` explains that a
50
+ quoted annotation only evaluates when the type is importable or defined at
51
+ registration time; a genuinely undefined name raises `NameError` at import.
52
+ `typing.get_type_hints` is deliberately not used; eval_str covers the whole
53
+ supported surface.
54
+
55
+ - No annotation -> `"string"`.
56
+ - `Optional[X]` / `X | None` -> the mapping of `X`.
57
+ - `list[X]` (a parameterized generic, including `typing.List[X]`) ->
58
+ `"list[<subtype>]"` where `<subtype>` is the mapping of `X`. A **bare**
59
+ `list` annotation raises `ValueError("Unsupported parameter annotation
60
+ ... bare list (write list[str], list[Path], ...)")` rather than silently
61
+ mapping to `"string"`.
62
+ - `pathlib.Path` -> `"path"`.
63
+ - `str` -> `"string"`, `bytes` -> `"binary"`, `int` -> `"integer"`,
64
+ `float` -> `"float"`, `bool` -> `"boolean"`.
65
+ - Subclasses of the supported scalars (`str`, `bytes`, `int`, `float`,
66
+ `bool`, `pathlib.Path`) map like their base type.
67
+ - `typing.Any` deliberately maps to `"string"` — the explicit untyped
68
+ opt-out.
69
+ - `Annotated[X, ...]` unwraps to the mapping of `X`; the full annotation
70
+ text is still preserved in the metadata's `annotation` field.
71
+ - Anything else (`dict[...]`, `set`, custom classes, multi-member unions
72
+ such as `int | str`) raises `_unsupported_annotation_error` at
73
+ metadata time instead of degrading to `"string"`.
74
+
75
+ `_required_from_default(default_val)` returns `default_val is
76
+ inspect._empty`: a parameter with no default is required (verified: `a:
77
+ str` and `b: "str | None"` are both required; `c=None` and `d: int = 3`
78
+ are not).
79
+
80
+ The `BooleanOptionalAction` special case on the CLI comes from
81
+ `_add_arg_for_param`, not from `describe_function`: the flag code branches
82
+ on `default is True`, so only a parameter that *declares* `= True` gets the
83
+ `--flag | --no-flag` pair. An `Optional[bool]` with no default keeps
84
+ `default: None` in the metadata and therefore becomes
85
+ `action="store_true"` (verified: `Optional[bool]` shows a bare `--flag`
86
+ that turns the value on, and running without it yields `flag=False`).
87
+
88
+ `describe_function` also works on callables without Python source: a
89
+ builtin such as `len` is described by name, signature, and docstring, with
90
+ all parameters typed `"string"`. `*args`/`**kwargs` parameters are
91
+ included as ordinary (required, `"string"`) parameters rather than
92
+ skipped.
93
+
94
+ ## Docstring grammar
95
+
96
+ `describe_function` derives the description and per-parameter help from the
97
+ docstring. There are **two independent parsers**, tried in order, plus a
98
+ separate description extractor. All rules below are probe-verified.
99
+
100
+ ### Description: `_extract_description`
101
+
102
+ Walks the (dedented) docstring line by line and **stops at the first line
103
+ whose stripped, lower-cased form is in this set**:
104
+
105
+ args: arguments: returns: raises: examples: example: notes: note:
106
+ parameters returns raises examples notes
107
+
108
+ Blank lines and everything else are kept; leading/trailing blanks are
109
+ trimmed and internal blank lines preserved. Consequences (verified):
110
+
111
+ - The set is matched **exactly after strip+lower**, so `Args :` (space
112
+ before the colon) or `ARGUMENTS:` are *not* stop headers and end up inside
113
+ the description.
114
+ - `Options:`, `option:`, `Attributes`, `Yields:`, `See Also:`, `Todo:`,
115
+ `description` are *not* in the set, so they also stay inside the
116
+ description.
117
+ - reST fields (`:param a: ...`) are not recognized at all and remain in the
118
+ description.
119
+ - A docstring with no recognized header puts the **whole docstring** into
120
+ `description`.
121
+
122
+ ### Parameter help, attempt 1: Google style `parse_google_args`
123
+
124
+ Scans for a line whose stripped form is exactly `Args:` or `Arguments:`
125
+ (anywhere in the docstring, indentation irrelevant). If found, it parses
126
+ entries until an **unindented line ending with `:`** (the next section
127
+ header) or end of docstring.
128
+
129
+ An entry is an **indented** line matching
130
+
131
+ ^\s*([A-Za-z_]\w*)\s*(\([^)]*\))?\s*:\s*(.*)$
132
+
133
+ i.e. `name: text` or `name (type): text`; the parenthesized type is parsed
134
+ and **discarded** (the signature decides `type`). Continuation behaviour:
135
+
136
+ - Any later line that is not itself an entry header is appended (stripped)
137
+ to the current parameter's help, joined with a single space — including
138
+ lines at the left margin that merely fail the regex. A non-matching
139
+ indented line after an entry is therefore *swallowed into the previous
140
+ parameter's help*.
141
+ - Blank lines inside a section are dropped (they append `""` which
142
+ `" ".join` collapses).
143
+ - An entry with an empty description yields the empty string, and a
144
+ parameter named in `Args:` but absent from the function signature is
145
+ silently dropped later by `describe_function`.
146
+
147
+ ### Parameter help, attempt 2: NumPy style
148
+
149
+ Runs only when the Google parser found nothing. Looks for a line whose
150
+ stripped, lower-cased form is `parameters` followed by a line consisting
151
+ only of dashes. Entries are then **unindented** lines containing a colon;
152
+ the text before the first colon is the parameter name and the following
153
+ indented lines are its help (joined with single spaces).
154
+
155
+ - The classic NumPy layout `a : int` on the entry line puts the *type* into
156
+ the name split: `a` becomes the name (`a : int` splits at the first colon
157
+ giving `a `, stripped to `a`), and the type is silently dropped.
158
+ - An **unindented** line that does not contain a colon terminates the
159
+ section — which is why a NumPy `Returns` header with its dashes swallows
160
+ the dashes into the last parameter's help instead of stopping.
161
+
162
+ ### What the parser does not capture
163
+
164
+ - Return descriptions. The emitted metadata has only the `returns` type
165
+ string derived from the annotation; `Returns:` text is never stored.
166
+ - reST `:param:`/`:type:` fields.
167
+ - `Options:`, `Attributes:`, `Yields:`, `See Also:`, `Notes:` content —
168
+ these merely terminate the Google section (any unindented `...:` line
169
+ does) or stay in the description.
170
+
171
+ ### Verified probe outcomes
172
+
173
+ | docstring | result |
174
+ |-----------|--------|
175
+ | none | `description: ""`, `help: ""` |
176
+ | Google `name: text` + wrapped line | help = `text` + `" "` + wrapped |
177
+ | Google `name (type): text` | type ignored, help = `text` |
178
+ | Google entry with empty text | help = `""` |
179
+ | NumPy `Parameters` + dashes + `a : int` + indented help | help = indented lines joined |
180
+ | NumPy followed by `Returns` + dashes | dashes land in the last help string |
181
+ | `Args :` (space before colon) | not a header: rest goes into description, help `""` |
182
+ | reST `:param a:` / `:type a:` | fields stay in description, help `""` |
183
+ | `Arguments:` | recognized like `Args:` |
184
+ | `Params:` | **not** recognized by either parser |
185
+ | documented name not in signature | dropped |
186
+ | parameter with no entry | help `""` |
187
+
188
+ ## The generated CLI
189
+
190
+ When `scout.task` files are run as programs, the deferred dispatcher builds
191
+ one `argparse` parser per invocation.
192
+
193
+ ### Flags
194
+
195
+ - Every parameter becomes `--name` (`--scout-output` is reserved; see below).
196
+ - `list[...]` parameters get `nargs='+'` with a caster for the declared
197
+ element type (`integer` -> `int`, `float` -> `float`, `path` -> `Path`,
198
+ otherwise `str`).
199
+ - `boolean` parameters: only `default is True` (an explicit `= True`)
200
+ yields `argparse.BooleanOptionalAction`, so both `--flag` and
201
+ `--no-flag` work; any other default (including `None` and `False`) yields
202
+ `action="store_true"` with `default=False`, i.e. the flag can only turn
203
+ it **on** (verified: `flag: bool = False` shows `--flag` with no value,
204
+ and running without it returns `flag=False`).
205
+ - `integer` -> `int`, `float` -> `float`, `path` -> `Path`, anything
206
+ else (including `string`, `binary`, `array`, and unmapped types) -> `str`.
207
+ - `--scout-metadata` is not an argparse flag at all: it is tested directly
208
+ against `sys.argv` before parsing. `--scout-output` is the only argparse
209
+ flag the runner adds itself.
210
+ - `required` comes from `describe_function`: a parameter with no default
211
+ is required; `help` is the parsed docstring entry.
212
+ - `*args`/`**kwargs` parameters are described like ordinary required
213
+ parameters with type `"string"` (`--args ARGS`, `--kw KW`); they are not
214
+ filtered out (verified), so such a task is nearly unusable from the CLI
215
+ unless you pass them explicitly.
216
+
217
+ ### Dispatch rules (verified)
218
+
219
+ | argv | behaviour |
220
+ |------|-----------|
221
+ | `--scout-metadata` (anywhere in argv) | print the JSON array with the metadata of **all** tasks registered so far, exit 0 |
222
+ | `-h` / `--help` in `argv[1:]` | show the help of the selected task (`argv[1]`), or of the **last** registered task when `argv[1]` is missing/not a task name |
223
+ | `<taskname> --flags...` | run that task; exit 0 on success, 1 on exception |
224
+ | unknown `<taskname>` (run path) | stderr `[scout.task] Unknown task '<name>'`, exit code stays **0** (the `sys.exit(2)` there is swallowed by atexit) |
225
+ | unknown `<taskname>` + `-h` (help path) | same message on stderr but **exit 2**, because the help branch uses `os._exit(2)` |
226
+ | no `argv[1]`, no `-h` | run the **last** registered task with the given flags |
227
+
228
+ Notes (verified):
229
+
230
+ - `--scout-metadata` is matched as a literal element of `sys.argv`, so it
231
+ wins even when placed after a task name, and `--scout-metadata=1` would
232
+ not match.
233
+ - A single-function file still prints a **list** with one element; there is
234
+ no single-object variant. The deferred handler checks `--scout-metadata`
235
+ first and prints the whole registry; `_run_cli` has a second,
236
+ unreachable-in-practice check of its own that would print a single
237
+ object. So the list-of-objects form is the contract the Ruby side sees
238
+ (`read_python_metadata` does `JSON.parse(out.read)` on the process output
239
+ and iterates the result).
240
+ - After a successful run the handler calls `os._exit(code)` (not
241
+ `sys.exit`), so nothing after it runs — and no `atexit` callbacks run
242
+ either; stdout/stderr are flushed explicitly beforehand.
243
+ - Help with an **unknown** task name is different from help with no task
244
+ name: `<bogus> -h` prints `[scout.task] Unknown task '<bogus>'` on stderr
245
+ and exits **2** via `os._exit(2)` in the help branch (verified with
246
+ `two_task.py bogus -h`), whereas `-h` alone picks the last task and
247
+ exits 0.
248
+ - After a help request the process exits 0; `argparse` writes the help to
249
+ stdout.
250
+
251
+ ### Output serialization
252
+
253
+ The dispatcher in `_scout_run_deferred` applies these rules to the function's
254
+ return value when no `--scout-output` was given (all verified with
255
+ `od -c`):
256
+
257
+ 1. `bytes`/`bytearray` -> written raw to `sys.stdout.buffer`, **no trailing
258
+ newline**.
259
+ 2. `None`, `str`, `int`, `float`, `bool` -> `print(...)`; `None` prints an
260
+ empty line.
261
+ 3. `list`/`tuple` -> one `print` per item:
262
+ - `None` items print an empty line,
263
+ - `bytes`/`bytearray` items are written raw **followed by a newline**,
264
+ - everything else is printed via `print(item)`.
265
+ 4. Anything else -> `json.dumps(result, default=str, ensure_ascii=False)`.
266
+ `default=str` means a `set` serializes as the *string* `"{1, 2}"` and an
267
+ arbitrary object as `"OBJ"` (its `str()`), wrapped in JSON quotes.
268
+ When even `json.dumps` raises, `str(result)` is printed as a last
269
+ resort.
270
+
271
+ When `--scout-output PATH` **is** given the code takes a **different**
272
+ branch: `_write_output(path, result)` does
273
+ `path.parent.mkdir(parents=True, exist_ok=True)` and then writes either
274
+ `path.write_bytes(result)` for `bytes`/`bytearray`, or
275
+ `path.write_text(str(result))` for everything else. So with a file
276
+ destination:
277
+
278
+ - a `dict` is written as its Python `str()` (`{'a': {'b': [1, 2]}}`, not
279
+ JSON),
280
+ - a `list` is written as `[1, 2, 'z']` (the `repr`, not newline-separated),
281
+ - only `bytes` keep their raw form.
282
+
283
+ The stdout cascade and the file branch therefore **do not agree**: stdout
284
+ gives JSON for dicts and newline-separated items for lists, the file gives
285
+ `str()` for both.
286
+
287
+ A parameter literally named `scout_output` collides with the reserved flag
288
+ destination. The collision is invisible at the *flag* level (argparse
289
+ derives `--scout_output`, single underscore, from the parameter name, while
290
+ the reserved flag is `--scout-output`), but both flags write the same
291
+ namespace key `scout_output`. Verified outcomes for such a parameter: the
292
+ result is written to whatever path was given and the function receives
293
+ `None` for its own `scout_output` argument — regardless of whether the
294
+ reserved `--scout-output V` or the user's `--scout_output V` form was used.
295
+ A parameter with a default that merely happens to be named something else
296
+ keeps its value normally (verified: the default is only shadowed by the
297
+ name `scout_output`).
298
+
299
+ ### Exit codes
300
+
301
+ | situation | exit code |
302
+ |-----------|-----------|
303
+ | success | 0 |
304
+ | task function raised | 1 (message `[scout.task] Error: ...` on stderr; `os._exit(1)`) |
305
+ | argparse usage error | 2 |
306
+ | unknown task name | 0 when running, 2 when `-h` was also given (message on stderr) |
307
+
308
+ ## Import-time vs run-time
309
+
310
+ `scout.task(func)` computes `describe_function(func)` eagerly and stores the
311
+ result as the attribute `func.__scout_meta__` (the actual attribute name —
312
+ **not** `__scout_task_metadata__`), and appends `func` to the module-global
313
+ `_SCOUT_TASK_REGISTRY`. Only when the *defining module is `__main__`* does
314
+ it also register the `atexit` dispatcher `_scout_run_deferred`.
315
+
316
+ Consequences (verified):
317
+
318
+ - Importing a module that decorates functions is safe as long as
319
+ `inspect.signature` can read each signature; no CLI runs, because the
320
+ module's `__name__` is not `__main__` (verified: importing such a module
321
+ registers the task in `scout.runner._SCOUT_TASK_REGISTRY` but the body
322
+ never executes).
323
+ - Running such a file **as a program always dispatches**, even when the
324
+ import was made for library purposes: the dispatcher checks
325
+ `sys.argv[1]`, and when no task name matches it falls back to the **last
326
+ registered task** — which will then demand its required arguments
327
+ (exit 2) or execute.
328
+ - Both the unknown-task and the argparse-error paths raise `SystemExit`
329
+ inside the `atexit` callback. Python ignores `SystemExit` coming from an
330
+ `atexit` handler (it prints the traceback and keeps going), so the code
331
+ requested there is not honoured. Concretely CPython prints
332
+ `Exception ignored in atexit callback <function task.<locals>._scout_run_deferred ...>`
333
+ plus a short traceback before exiting normally. The **observable** codes
334
+ (verified) are: missing required argument -> 2, unknown task name -> 0 on
335
+ the run path but 2 when combined with `-h` (message on stderr either way),
336
+ successful run -> 0, function exception -> 1.
337
+
338
+ ## Known gaps (verified)
339
+
340
+ - `python/pyproject.toml` declares `version = "0.2.4"` while the gem is at
341
+ `0.2.6` (`gem` `VERSION` file and the regenerated gemspec at HEAD 290ee22);
342
+ the two are not synchronized. The classifiers also stop at Python 3.12
343
+ while `requires-python` is `>=3.10`.
344
+ - `python/build/lib/scout/` and `python/scout_rig.egg-info/` are stale
345
+ build artifacts sitting in the tree (verified: at HEAD the copies are
346
+ byte-identical to `python/scout/`, and the egg-info still records
347
+ `Version: 0.2.4`). They are ignored by `python/.gitignore` (`build/`
348
+ and `*.egg-info/`), so git does not track them, but any packaging run
349
+ that consults them (an editable install, a wheel built from the stale
350
+ tree) can ship the old version string; delete them before packaging.
351
+ - `python/test.py` is an ad-hoc script (it shells out to the `Baking`
352
+ example workflow and requires it installed); the Ruby rake tasks do not
353
+ run any Python test, and no test framework is configured for the Python
354
+ package at all (no `[tool.pytest]` in `pyproject.toml`, no tests
355
+ directory).
356
+ - `scout.workflow` is a module, not a package, so
357
+ `scout.workflow.remote` cannot be imported normally (see
358
+ [Driving Workflows from Python](../user/DrivingWorkflowsFromPython.md)).
359
+ - `requests` is imported unconditionally at the top of `remote.py` although
360
+ the pyproject lists it only under the `remote` extra.
361
+ - `save_inputs` in `python/scout/workflow.py` is a `return`-only stub: dead
362
+ code, never called by anything in `python/`, `lib/`, or `test/` (only
363
+ `save_job_inputs` in `scout/__init__.py` is used, by `run_job`). This
364
+ confirms Improvements item B4 as still open.
365
+
366
+ ## See also
367
+
368
+ - [PythonWorkflow Internals](PythonWorkflowInternals.md) — the Ruby side
369
+ that consumes this metadata.
370
+ - [Driving Workflows from Python](../user/DrivingWorkflowsFromPython.md) —
371
+ the user-facing view of the `scout` package.