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,504 @@
1
+ # ScoutPython Internals
2
+
3
+ This document explains the internal architecture of ScoutPython, the
4
+ Ruby-facing API for executing Python code via PyCall.
5
+
6
+ ## Audience
7
+
8
+ This page is intended for:
9
+
10
+ - ✓ Framework contributors
11
+ - ✗ Workflow authors (see [Running Python from Ruby](../user/RunningPythonFromRuby.md))
12
+
13
+ ## Why this exists
14
+
15
+ PyCall provides the raw Ruby↔Python bridge, but it has several gaps that
16
+ ScoutPython fills:
17
+
18
+ 1. **No lazy initialization** — PyCall must be initialized before use,
19
+ but doesn't guard against double-init.
20
+ 2. **No threading safety** — PyCall operations require GIL acquisition.
21
+ 3. **No shutdown management** — Python objects must be GC'd before the
22
+ GIL becomes unavailable.
23
+ 4. **No import ergonomics** — PyCall requires verbose `pyimport` calls.
24
+ 5. **No subprocess alternative** — PyCall is in-process only.
25
+
26
+ ScoutPython wraps PyCall with layered execution modes, a threading model,
27
+ an at_exit hook, import helpers, and a subprocess-based scripting facility.
28
+
29
+ ## Execution mode hierarchy
30
+
31
+ Each mode composes the one below it. Understanding this layering is key to
32
+ understanding the code.
33
+
34
+ ```
35
+ run → init_scout + run_simple + GC
36
+ run_simple → MUTEX.synchronize + module_eval
37
+ run_direct → PyCall.eval (raw)
38
+ run_threaded → queue + dedicated thread + init_in_thread + run_simple
39
+ run_log → run + Log.trap_std/trap_stderr
40
+ ```
41
+
42
+ ### run_direct
43
+
44
+ ```ruby
45
+ def self.run_direct(mod = nil, *args, as: mod, import: nil, &block)
46
+ new_binding = Binding.new # fresh PyCall::Import scope
47
+ new_binding.extend mod, as: as, import: import
48
+ new_binding.instance_exec(*args, &block)
49
+ end
50
+ ```
51
+
52
+ `run_direct` creates a fresh `Binding`, extends it with the requested import,
53
+ and `instance_exec`s the block. No synchronization, no initialization
54
+ checking, no GC.
55
+
56
+ **Warning:** Using `run_direct` before PyCall is initialized will crash.
57
+ In practice a plain `require 'scout/python'` already triggers
58
+ `PyCall.init` implicitly (the `require` runs `add_paths` →
59
+ `process_paths` → `pyimport :sys`, which resolves PyCall constants and
60
+ calls `PyCall.init`), so this is a contract statement about the mode rather
61
+ than a crash you can reproduce from a fresh require — but the mode itself
62
+ performs no initialization checking.
63
+
64
+ ### run_simple
65
+
66
+ ```ruby
67
+ def self.run_simple(mod = nil, *args, as: mod, import: nil, &block)
68
+ MUTEX.synchronize do
69
+ ScoutPython.extend mod, as: as, import: import
70
+ ScoutPython.instance_exec(*args, &block)
71
+ end
72
+ end
73
+ ```
74
+
75
+ Adds `MUTEX.synchronize` for thread safety and runs the block in the
76
+ `ScoutPython` module scope (so imports persist on the module).
77
+
78
+ ### run
79
+
80
+ ```ruby
81
+ def self.run(mod = nil, *args, as: mod, import: nil, &block)
82
+ init_scout
83
+ res = run_simple(mod, *args, as: as, import: import, &block)
84
+ GC.start
85
+ res
86
+ end
87
+ ```
88
+
89
+ Adds initialization check and post-execution GC. This is the recommended
90
+ default.
91
+
92
+ Why the `GC.start`? `run` returns `PyCall` object references to Ruby, and
93
+ PyCall finalizers must run while the GIL is still held by this thread. The
94
+ `ensure`-style GC forces Python-owned objects that became unreachable
95
+ during the call to be finalized promptly rather than at an arbitrary later
96
+ point (for example during VM shutdown, after the GIL situation has
97
+ changed). It is the same rationale as the `GC.start` inside the `at_exit`
98
+ hook. Note that the `GC.start` runs **outside** `MUTEX.synchronize` —
99
+ `run_simple` releases the mutex before returning.
100
+
101
+ Also note `run` calls `init_scout`, which is what calls `PyCall.init` — so
102
+ with `run` the *calling* thread is the thread that owns PyCall for the
103
+ lifetime of the process (see `run_threaded` for why that matters).
104
+
105
+ ### run_threaded
106
+
107
+ Uses a dedicated background thread with a queue. The actual code in
108
+ `lib/scout/python/run.rb` is:
109
+
110
+ ```ruby
111
+ def self.run_in_thread(&block)
112
+ self.synchronize do
113
+ init_thread
114
+ QUEUE_IN.push block
115
+ QUEUE_OUT.pop
116
+ end
117
+ end
118
+
119
+ # init_thread's worker loop (lib/scout/python/run.rb:31-54)
120
+ Thread.new do
121
+ require 'pycall'
122
+ ScoutPython.init_scout
123
+ ScoutPython.process_paths
124
+ while block = QUEUE_IN.pop
125
+ break if block == :stop
126
+ res = module_eval(&block) # rescued, logged and re-raised
127
+ QUEUE_OUT.push res
128
+ end
129
+ end
130
+ ```
131
+
132
+ Sketch of the mechanism:
133
+
134
+ ```ruby
135
+ QUEUE_IN = Queue.new
136
+ QUEUE_OUT = Queue.new
137
+
138
+ def self.run_in_thread(mod, *args, as:, import:, &block)
139
+ init_thread # lazily creates the background thread
140
+ MUTEX.synchronize do
141
+ QUEUE_IN.push [mod, args, as, import, block]
142
+ QUEUE_OUT.pop # blocks until result is ready
143
+ end
144
+ end
145
+
146
+ # The background thread loop:
147
+ Thread.new do
148
+ ScoutPython.init_scout
149
+ ScoutPython.process_paths
150
+ loop do
151
+ item = QUEUE_IN.pop
152
+ break if item == :stop
153
+ result = begin
154
+ mod, args, as, import, block = item
155
+ run_simple(mod, *args, as: as, import: import, &block)
156
+ rescue => e
157
+ e
158
+ end
159
+ QUEUE_OUT.push result
160
+ end
161
+ end
162
+ ```
163
+
164
+ All threaded access is serialized through the queue. This is safe but
165
+ concurrent `run_threaded` calls block each other.
166
+
167
+ Verified behaviour (probes `probe_concurrency.rb` / `probe9.log`):
168
+
169
+ - `run_in_thread` holds `MUTEX` for the whole push/wait cycle, so two Ruby
170
+ threads calling `run_threaded` at the same time execute strictly one
171
+ after the other; each receives its own result. The Ruby-side blocks run
172
+ inside the single worker thread via `module_eval`, never in parallel.
173
+ - An exception raised by the block is logged (`Log.exception`) and re-raised
174
+ in the worker, which kills the worker thread; the waiting caller then
175
+ blocks forever on `QUEUE_OUT.pop` — there is no `Timeout` or `Thread#value`
176
+ rescue. (Probe `probe_thread_death.rb` / `probe8.log`: the process had to
177
+ be killed.) The "thread can be restarted if it dies" claim below only
178
+ helps a *future* call; the in-flight one hangs.
179
+ - **`run_threaded` is mutually exclusive with the main-thread modes** in
180
+ practice. PyCall/libpython in this setup only tolerates PyCall calls from
181
+ the thread that ran `PyCall.init`. Mixing the two thread populations
182
+ segfaults the process (exit 139, `pycall.rb:82 in import_module`), in
183
+ either direction:
184
+ - `run`/`run_simple` (which call `PyCall.init` in the calling thread)
185
+ followed by `run_threaded` (worker thread touches PyCall) → segfault
186
+ (probe `probe_mixed_modes.rb` / `probeX_out.txt`).
187
+ - `run_threaded` first (worker thread runs `PyCall.init`) then `run` from
188
+ the main thread → segfault (probe `probe_thread_owner.rb` /
189
+ `probeO_out.txt`).
190
+ - Even a second Ruby thread calling plain `run`/`run` blocks segfaults
191
+ (probe `probe_thread_owner3.rb` / `probeQ_out.txt`), while pure
192
+ `run_threaded` calls from several Ruby threads work fine
193
+ (probe `probe_thread_owner4.rb`).
194
+
195
+ The practical rule: pick one population per process — either stay with
196
+ the main-thread modes (`run`, `run_simple`, `run_direct`, `run_log`) and
197
+ leave `run_threaded` unused, or use `run_threaded` exclusively and never
198
+ call `PyCall` from any other thread.
199
+
200
+ ### run_log
201
+
202
+ ```ruby
203
+ def self.run_log(mod = nil, *args, as: mod, import: nil, &block)
204
+ Log.trap_stderr do
205
+ Log.trap_std do
206
+ run(mod, *args, as: as, import: import, &block)
207
+ end
208
+ end
209
+ end
210
+ ```
211
+
212
+ Wraps `run` with Scout's log trapping, capturing Python stdout/stderr into
213
+ the Scout logging system.
214
+
215
+ ## Initialization and shutdown
216
+
217
+ ### init_scout
218
+
219
+ Guarded by `@@__init_scout_python` class variable to ensure one-time
220
+ initialization:
221
+
222
+ ```ruby
223
+ @@__init_scout_python = nil
224
+
225
+ def self.init_scout
226
+ return if @@__init_scout_python
227
+
228
+ PyCall.init
229
+ process_paths
230
+ pyimport "scout"
231
+
232
+ @@__init_scout_python = true
233
+
234
+ at_exit do
235
+ Thread.list.each do |thread|
236
+ next if thread == Thread.main
237
+ thread.kill
238
+ thread.join rescue nil
239
+ end
240
+ GC.start
241
+ PyCall.builtins.object # GIL health check
242
+ end
243
+ end
244
+ ```
245
+
246
+ The guard is real, but the semantics of a *warm* second call are worth
247
+ knowing (probes `probe_direct_first.rb` / `probeT_out.txt`,
248
+ `probe_init_guard.rb`):
249
+
250
+ - `init_scout` is idempotent at the Scout layer: once the class variable is
251
+ set, nothing re-runs — no second `PyCall.init`, no second `at_exit`
252
+ registration, no re-import of the `scout` Python module.
253
+ - `PyCall.init` is guarded at its own layer too
254
+ (`return false if LibPython.instance_variable_defined?(:@handle)`), so a
255
+ second call from the same thread is a no-op, not an error.
256
+ - `ScoutPython.run_direct` is *not* behind the guard, but the documented
257
+ "`run_direct` before PyCall is initialized will crash" warning is not
258
+ reproducible from a plain `require 'scout/python'`: the `require` itself
259
+ runs `add_paths` → `process_paths` → `pyimport :sys` at load time, which
260
+ triggers `PyCall.init` via `const_missing` as a side effect. A
261
+ `run_direct`-first process therefore initializes Python implicitly and
262
+ works. Treat the warning as a statement about the mode's contract (no
263
+ initialization checking), not an observable failure at HEAD.
264
+ - `init_scout` only puts the `scout` Python module on the `ScoutPython`
265
+ module namespace; imports made inside blocks (`json`, `numpy`, ...) do
266
+ not leak into it.
267
+
268
+ ### at_exit hook
269
+
270
+ The shutdown sequence is critical:
271
+
272
+ 1. **Kill all non-main threads** — Including the ScoutPython background thread.
273
+ 2. **GC.start** — Finalize Python objects while the GIL is still available.
274
+ 3. **Touch PyCall.builtins.object** — Verify GIL is still healthy.
275
+
276
+ If GC happens after the GIL is gone, PyCall object finalizers will segfault.
277
+
278
+ **Known issue:** The at_exit hook kills ALL non-main threads, not just the
279
+ ScoutPython thread. This could interfere with other threading code in the
280
+ process. See [Improvements](../Improvements.md).
281
+
282
+ Empirically (probes `probe_exit_matrix.rb`, `probe_stop_thread.rb`,
283
+ `probe_stop2.rb`, `probe_atexit_worker.rb`) the hook does **not** currently
284
+ deliver a clean exit for the threaded path, and the "always call
285
+ `stop_thread`" advice does not rescue it:
286
+
287
+ - Leaving the worker thread alive and letting the hook run does not exit:
288
+ the process hangs until killed externally (exit 137 after
289
+ `timeout -s KILL`).
290
+ - `stop_thread` itself stalls inside `MUTEX.synchronize`; when its steps are
291
+ driven manually (`QUEUE_IN.push :stop`, `join(2)`), the thread does die,
292
+ but the next PyCall call from the main thread segfaults (exit 139 at
293
+ `pycall.rb:82`). That is the mixed-thread case described under
294
+ `run_threaded`: once the worker owned `PyCall.init`, the main thread may
295
+ not touch PyCall again.
296
+ - A `GC.start` before exit, with or without `stop_thread`, changes nothing.
297
+
298
+ Only the main-thread modes (`run`, `run_simple`, `run_direct`) used alone
299
+ exit cleanly. Verified B2 detail: the hook iterates
300
+ `Thread.list - [Thread.current]`; at exit time `Thread.current` *is* the
301
+ main thread, so "non-main" is accurate — every other thread in the process,
302
+ including threads that have nothing to do with ScoutPython, is killed. A
303
+ user `at_exit` registered *after* `init_scout` runs *before* scout's hook
304
+ (Ruby runs at_exit blocks in reverse registration order), so user shutdown
305
+ logic can still complete first.
306
+
307
+ ## Path management
308
+
309
+ `ScoutPython.paths` is an array of directories to add to Python's `sys.path`.
310
+
311
+ - `add_path(path)` — Append a path.
312
+ - `process_paths` — For each registered path, call `sys.path.append(path)`.
313
+
314
+ At load time, all Python directories registered via the Scout Path subsystem
315
+ are added: `ScoutPython.add_paths(Scout.python.find_all)`.
316
+
317
+ **Verified (probes `probe_pathdup2.rb` / `probeL_out.txt`):** `process_paths`
318
+ is called multiple times (in `init_scout`, `run_simple`, and
319
+ `init_thread`) and does not deduplicate. Every main-thread `run` call
320
+ appends the Scout directory again — `sys.path` grew 8 → 9 → 10 over three
321
+ `run` calls, all duplicates being the Scout python directory. The threaded
322
+ path is stable instead: `init_thread` re-runs `process_paths` only when it
323
+ (re)creates the thread, and the worker's loop calls `run_simple`-free code,
324
+ so `sys.path` stayed at 8 across three `run_threaded` calls. Duplicates are
325
+ harmless for imports but worth knowing when you inspect `sys.path`.
326
+
327
+ Scope (probe `probe_libpython.rb` / `probeJ_out.txt`): paths.rb manages
328
+ `sys.path` **only**. It never touches `LD_LIBRARY_PATH`, `PYTHONHOME`,
329
+ `PYTHONPATH` or any other loader/library configuration, and it never loads
330
+ native libraries — `libpython` and every native extension are `dlopen`ed by
331
+ PyCall and the dynamic loader, not by ScoutPython. `ScoutPython.paths` is
332
+ seeded at require time from `Scout.python.find_all` (here: the repository's
333
+ own `python/` directory) and can be extended with `ScoutPython.add_path`.
334
+
335
+ After `init_scout`, `sys.path` contains the Scout directory appended after
336
+ the standard Python paths. Note also that PyCall itself appends its own
337
+ helper directory (`.../pycall/python`) to `sys.path` during `PyCall.init`.
338
+
339
+ ## Binding scopes
340
+
341
+ ```ruby
342
+ class Binding
343
+ include PyCall::Import
344
+ end
345
+ ```
346
+
347
+ Each `Binding` instance gets its own import namespace via
348
+ `PyCall::Import`. This allows isolated imports:
349
+
350
+ ```ruby
351
+ ScoutPython.binding_run do
352
+ pyimport :torch # only available in this block
353
+ end
354
+ ```
355
+
356
+ **Known issue:** `binding_run` always creates a new binding, ignoring its
357
+ `binding` parameter:
358
+
359
+ ```ruby
360
+ def self.binding_run(binding = nil, *args, &block)
361
+ binding = new_binding # parameter overwritten!
362
+ binding.instance_exec(*args, &block)
363
+ end
364
+ ```
365
+
366
+ Verified (probe `probe_misc.rb`): `binding_run("not-a-binding") { ... }`
367
+ runs happily and returns the block's result, confirming the parameter is
368
+ completely ignored — any object is accepted and discarded. This is B3 in
369
+ [Improvements](../Improvements.md), still true at HEAD.
370
+
371
+ The building block still works as intended: `ScoutPython.new_binding`
372
+ returns a `Binding` instance whose imports **persist across** separate
373
+ `instance_exec` calls on that same instance, so callers who want to reuse a
374
+ scope can do it manually:
375
+
376
+ ```ruby
377
+ b = ScoutPython.new_binding
378
+ b.instance_exec { pyimport :math }
379
+ b.instance_exec { math.sqrt(16) } # => 4.0 — math is still there
380
+ ```
381
+
382
+ ## Import helpers
383
+
384
+ | Method | What it does |
385
+ |--------|-------------|
386
+ | `import_method(mod, method, as=nil)` | `pyimport mod; pyfrom mod, import: method` → Ruby Method |
387
+ | `call_method(mod, method, *args)` | Import + call in one step |
388
+ | `get_module(mod)` | `pyimport mod` (aliased with underscores for dotted names) |
389
+ | `get_class(mod, cls)` | Import module, return `module.cls` |
390
+ | `class_new_obj(mod, cls, args={})` | Import class + instantiate with kwargs |
391
+ | `exec(script)` | `PyCall.exec(script)` |
392
+
393
+ The `get_module` helper aliases dotted module names with underscores:
394
+ `torch.nn` becomes accessible as `ScoutPython.torch_nn`. This avoids method
395
+ name conflicts.
396
+
397
+ Verified side effect (probe `probe_init_guard.rb`): because these helpers
398
+ use `pyimport`/`pyfrom` on the `ScoutPython` module itself, imported names
399
+ persist as constants there. `import_method(:math, :sqrt)` leaves `sqrt`
400
+ accessible as `ScoutPython.sqrt` afterwards — the "imports leak into the
401
+ module namespace" behaviour described for `run` blocks applies to the
402
+ helpers too. Use `Binding` scopes (see above) when that matters.
403
+
404
+ ## Iteration
405
+
406
+ Three methods traverse Python iterables:
407
+
408
+ 1. **`iterate(obj)`** — Tries `__iter__`/`__next__` protocol first. If the
409
+ object is not iterable, falls back to `iterate_index`. Detects
410
+ `StopIteration` by matching the exception type string.
411
+ 2. **`iterate_index(obj)`** — Uses `PyCall.len(obj)` and `obj[i]`.
412
+ 3. **`collect(obj)`** — Gathers all elements into a Ruby array.
413
+
414
+ **StopIteration detection:** Uses `$!.type.to_s == "<class 'StopIteration'>"`.
415
+ This string comparison is fragile but necessary because PyCall wraps Python
416
+ exceptions in `PyCall::PyError`.
417
+
418
+ Verified (probe `probe_iterate_err.rb`): a short iterator ends cleanly with
419
+ `StopIteration` swallowed inside `iterate` (the block sees only the yielded
420
+ elements), while any *other* Python exception propagates to Ruby as a
421
+ `PyCall::PyError`. So the string match only special-cases the one
422
+ end-of-iteration exception.
423
+
424
+ ## Threading model summary
425
+
426
+ ```
427
+ Main thread Background thread
428
+ ───────────── ──────────────────
429
+ run_threaded { ... }
430
+ │
431
+ ├─ init_thread()──────────►Thread.new {
432
+ │ init_scout()
433
+ │ process_paths()
434
+ ├─ QUEUE_IN.push(block) loop {
435
+ │ item = QUEUE_IN.pop
436
+ │ blocks ← break if item == :stop
437
+ │ run_simple { block }
438
+ │ }
439
+ ├─ QUEUE_OUT.pop ─────────►result
440
+ │ }
441
+ ▼
442
+ result
443
+ ```
444
+
445
+ - All access is serialized through MUTEX. `MUTEX` serializes
446
+ *dispatch*, not execution population: `run`/`run_simple` hold it while
447
+ they run PyCall calls on the calling thread, `run_in_thread` holds it
448
+ while pushing to `QUEUE_IN` and waiting on `QUEUE_OUT`. Because PyCall
449
+ effectively belongs to the thread that ran `PyCall.init` (see
450
+ `run_threaded`), the mutex cannot make the two populations
451
+ interchangeable — it only prevents two Ruby threads from dispatching at
452
+ the same instant.
453
+ - The thread can be restarted if it dies (`init_thread` checks
454
+ `!self.thread.alive?` and logs "Reloading ScoutPython thread"). Note that
455
+ restarting happens **outside** `MUTEX.synchronize` in `init_thread`, and
456
+ empirically the reload path did not survive testing: after killing the
457
+ worker and issuing a second `run_threaded`, the process segfaulted
458
+ (probes `probe_thread_reload.rb` / `probe7_out.txt`). Treat "the thread
459
+ can be restarted" as the intent of the code, not as verified behaviour —
460
+ a dead worker thread realistically means a dead process.
461
+ - `stop_thread` sends `:stop`, joins (2s timeout), or kills, then GCs.
462
+ Empirically `stop_thread` stalls inside `MUTEX.synchronize` when called
463
+ from the main thread after threaded use (see the at_exit section), so it
464
+ is not currently a reliable shutdown primitive.
465
+
466
+ ## Key design decisions
467
+
468
+ 1. **Layered execution modes** — Each mode adds exactly one concern. This
469
+ makes the code easy to reason about and test.
470
+
471
+ 2. **MUTEX for all in-process access** — Ensures thread safety for PyCall
472
+ operations that require the GIL.
473
+
474
+ 3. **Dedicated thread for isolated execution** — `run_threaded` provides a
475
+ clean Python environment that doesn't pollute the main module namespace.
476
+
477
+ 4. **at_exit for safe shutdown** — Critical for avoiding segfaults. GC must
478
+ happen before GIL loss. (Empirically the hook does not yet achieve a
479
+ clean exit for the threaded path; see the at_exit section above.)
480
+
481
+ 5. **Subprocess for complex work** — `script()`, `run_file` and
482
+ `python_task` spawn new `python` processes (via
483
+ `env PYTHONPATH=<ScoutPython.paths> python ...`), avoiding GIL
484
+ contention, thread-population hazards and native-library sharing with
485
+ the Ruby process entirely.
486
+
487
+ ## Probes referenced here
488
+
489
+ The behaviour claims above were established with throwaway probes under
490
+ `tmp/` in the working tree (not committed):
491
+ `probe_direct_first.rb`, `probe_init_guard.rb`, `probe_libpython.rb`,
492
+ `probe_env_embed.rb`, `probe_concurrency.rb`, `probe_thread_death.rb`,
493
+ `probe_thread_owner.rb`, `probe_thread_owner3.rb`,
494
+ `probe_thread_owner4.rb`, `probe_thread_reload.rb`,
495
+ `probe_mixed_modes.rb`, `probe_stop_thread.rb`, `probe_stop2.rb`,
496
+ `probe_exit_matrix.rb`, `probe_atexit_worker.rb`, `probe_misc.rb`,
497
+ `probe_iterate_err.rb`. Findings are recorded durably in the Cortex
498
+ artifact `scout-rig/subsys/python-bridge.md`.
499
+
500
+ ## See also
501
+
502
+ - [Architecture](Architecture.md) — Overall module map.
503
+ - [Data Conversion Internals](DataConversionInternals.md) — How script() and converters work.
504
+ - [Running Python from Ruby](../user/RunningPythonFromRuby.md) — User-facing guide.