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,539 @@
1
+ # PythonWorkflow Internals
2
+
3
+ This document explains how `python_task` works internally: how Python
4
+ function metadata is discovered, how types are mapped, and how tasks are
5
+ executed at runtime.
6
+
7
+ ## Audience
8
+
9
+ This page is intended for:
10
+
11
+ - ✓ Framework contributors
12
+ - ✗ Workflow authors (see [Defining Python Tasks](../user/DefiningPythonTasks.md))
13
+
14
+ ## Why this exists
15
+
16
+ The challenge PythonWorkflow solves is: **how do you make a Python function
17
+ into a Scout task without requiring the user to redeclare inputs on both
18
+ sides?**
19
+
20
+ The solution is **metadata-driven task definition**. The Python function's
21
+ signature (type hints, defaults) and docstring (parameter descriptions) are
22
+ introspected at workflow definition time, automatically producing the Scout
23
+ task declaration.
24
+
25
+ A standalone `Extension: suffix` field in a function docstring is returned as
26
+ optional per-function metadata. Ruby applies that suffix to the function's
27
+ result path ahead of the file-level `python_task extension:` fallback; absent
28
+ the field, the existing file-level/default behavior remains. The suffix only
29
+ selects the result path extension and does not alter result conversion.
30
+
31
+ ## Architecture
32
+
33
+ ```
34
+ Workflow definition time
35
+ ────────────────────────
36
+ Ruby: python_task :hello
37
+ │
38
+ ▼
39
+ Ruby: read_python_metadata(file) ───► Python subprocess: file.py --scout-metadata
40
+ │ │
41
+ │ JSON parse │ describe_function()
42
+ ▼ │ (runner.py: introspect signature + docstring)
43
+ Ruby: metas = [{name, description, returns, params, extension?}, ...]
44
+ │
45
+ ▼
46
+ Ruby: For each meta:
47
+ - map_returns(meta['returns']) → Scout return type
48
+ - For each param: map_param → Scout input
49
+ - task(name => return_type) { ... }
50
+
51
+
52
+ Task execution time
53
+ ───────────────────
54
+ Ruby: job.run
55
+ │
56
+ ▼
57
+ Ruby: build_python_argv(meta_params, positional values) ───► CLI argv
58
+ (block receives inputs positionally, in metadata param order;
59
+ Shellwords.shelljoin([fn_name] + argv) ───► one shell string)
60
+ │
61
+ ▼
62
+ Ruby: ScoutPython.run_file(file, arg_str) ───► Python subprocess
63
+ │
64
+ │ stdout = return value
65
+ ▼
66
+ Ruby: decode result (JSON → array split → string)
67
+ ```
68
+
69
+ `PythonWorkflow.load_directory(path, workflow_name)` is the bulk form: it
70
+ builds a fresh anonymous module (extending both `Workflow` and
71
+ `PythonWorkflow`), registers it under a constant, points
72
+ `python_task_dir` at `path` (defaulting to `Scout.python.task` when
73
+ omitted) and calls `python_task` for every `*.py` file found by
74
+ `path.glob_names("*.py")`. Verified details:
75
+
76
+ - `path` must be a `Path`-like object responding to `glob_names`; a plain
77
+ String raises `NoMethodError: undefined method 'glob_names'`.
78
+ - The default `workflow_name` is the constant `PythonWorkflow`, and
79
+ `Kernel.const_set` **overwrites** an existing constant of that name (Ruby
80
+ warns "already initialized constant"). The two-argument form
81
+ `load_directory(dir)` still uses `PythonWorkflow`; `load_directory(dir,
82
+ name)` sets a custom constant name.
83
+ - Names containing `/` (or any invalid constant characters) raise
84
+ `NameError: wrong constant name ...` from `const_set`.
85
+ - An empty directory yields a module with no tasks and does not fail.
86
+ - Only the directory given is scanned; there is no recursion into
87
+ subdirectories (verified: `sub/one.py` is not registered).
88
+
89
+ ## Directory metadata loading
90
+
91
+ `load_python_tasks(batch: true)` is the reusable directory loader. Its default
92
+ is the batch path: all `*.py` task file metadata is gathered with one
93
+ `--scout-metadata-files` runner process and passed into task registration. With
94
+ `batch: false`, each `*.py` task file is inspected by an individual metadata
95
+ subprocess instead.
96
+
97
+ `PythonWorkflow`'s extension hook does not preload tasks; it prepares the
98
+ workflow to use Python tasks. Assigning `python_task_dir=` then loads that
99
+ directory in batch mode, so the supported lifecycle is to define/extend the
100
+ `Workflow` first, extend `PythonWorkflow` second, and assign the task directory
101
+ afterward:
102
+
103
+ ```ruby
104
+ module TestWF
105
+ extend Workflow
106
+ end
107
+ TestWF.extend PythonWorkflow
108
+ TestWF.python_task_dir = Path.setup("python/tasks")
109
+ ```
110
+
111
+ The setter must call `load_python_tasks`; there is no `load_tasks` method in
112
+ this extension. `PythonWorkflow.load_directory(path, name, batch: false)`
113
+ explicitly requests per-file metadata discovery; its default is `batch: true`,
114
+ and `load_directory(path, name, literal_strings: true)` initializes
115
+ `python_literal_strings` before any registration (the plain setter does not
116
+ re-register anything). These keyword forms do not change the extension hook's
117
+ batch selection.
118
+
119
+ Batch runner execution sets each file's `__name__` to `__main__` and captures
120
+ registrations, including registrations guarded by `if __name__ == '__main__'`.
121
+ It reuses one interpreter for all files. A reproduced same-process caveat is
122
+ that imported modules are cached: a task registered only as a shared-import
123
+ side effect can be included for the first file but absent for a later file.
124
+ This establishes that batch behavior is not fully equivalent to separate
125
+ per-file processes; use the default per-file mode when isolation from shared
126
+ module state is required. These notes describe tested behavior, not a claim
127
+ that all stateful Python programs are supported equivalently.
128
+
129
+ ### Re-registration and inspection
130
+
131
+ - `refresh_python_tasks!` re-runs the directory load and reconciles the
132
+ registered tasks with what the files currently export, returning
133
+ `{added:, changed:, removed:, unchanged:}`. The lifecycle is strictly
134
+ ordered: **collect** the current file metadata (one batch metadata
135
+ subprocess) → **decide** (added/changed/removed/unchanged per *name*,
136
+ including the `python_literal_strings` config-compare path and tasks
137
+ relocated between files) → **validate** the complete desired state →
138
+ **apply**.
139
+ - **Failure policy (validate-before-mutate):** the complete desired state —
140
+ metadata shape, duplicates, names exported by two files, collisions with
141
+ native (Ruby-defined) tasks — is validated before the first mutation, so
142
+ a failed refresh raises with the registry and the tracking map exactly
143
+ as they were. There is no snapshot/rollback machinery and none is needed:
144
+ nothing is mutated until everything is known to be valid.
145
+ - **Tracking is a plain map:** `@python_task_registrations` is
146
+ `file -> {metas:, literal_strings:}` — names and metadata, no task
147
+ objects. Task-object identity is not tracked at all; unchanged tasks
148
+ simply keep the task object the previous registration installed, and
149
+ ownership is decided from the live task's provenance (a task whose block
150
+ was defined in `python/task.rb` is a PythonWorkflow registration).
151
+ - **Registration is per-task:** a file with any added/changed task is
152
+ re-registered through `python_task` with ONLY those metas, so the
153
+ unchanged siblings keep their task objects and the in-process
154
+ `Workflow.job_cache` entries keyed to a surviving sibling stay live and
155
+ retrievable; the file's tracking record is then committed once with
156
+ *all* current metas for that file, so desired tracking equals the
157
+ applied registry.
158
+ - **Idempotency:** a second refresh with unchanged sources is a pure no-op
159
+ (empty `added`/`changed`/`removed`, `unchanged` populated, same task
160
+ objects in place). Native Ruby tasks in the workflow are untouched. Use
161
+ it after editing Python sources in-process.
162
+ - `python_input_contracts` / `python_input_contract` expose the single
163
+ authoritative input-contract view per task (Python annotation, Scout
164
+ type, default, required, `behavior`, `flags`), built from the stored
165
+ registration metadata — not from a fresh extraction of the live task's
166
+ inputs. See
167
+ [DefiningPythonTasks](../user/DefiningPythonTasks.md) for the
168
+ `behavior` column values.
169
+ - `python_literal_strings` is resolved at **registration time** (the input
170
+ options, including `noload`, are built when the task registers). Flip it
171
+ before loading, or refresh afterwards.
172
+
173
+ ## Phase 1: Metadata discovery
174
+
175
+ ### read_python_metadata(file)
176
+
177
+ Actual code at HEAD (`lib/scout/workflow/python/task.rb`):
178
+
179
+ ```ruby
180
+ def self.read_python_metadata(file)
181
+ out = ScoutPython.run_file file, '--scout-metadata'
182
+ raise "Error getting metadata from #{file}" unless out.exit_status == 0
183
+ JSON.parse(out.read)
184
+ end
185
+ ```
186
+
187
+ Consequences:
188
+
189
+ - **JSON errors are not wrapped.** A zero exit with non-JSON stdout raises
190
+ a bare `JSON::ParserError` from `JSON.parse(out.read)`.
191
+ - **Metadata is validated before any DSL side effect.**
192
+ `validate_python_task_metadata` runs in `register_python_task_metadata`
193
+ before the registrations hash or any `input`/`task` DSL call is touched,
194
+ and raises for: an empty metas list ("No tasks exported by <file>"), a
195
+ meta that is not a Hash, a missing `name` or `params` key, `params`
196
+ that is not a list, a duplicate task name *within* one metas list, and
197
+ a name that collides with a task already registered from a *different*
198
+ file. Re-registering from the same file replaces the previous entry, so
199
+ `refresh_python_tasks!` keeps working.
200
+
201
+ This runs the Python file as a subprocess with `--scout-metadata`. The
202
+ Python `scout.runner` module handles this flag:
203
+
204
+ ```python
205
+ # runner.py: _scout_run_deferred (atexit handler)
206
+ if '--scout-metadata' in sys.argv:
207
+ metas = [getattr(func, '__scout_meta__', None)
208
+ for func in _SCOUT_TASK_REGISTRY]
209
+ print(json.dumps(metas))
210
+ os._exit(0)
211
+ ```
212
+
213
+ The metadata is a list of dicts, one per registered function. A
214
+ single-function file prints a one-element list; `python_task` accepts
215
+ either a list or a bare dict (`metas = [metas] unless Array === metas`). An
216
+ empty list is rejected by validation ("No tasks exported by <file>")
217
+ before any DSL call; a file that registers no function prints nothing at
218
+ all and still fails earlier, at the `JSON.parse`.
219
+
220
+ The metadata keys actually consumed by `python_task` are `name`,
221
+ `description`, `returns` and `params`; each param uses `name`, `type`,
222
+ `required`, `default` and `help`. Note that `describe_function` keys
223
+ `required` on the *absence of a default*, not on the annotation.
224
+
225
+ ### Metadata structure
226
+
227
+ Each metadata dict from Python has:
228
+
229
+ ```json
230
+ {
231
+ "name": "hello",
232
+ "description": "Greet a person.",
233
+ "returns": "string",
234
+ "params": [
235
+ {"name": "name", "type": "string", "required": true, "default": null, "help": "..."},
236
+ {"name": "excited", "type": "boolean", "required": false, "default": false, "help": "..."}
237
+ ]
238
+ }
239
+ ```
240
+
241
+ (There is no `function_name` key; the emitted keys are `name`,
242
+ `description`, `returns`, `params`.)
243
+
244
+ ## Phase 2: Type mapping
245
+
246
+ ### map_param(param, literal_strings: false)
247
+
248
+ Maps a Python parameter to a Scout input type declaration. The
249
+ `literal_strings` flag (resolved from the workflow's
250
+ `python_literal_strings` at registration time) adds `noload` to
251
+ `str`-mapped inputs so a Ruby `String` naming an existing file is no
252
+ longer read into its contents.
253
+
254
+ `map_param` matches the exact strings emitted by
255
+ `describe_function` — those are `string`, `integer`, `float`, `boolean`,
256
+ `binary`, `path`, `list[...]` or `None` (no `str`/`int`/`bool` aliases, no
257
+ `task`). Unsupported annotations fail loudly at metadata time on the
258
+ Python side, so the final `:string` fallback is defensive rather than a
259
+ reachable degradation path:
260
+
261
+ | Python type string | Scout type |
262
+ |--------------------|------------|
263
+ | `string` | `:string` |
264
+ | `integer` | `:integer` |
265
+ | `float` | `:float` |
266
+ | `boolean` | `:boolean` |
267
+ | `binary` | `:binary` |
268
+ | `path` | `:file` |
269
+ | `list[string]`, `list[integer]`, `list[float]`, … | `:array` |
270
+ | `list[path]` | `:file_array` |
271
+ | `nil` (no annotation) | `:string` |
272
+ | (any other string) | `:string` (defensive) |
273
+
274
+ Only the subtype `path` is inspected inside `list[...]`; every other
275
+ subtype (`list[integer]`, `list[bytes]`, …) collapses to `:array`.
276
+
277
+ `map_param` also sets `required: true` in the input options when the Python
278
+ param has no default, and copies `default` and `help` verbatim into the
279
+ Scout input declaration.
280
+
281
+ ### map_returns(return_type)
282
+
283
+ Maps a Python return annotation to a Scout task return type.
284
+
285
+ `map_returns` matches the exact strings emitted by `describe_function` —
286
+ `string`, `integer`, `float`, `boolean`, `binary`, `path`, `array`, or
287
+ anything beginning with `list[` (no `int`/`bool` aliases, and a bare
288
+ `list` is *not* recognized because a bare `list` annotation is reported as
289
+ the plain type string, not `list[...]`). Unsupported return annotations
290
+ now fail loudly at metadata time on the Python side, so the final
291
+ `:string` fallback below is a defensive default rather than a reachable
292
+ degradation path:
293
+
294
+ | Python type string | Scout type |
295
+ |--------------------|------------|
296
+ | `nil` / JSON `null` (no annotation) | `:string` |
297
+ | `string` | `:string` |
298
+ | `integer` | `:integer` |
299
+ | `float` | `:float` |
300
+ | `boolean` | `:boolean` |
301
+ | `binary` | `:binary` |
302
+ | `path` | `:string` |
303
+ | `array` | `:array` |
304
+ | `list[...]` (any subtype) | `:array` |
305
+ | (any other string) | `:string` |
306
+
307
+ **Note:** `path` returns map to `:string` (not `:file`) because the path
308
+ value is a string result, not a file input. See [Improvements](../Improvements.md)
309
+ for a discussion.
310
+
311
+ ## Phase 3: Task declaration
312
+
313
+ For each metadata object, PythonWorkflow declares a Scout task:
314
+
315
+ ```ruby
316
+ python_task :hello # reads metadata for all functions in hello.py
317
+ ```
318
+
319
+ For a multi-function file, this creates one task per function. The task
320
+ body is defined in a block that executes the Python function as a
321
+ subprocess.
322
+
323
+ Details of the per-meta declaration loop (verified):
324
+
325
+ - `ruby_inputs` is `[]` when `meta['params']` is `nil` (this guard was
326
+ added in 8c4d941, "Fixed issue with missing parametesr in python tasks");
327
+ an empty `params: []` array behaves the same.
328
+ - Each input is declared with `input(name, type, desc, default, options)`;
329
+ `options` carries only `required: true` when applicable.
330
+ - `self.desc(task_desc)` is called once per meta, where
331
+ `task_desc = desc || meta['description']`. The `desc:` kwarg therefore
332
+ overrides the docstring description **for every** function in the file.
333
+ - `extension(extension)` is likewise applied to every declared task.
334
+ - `meta['returns'] = returns.to_s if returns` — the `returns:` kwarg
335
+ overrides the return type string for every function too, and an unknown
336
+ string (`'yaml'`) silently maps through `map_returns` to `:string`.
337
+ - The task name is `meta['name']`, i.e. the Python function name, not the
338
+ `python_task` argument. Registering the same function name twice
339
+ overwrites the earlier task silently.
340
+ - The declared Scout return type is `map_returns(meta['returns'])`, which
341
+ may be `:string` (never `nil`), so `task(name => type)` always receives
342
+ a concrete type symbol.
343
+
344
+ ### Task file discovery
345
+
346
+ `python_task` locates the Python file using:
347
+
348
+ 1. `file:` option if provided. The file is used verbatim (no pathmap
349
+ lookup); a missing file raises
350
+ `RuntimeError: Python task file not found: <file>`.
351
+ 2. Otherwise, `python_task_dir[task_name].find_with_extension('py')`, and
352
+ the same existence check runs on the resolved path.
353
+
354
+ `python_task_dir` defaults to `Scout.python.tasks.find`, which returns the
355
+ first existing `python/tasks` directory in the Scout pathmap order and
356
+ otherwise falls back to the user path (`~/.scout/python/tasks`) even when it
357
+ does not exist.
358
+
359
+ ## Phase 4: Execution
360
+
361
+ ### build_python_argv(params, values)
362
+
363
+ Actual code at HEAD (`lib/scout/workflow/python/inputs.rb`):
364
+
365
+ ```ruby
366
+ def self.build_python_argv(params, values)
367
+ values = values.transform_values { |v| String === v ? v.strip : v }
368
+ params.map do |param|
369
+ name, value = param.values_at("name", "default")
370
+ ...
371
+ end
372
+ end
373
+ ```
374
+
375
+ Consequences:
376
+
377
+ - The value mapping is decided by the **value's class**, not the declared
378
+ Python type: an `Array` emits one argv word per element; a `String`
379
+ containing commas splits on commas; any other single value emits one
380
+ word. Arrays serialize literally, full stop — the bridge never reads a
381
+ file for a list value.
382
+ - `nil` is the only "missing" spelling: a `nil` value emits no flag, while
383
+ an empty string still emits `--name ''`
384
+ (so `''` is distinguishable from a missing input).
385
+
386
+ | Input type | Ruby value handling |
387
+ |------------|---------------------|
388
+ | nil | Nothing emitted |
389
+ | boolean (no default or default false) | `--name` if true, nothing if false |
390
+ | boolean (default true) | `--name` if true, `--no-name` if false |
391
+ | list (String with comma) | Split by comma, parts stripped |
392
+ | list (other String) | Single item |
393
+ | list (Array) | One argv word per element, taken literally |
394
+ | path/file | Passed as-is |
395
+ | scalar | `--name value` (empty string still emits `--name ''`) |
396
+
397
+ Ambiguities (Improvements A3): comma-containing elements cannot be
398
+ expressed through a comma-separated string (they are split) — pass an
399
+ `Array`; elements beginning with `-` are emitted bare and are then parsed
400
+ by argparse as options (exit status 2); an empty-string element produces
401
+ an empty argv word. Note the *Scout input layer* (`:array` inputs) may
402
+ still expand a bare-filename `String` into its lines before the task
403
+ block runs; that is Scout-native behaviour, outside this workflow (see
404
+ [DefiningPythonTasks](../user/DefiningPythonTasks.md)).
405
+
406
+ ### run_file and shell quoting
407
+
408
+ ```ruby
409
+ ScoutPython.run_file(file, arg_str)
410
+ # → CMD.cmd("env PYTHONPATH=... python '#{file}' #{arg_str}")
411
+ ```
412
+
413
+ `python_task` builds `arg_str` with `Shellwords.shelljoin(full_argv)` where
414
+ `full_argv = [function_name] + argv`. This protects values containing
415
+ spaces, semicolons, parentheses or commas, but has two consequences:
416
+
417
+ - The **file path itself** is interpolated with Ruby string quoting
418
+ (`'#{file}'`), not Shellwords. A file named `it's.py` produces a broken
419
+ shell command (`sh: Syntax error: Unterminated quoted string`, exit
420
+ status 2).
421
+ - Values beginning with `-` survive shelljoin (they are emitted bare), so
422
+ argparse still rejects them (`argument --s: expected one argument`,
423
+ exit status 2). There is no `--` separator in the generated command.
424
+
425
+ ### Return value decoding
426
+ PythonWorkflow task execution passes `SCOUT_JOB_FILES_DIR` through the
427
+ `run_file` child-only `env:` option, using the executing Step's `files_dir`.
428
+ This identifies the job's `.files` auxiliary-file directory; Python task code
429
+ can use it to create outputs that belong with the job. `run_file` first removes
430
+ any inherited `SCOUT_JOB_FILES_DIR` from the child, then applies explicit
431
+ `env:` values. Thus metadata discovery and direct calls without a Step have no
432
+ job directory and cannot accidentally observe a stale parent value. The Ruby
433
+ process environment is never mutated. Other runner calls do not set this
434
+ variable.
435
+
436
+
437
+ The Python function's return value is printed to stdout. Ruby decodes it:
438
+
439
+ ```ruby
440
+ txt = run_output.read
441
+ begin
442
+ JSON.parse(txt)
443
+ rescue
444
+ if ruby_returns == :array || ruby_returns == :file_array
445
+ txt.split("\n").map(&:to_s)
446
+ else
447
+ txt.strip
448
+ end
449
+ end
450
+ ```
451
+
452
+ The heuristic is:
453
+ 1. Try JSON first (handles dicts, nested lists, numbers, booleans — and,
454
+ unintentionally, any plain string that happens to be valid JSON).
455
+ 2. If JSON fails and the return type is `:array` or `:file_array`, split on
456
+ newlines.
457
+ 3. Otherwise, return stripped text.
458
+
459
+ Note that the split applies to the whole stdout including any stray prints;
460
+ and the newline split always produces Strings, so a `list[int]` return
461
+ yields `["1", "2"]` in Ruby, not integers (verified). The runner serializes
462
+ lists one item per line (`runner.py`), so the JSON branch is normally only
463
+ taken for dict-like returns.
464
+
465
+ ## Key design decisions
466
+
467
+ 1. **Metadata-driven, not attribute-driven** — Task definition is driven by
468
+ Python function metadata, not by Ruby-side configuration. This eliminates
469
+ double-declaration.
470
+
471
+ 2. **Subprocess execution** — Each task run spawns a new Python process.
472
+ This is slower than in-process but avoids GIL contention, memory leaks,
473
+ and state contamination between tasks.
474
+
475
+ 3. **CLI-first communication** — Communication between Ruby and Python is
476
+ via CLI arguments (inputs) and stdout (return value). This is the Unix
477
+ philosophy: text as the universal interface.
478
+
479
+ 3b. **Multi-function files** — A single Python file can define multiple
480
+ tasks. The first positional argument in the CLI argv selects the function
481
+ (`full_argv = [meta['name']] + argv`). The selector is the *metadata*
482
+ name, which for a plain `scout.task(fn)` call is the function name; a
483
+ single-function file ignores the positional entirely, while a
484
+ multi-function file without it fails in argparse (exit status 2), and an
485
+ unknown name makes the runner print `[scout.task] Unknown task 'x'` and
486
+ exit non-zero.
487
+
488
+ 4. **Heuristic return decoding** — JSON is tried first (handles structured
489
+ data), with fallbacks for arrays (newline-split) and plain text. This
490
+ covers the vast majority of use cases.
491
+
492
+ 5. **Type mapping mirrors Python annotations** — The mapping table is a
493
+ straightforward mapping from Python type strings to Scout types. The
494
+ Python side produces type strings via `describe_function`.
495
+
496
+ ## Known issues
497
+
498
+ 1. **Unused `err` variable** (Improvements B1 — **resolved**) — the raise
499
+ in `read_python_metadata` no longer interpolates an undefined local;
500
+ it is now `raise "Error getting metadata from #{file}"`. In practice
501
+ `ScoutPython.run_file` → `CMD.cmd` still raises `ProcessFailed` on a
502
+ non-zero exit before this check runs, so the user-facing failure
503
+ remains a `ProcessFailed` with the interpreter's stderr embedded.
504
+
505
+ 2. **No metadata caching** (Improvements O1, verified still true at HEAD) —
506
+ `read_python_metadata` runs a Python subprocess every time `python_task`
507
+ is called, with no memoization by path, mtime or content; identical
508
+ calls re-execute the file. Measured: ~0.4–0.5 s per single registration,
509
+ ~1.3 s for `load_directory` over three files (interpreter startup
510
+ dominates). Definition time therefore scales linearly with the number of
511
+ registered functions, and import-heavy Python files pay their import
512
+ cost once per registration.
513
+
514
+ 3. **String split ambiguity** (Improvements A3 — **resolved**) — In
515
+ `build_python_argv`, list inputs given as strings are split by comma, so
516
+ `'a,b'` becomes two elements while `['a,b']` stays one. Elements
517
+ beginning with `-` break argparse. The bridge serializes an `Array`
518
+ literally, full stop; pass an `Array` to keep comma-containing elements
519
+ intact. The Scout input layer (`:array` inputs) may still expand a
520
+ bare-filename `String` into its lines before the task block runs — that
521
+ is Scout-native behaviour, out of scope here.
522
+
523
+ 4. **Return decoding ambiguity** (verified) — If a string return value
524
+ happens to be valid JSON, it is JSON-parsed instead of returned as-is
525
+ (`"[1, 2]"` → `[1, 2]`, `"1"` → `1`). Conversely a `list` return is
526
+ serialized one item per line, so the JSON branch never sees it and the
527
+ items come back as Strings.
528
+
529
+ 5. **path return maps to :string** (Improvements A4, verified) — `path`
530
+ returns map to `:string` in Scout while `path` inputs map to `:file`.
531
+ The mapped type symbol only affects how Scout treats the value
532
+ downstream (e.g. `Step#stream`, file extension inference); the actual
533
+ path string is returned either way.
534
+
535
+ ## See also
536
+
537
+ - [Architecture](Architecture.md) — Overall module map.
538
+ - [ScoutPython Internals](ScoutPythonInternals.md) — The run_file mechanism.
539
+ - [Defining Python Tasks](../user/DefiningPythonTasks.md) — User-facing guide.