mo-trace 0.1.0__tar.gz → 0.2.0__tar.gz
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.
- {mo_trace-0.1.0 → mo_trace-0.2.0}/PKG-INFO +26 -26
- {mo_trace-0.1.0 → mo_trace-0.2.0}/README.md +25 -25
- {mo_trace-0.1.0/matrace → mo_trace-0.2.0/motrace}/cli.py +21 -21
- {mo_trace-0.1.0/matrace → mo_trace-0.2.0/motrace}/convert.py +10 -10
- {mo_trace-0.1.0/matrace → mo_trace-0.2.0/motrace}/core.py +7 -7
- {mo_trace-0.1.0 → mo_trace-0.2.0}/pyproject.toml +8 -8
- {mo_trace-0.1.0 → mo_trace-0.2.0}/tests/conftest.py +4 -4
- {mo_trace-0.1.0 → mo_trace-0.2.0}/tests/test_convert.py +9 -9
- mo_trace-0.1.0/tests/test_matrace.py → mo_trace-0.2.0/tests/test_motrace.py +27 -27
- {mo_trace-0.1.0 → mo_trace-0.2.0}/.gitignore +0 -0
- {mo_trace-0.1.0/matrace → mo_trace-0.2.0/motrace}/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mo-trace
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: nbdev-style literate programming for marimo notebooks
|
|
5
5
|
License-Expression: Apache-2.0
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -11,30 +11,30 @@ Requires-Dist: tinker>=0.39; extra == 'tinker'
|
|
|
11
11
|
Requires-Dist: tml-renderers>=0.4; extra == 'tinker'
|
|
12
12
|
Description-Content-Type: text/markdown
|
|
13
13
|
|
|
14
|
-
#
|
|
14
|
+
# motrace
|
|
15
15
|
|
|
16
16
|
A minimal [nbdev](https://nbdev.fast.ai) for [marimo](https://marimo.io) notebooks. Write the code, its docs and its tests
|
|
17
|
-
in a marimo notebook.
|
|
17
|
+
in a marimo notebook. motrace turns the exported cells into a normal Python package and keeps the two in sync.
|
|
18
18
|
|
|
19
|
-
|
|
|
19
|
+
| motrace | nbdev equivalent | does |
|
|
20
20
|
|---|---|---|
|
|
21
|
-
| `
|
|
22
|
-
| `
|
|
23
|
-
| `
|
|
24
|
-
| `
|
|
21
|
+
| `motrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
|
|
22
|
+
| `motrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
|
|
23
|
+
| `motrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
|
|
24
|
+
| `motrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
|
|
25
25
|
|
|
26
|
-
Run `
|
|
26
|
+
Run `motrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
|
|
27
27
|
|
|
28
28
|
## Install
|
|
29
29
|
|
|
30
30
|
```sh
|
|
31
|
-
pip install mo-trace # or: uv add --dev mo-trace (imported as `
|
|
31
|
+
pip install mo-trace # or: uv add --dev mo-trace (imported as `motrace`)
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
Add a `[tool.
|
|
34
|
+
Add a `[tool.motrace]` table to your project's `pyproject.toml`:
|
|
35
35
|
|
|
36
36
|
```toml
|
|
37
|
-
[tool.
|
|
37
|
+
[tool.motrace]
|
|
38
38
|
lib_path = "mypkg" # default: [project].name, with - replaced by _
|
|
39
39
|
nbs_path = "jobs" # default: jobs
|
|
40
40
|
```
|
|
@@ -67,13 +67,13 @@ def _(cosine):
|
|
|
67
67
|
|
|
68
68
|
@app.cell
|
|
69
69
|
def _():
|
|
70
|
-
#| eval: false # skipped by
|
|
70
|
+
#| eval: false # skipped by motrace-prepare
|
|
71
71
|
slow_benchmark()
|
|
72
72
|
return
|
|
73
73
|
```
|
|
74
74
|
|
|
75
75
|
Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
|
|
76
|
-
`eval: false`.
|
|
76
|
+
`eval: false`. motrace also follows nbdev for these details:
|
|
77
77
|
- `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
|
|
78
78
|
- `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
|
|
79
79
|
- The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
|
|
@@ -82,20 +82,20 @@ Supported directives: `default_exp`, `export [module]`, `exporti [module]` (expo
|
|
|
82
82
|
## Differences from nbdev (by design or necessity)
|
|
83
83
|
|
|
84
84
|
- **Imports across modules are generated for you.** Marimo forbids defining a name in more than one cell, so a cell exported
|
|
85
|
-
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would.
|
|
85
|
+
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would. motrace reads marimo's dataflow graph
|
|
86
86
|
instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
|
|
87
87
|
from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
|
|
88
88
|
- **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
|
|
89
89
|
- **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
|
|
90
90
|
cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
|
|
91
|
-
`
|
|
91
|
+
`motrace-export` again after reordering cells.
|
|
92
92
|
- **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
|
|
93
93
|
`IN_TEST=1` set. Cells execute in marimo's dependency order.
|
|
94
|
-
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `
|
|
94
|
+
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `motrace-clean` rewrites each notebook
|
|
95
95
|
in marimo's own canonical format and strips trailing whitespace. It keeps `__generated_with` unchanged, so upgrading marimo
|
|
96
|
-
doesn't change every notebook. `
|
|
97
|
-
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `
|
|
98
|
-
- **Private marimo APIs.**
|
|
96
|
+
doesn't change every notebook. `motrace-clean --stdin` works as a git filter.
|
|
97
|
+
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `motrace-prepare` is export + test + clean.
|
|
98
|
+
- **Private marimo APIs.** motrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
|
|
99
99
|
|
|
100
100
|
## Example: a tiny language model from one notebook
|
|
101
101
|
|
|
@@ -105,24 +105,24 @@ Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`
|
|
|
105
105
|
|
|
106
106
|
```sh
|
|
107
107
|
cd examples/tinylm
|
|
108
|
-
|
|
108
|
+
motrace-prepare # export, test, clean -> Success.
|
|
109
109
|
pip install . # or: pip install -e .
|
|
110
110
|
tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
|
|
111
111
|
marimo edit jobs/tinylm.py # keep developing in the notebook
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
-
## Training data: notebook → Pi rollout → Tinker (`
|
|
114
|
+
## Training data: notebook → Pi rollout → Tinker (`motrace-convert`)
|
|
115
115
|
|
|
116
116
|
```sh
|
|
117
117
|
pip install "mo-trace[tinker]"
|
|
118
|
-
|
|
118
|
+
motrace-convert examples/tinylm/jobs/tinylm.py -o traces
|
|
119
119
|
python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
|
|
120
120
|
```
|
|
121
121
|
|
|
122
|
-
`
|
|
122
|
+
`motrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
|
|
123
123
|
building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
|
|
124
124
|
strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
|
|
125
|
-
marimo dependency order. It runs `
|
|
125
|
+
marimo dependency order. It runs `motrace-prepare` after every step and finally checks that the package imports. Every tool
|
|
126
126
|
call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
|
|
127
127
|
rejected. The output files are:
|
|
128
128
|
|
|
@@ -133,7 +133,7 @@ rejected. The output files are:
|
|
|
133
133
|
| `sft.jsonl` | a Tinker `Datum` (`model_input`, `target_tokens`, 0/1 `weights`) of the whole trajectory, rendered with Inkling 2 Small's renderer. Only assistant tokens carry loss: reasoning, text, tool calls and end-of-turn |
|
|
134
134
|
| `opd_prompts.jsonl` | one starting state per assistant turn for on-policy distillation. Each has `prompt_tokens` (a token prefix of the trajectory), `teacher_prompt_tokens`, the reference turn, and the workspace files at that point |
|
|
135
135
|
|
|
136
|
-
Load the data with `
|
|
136
|
+
Load the data with `motrace.convert.load_sft()`. `motrace.convert.opd_datum()` builds the `importance_sampling` datum,
|
|
137
137
|
with advantage = teacher logprob − student logprob for each sampled token.
|
|
138
138
|
|
|
139
139
|
Notes:
|
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# motrace
|
|
2
2
|
|
|
3
3
|
A minimal [nbdev](https://nbdev.fast.ai) for [marimo](https://marimo.io) notebooks. Write the code, its docs and its tests
|
|
4
|
-
in a marimo notebook.
|
|
4
|
+
in a marimo notebook. motrace turns the exported cells into a normal Python package and keeps the two in sync.
|
|
5
5
|
|
|
6
|
-
|
|
|
6
|
+
| motrace | nbdev equivalent | does |
|
|
7
7
|
|---|---|---|
|
|
8
|
-
| `
|
|
9
|
-
| `
|
|
10
|
-
| `
|
|
11
|
-
| `
|
|
8
|
+
| `motrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
|
|
9
|
+
| `motrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
|
|
10
|
+
| `motrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
|
|
11
|
+
| `motrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
|
|
12
12
|
|
|
13
|
-
Run `
|
|
13
|
+
Run `motrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
17
17
|
```sh
|
|
18
|
-
pip install mo-trace # or: uv add --dev mo-trace (imported as `
|
|
18
|
+
pip install mo-trace # or: uv add --dev mo-trace (imported as `motrace`)
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
Add a `[tool.
|
|
21
|
+
Add a `[tool.motrace]` table to your project's `pyproject.toml`:
|
|
22
22
|
|
|
23
23
|
```toml
|
|
24
|
-
[tool.
|
|
24
|
+
[tool.motrace]
|
|
25
25
|
lib_path = "mypkg" # default: [project].name, with - replaced by _
|
|
26
26
|
nbs_path = "jobs" # default: jobs
|
|
27
27
|
```
|
|
@@ -54,13 +54,13 @@ def _(cosine):
|
|
|
54
54
|
|
|
55
55
|
@app.cell
|
|
56
56
|
def _():
|
|
57
|
-
#| eval: false # skipped by
|
|
57
|
+
#| eval: false # skipped by motrace-prepare
|
|
58
58
|
slow_benchmark()
|
|
59
59
|
return
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
|
|
63
|
-
`eval: false`.
|
|
63
|
+
`eval: false`. motrace also follows nbdev for these details:
|
|
64
64
|
- `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
|
|
65
65
|
- `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
|
|
66
66
|
- The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
|
|
@@ -69,20 +69,20 @@ Supported directives: `default_exp`, `export [module]`, `exporti [module]` (expo
|
|
|
69
69
|
## Differences from nbdev (by design or necessity)
|
|
70
70
|
|
|
71
71
|
- **Imports across modules are generated for you.** Marimo forbids defining a name in more than one cell, so a cell exported
|
|
72
|
-
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would.
|
|
72
|
+
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would. motrace reads marimo's dataflow graph
|
|
73
73
|
instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
|
|
74
74
|
from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
|
|
75
75
|
- **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
|
|
76
76
|
- **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
|
|
77
77
|
cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
|
|
78
|
-
`
|
|
78
|
+
`motrace-export` again after reordering cells.
|
|
79
79
|
- **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
|
|
80
80
|
`IN_TEST=1` set. Cells execute in marimo's dependency order.
|
|
81
|
-
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `
|
|
81
|
+
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `motrace-clean` rewrites each notebook
|
|
82
82
|
in marimo's own canonical format and strips trailing whitespace. It keeps `__generated_with` unchanged, so upgrading marimo
|
|
83
|
-
doesn't change every notebook. `
|
|
84
|
-
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `
|
|
85
|
-
- **Private marimo APIs.**
|
|
83
|
+
doesn't change every notebook. `motrace-clean --stdin` works as a git filter.
|
|
84
|
+
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `motrace-prepare` is export + test + clean.
|
|
85
|
+
- **Private marimo APIs.** motrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
|
|
86
86
|
|
|
87
87
|
## Example: a tiny language model from one notebook
|
|
88
88
|
|
|
@@ -92,24 +92,24 @@ Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`
|
|
|
92
92
|
|
|
93
93
|
```sh
|
|
94
94
|
cd examples/tinylm
|
|
95
|
-
|
|
95
|
+
motrace-prepare # export, test, clean -> Success.
|
|
96
96
|
pip install . # or: pip install -e .
|
|
97
97
|
tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
|
|
98
98
|
marimo edit jobs/tinylm.py # keep developing in the notebook
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
## Training data: notebook → Pi rollout → Tinker (`
|
|
101
|
+
## Training data: notebook → Pi rollout → Tinker (`motrace-convert`)
|
|
102
102
|
|
|
103
103
|
```sh
|
|
104
104
|
pip install "mo-trace[tinker]"
|
|
105
|
-
|
|
105
|
+
motrace-convert examples/tinylm/jobs/tinylm.py -o traces
|
|
106
106
|
python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
|
|
107
107
|
```
|
|
108
108
|
|
|
109
|
-
`
|
|
109
|
+
`motrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
|
|
110
110
|
building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
|
|
111
111
|
strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
|
|
112
|
-
marimo dependency order. It runs `
|
|
112
|
+
marimo dependency order. It runs `motrace-prepare` after every step and finally checks that the package imports. Every tool
|
|
113
113
|
call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
|
|
114
114
|
rejected. The output files are:
|
|
115
115
|
|
|
@@ -120,7 +120,7 @@ rejected. The output files are:
|
|
|
120
120
|
| `sft.jsonl` | a Tinker `Datum` (`model_input`, `target_tokens`, 0/1 `weights`) of the whole trajectory, rendered with Inkling 2 Small's renderer. Only assistant tokens carry loss: reasoning, text, tool calls and end-of-turn |
|
|
121
121
|
| `opd_prompts.jsonl` | one starting state per assistant turn for on-policy distillation. Each has `prompt_tokens` (a token prefix of the trajectory), `teacher_prompt_tokens`, the reference turn, and the workspace files at that point |
|
|
122
122
|
|
|
123
|
-
Load the data with `
|
|
123
|
+
Load the data with `motrace.convert.load_sft()`. `motrace.convert.opd_datum()` builds the `importance_sampling` datum,
|
|
124
124
|
with advantage = teacher logprob − student logprob for each sampled token.
|
|
125
125
|
|
|
126
126
|
Notes:
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"""Command line entry points:
|
|
1
|
+
"""Command line entry points: motrace (the guide), motrace-export, motrace-prepare, motrace-clean."""
|
|
2
2
|
|
|
3
3
|
import argparse, sys
|
|
4
4
|
from . import __version__
|
|
5
5
|
from .core import nb_clean, nb_export, nb_test, nb_update, clean_text
|
|
6
6
|
|
|
7
7
|
GUIDE = '''
|
|
8
|
-
|
|
9
|
-
notebook;
|
|
8
|
+
motrace is nbdev for marimo notebooks: write code, docs and tests in a marimo
|
|
9
|
+
notebook; motrace turns chosen cells into a regular Python package and keeps
|
|
10
10
|
the two in sync.
|
|
11
11
|
|
|
12
12
|
SETUP
|
|
13
13
|
Add to your project's pyproject.toml:
|
|
14
14
|
|
|
15
|
-
[tool.
|
|
15
|
+
[tool.motrace]
|
|
16
16
|
lib_path = "mypkg" # package to generate (default: [project].name)
|
|
17
17
|
nbs_path = "jobs" # where notebooks live (default: jobs)
|
|
18
18
|
|
|
@@ -47,19 +47,19 @@ IN A MARIMO NOTEBOOK
|
|
|
47
47
|
|
|
48
48
|
Import your own package absolutely (`from mypkg.core import norm`) only
|
|
49
49
|
from *other* notebooks; within one notebook just use the name, since marimo
|
|
50
|
-
forbids defining a name twice.
|
|
50
|
+
forbids defining a name twice. motrace adds the imports a module needs
|
|
51
51
|
(setup-cell imports, names exported to sibling modules) automatically.
|
|
52
52
|
Underscore names (`_tmp`) are cell-local in marimo: use them in tests.
|
|
53
53
|
|
|
54
54
|
IN THE CLI
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
motrace-export notebooks -> mypkg/*.py
|
|
56
|
+
motrace-export --update edits made in mypkg/*.py -> back into notebooks
|
|
57
|
+
motrace-prepare export, run all notebooks' tests in parallel
|
|
58
58
|
(one process each, cwd = notebook dir), clean;
|
|
59
59
|
exits 1 and names any failing notebook
|
|
60
|
-
|
|
60
|
+
motrace-clean normalize notebooks (marimo's canonical format,
|
|
61
61
|
no trailing whitespace) to keep diffs small
|
|
62
|
-
|
|
62
|
+
motrace-convert NB -o DIR replay a notebook as a Pi coding-agent rollout
|
|
63
63
|
and write it as Tinker training data (SFT and
|
|
64
64
|
on-policy distillation) for Inkling 2 Small;
|
|
65
65
|
needs `pip install "mo-trace[tinker]"`
|
|
@@ -67,9 +67,9 @@ IN THE CLI
|
|
|
67
67
|
|
|
68
68
|
Typical loop:
|
|
69
69
|
marimo edit jobs/00_core.py write code + tests
|
|
70
|
-
|
|
70
|
+
motrace-prepare before committing
|
|
71
71
|
# edited mypkg/core.py directly (IDE, refactor tool)? then:
|
|
72
|
-
|
|
72
|
+
motrace-export --update && motrace-prepare
|
|
73
73
|
|
|
74
74
|
Generated modules start with `# AUTOGENERATED! DO NOT EDIT!` and carry
|
|
75
75
|
`# %% ../jobs/00_core.py #3` markers mapping each block to its cell. Only
|
|
@@ -90,19 +90,19 @@ ORGANIZING NOTEBOOKS
|
|
|
90
90
|
- Several notebooks may export into the same module; it is rebuilt whole.
|
|
91
91
|
- Keep notebooks fast: they are your test suite. Mark slow or interactive
|
|
92
92
|
cells `#| eval: false`.
|
|
93
|
-
- After reordering exported cells, run
|
|
94
|
-
(cells are matched by position;
|
|
93
|
+
- After reordering exported cells, run motrace-export before --update
|
|
94
|
+
(cells are matched by position; motrace refuses mismatched updates).
|
|
95
95
|
'''
|
|
96
96
|
|
|
97
97
|
def main_cli(argv=None):
|
|
98
|
-
p = argparse.ArgumentParser('
|
|
98
|
+
p = argparse.ArgumentParser('motrace', description=f'motrace {__version__}: nbdev-style literate programming for '
|
|
99
99
|
'marimo notebooks', epilog=GUIDE, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
100
100
|
p.add_argument('--version', action='version', version=__version__)
|
|
101
101
|
p.parse_args(argv)
|
|
102
102
|
p.print_help()
|
|
103
103
|
|
|
104
104
|
def export_cli(argv=None):
|
|
105
|
-
p = argparse.ArgumentParser('
|
|
105
|
+
p = argparse.ArgumentParser('motrace-export', description='Export marimo notebooks to Python modules '
|
|
106
106
|
'(like nbdev-export), or with --update sync module edits back (like nbdev-update)')
|
|
107
107
|
p.add_argument('path', nargs='?', help='notebook or directory to export (default: nbs_path); '
|
|
108
108
|
'with --update, a module or directory (default: lib_path)')
|
|
@@ -111,7 +111,7 @@ def export_cli(argv=None):
|
|
|
111
111
|
for f in (nb_update if a.update else nb_export)(a.path): print(f'{"updated" if a.update else "exported"} {f}')
|
|
112
112
|
|
|
113
113
|
def clean_cli(argv=None):
|
|
114
|
-
p = argparse.ArgumentParser('
|
|
114
|
+
p = argparse.ArgumentParser('motrace-clean', description='Normalize marimo notebooks to avoid merge conflicts')
|
|
115
115
|
p.add_argument('fname', nargs='?', help='notebook or directory to clean (default: nbs_path)')
|
|
116
116
|
p.add_argument('--stdin', action='store_true', help='clean a notebook read from stdin to stdout (git filter)')
|
|
117
117
|
a = p.parse_args(argv)
|
|
@@ -119,10 +119,10 @@ def clean_cli(argv=None):
|
|
|
119
119
|
for f in nb_clean(a.fname): print(f'cleaned {f}')
|
|
120
120
|
|
|
121
121
|
def convert_cli(argv=None):
|
|
122
|
-
p = argparse.ArgumentParser('
|
|
122
|
+
p = argparse.ArgumentParser('motrace-convert', description='Replay a marimo notebook as a Pi coding-agent rollout '
|
|
123
123
|
'(real tool executions) and write it as Tinker training data for Inkling 2 Small: '
|
|
124
124
|
'pi_session.jsonl, messages.json, sft.jsonl, opd_prompts.jsonl')
|
|
125
|
-
p.add_argument('notebook', help='marimo notebook inside a
|
|
125
|
+
p.add_argument('notebook', help='marimo notebook inside a motrace project')
|
|
126
126
|
p.add_argument('-o', '--out', default='traces', help='output directory (default: traces)')
|
|
127
127
|
p.add_argument('--model', default='thinkingmachines/Inkling-2-Small', help='Tinker model whose renderer to use')
|
|
128
128
|
p.add_argument('--effort', type=float, default=0.0, help='Inkling thinking-effort conditioning in [0, 1). Reasoning '
|
|
@@ -133,7 +133,7 @@ def convert_cli(argv=None):
|
|
|
133
133
|
tinker = not a.no_tinker
|
|
134
134
|
if tinker:
|
|
135
135
|
try: import tinker_cookbook # noqa: F401
|
|
136
|
-
except ImportError: sys.exit('
|
|
136
|
+
except ImportError: sys.exit('motrace-convert: Tinker output needs `pip install "mo-trace[tinker]"` (or pass --no-tinker)')
|
|
137
137
|
from .convert import convert
|
|
138
138
|
ro, files = convert(a.notebook, a.out, model=a.model, effort=a.effort, cwd=a.cwd, tinker=tinker)
|
|
139
139
|
n = sum(m['role'] == 'assistant' for m in ro['messages'])
|
|
@@ -141,7 +141,7 @@ def convert_cli(argv=None):
|
|
|
141
141
|
for f in files: print(f'wrote {f}')
|
|
142
142
|
|
|
143
143
|
def prepare_cli(argv=None):
|
|
144
|
-
p = argparse.ArgumentParser('
|
|
144
|
+
p = argparse.ArgumentParser('motrace-prepare', description='Export, test (in parallel) and clean notebooks')
|
|
145
145
|
p.add_argument('--n_workers', type=int, default=None, help='parallel test processes (default: min(cpus, 8))')
|
|
146
146
|
p.add_argument('--timing', action='store_true', help='print how long each notebook took')
|
|
147
147
|
p.add_argument('--timeout', type=float, default=None, help='seconds before a notebook test is killed')
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""motrace-convert: replay a marimo notebook as a Pi coding-agent rollout, then render it as Tinker training data.
|
|
2
2
|
|
|
3
3
|
The rollout is what Pi (https://github.com/earendil-works/pi-mono) would record if an agent built the notebook
|
|
4
4
|
step by step: explore the project, `write` the first cells, `edit` in each further exported cell plus its tests,
|
|
5
|
-
run `
|
|
5
|
+
run `motrace-prepare` after every step, and finally check the generated package. Every tool call is actually
|
|
6
6
|
executed in a scratch copy of the project, so every tool result is real output.
|
|
7
7
|
|
|
8
8
|
Outputs (in `out_dir`):
|
|
@@ -200,15 +200,15 @@ def rollout(nb, cwd=None):
|
|
|
200
200
|
if title:
|
|
201
201
|
summ = next((l[2:].strip() for l in title.splitlines() if l.startswith('> ')), '')
|
|
202
202
|
lines.append(f'{title.splitlines()[0][2:]}' + (f': {summ}' if summ else '') + '\n')
|
|
203
|
-
lines.append(f'Build the `{lib}` package as a marimo notebook at `{nbrel}`, using
|
|
203
|
+
lines.append(f'Build the `{lib}` package as a marimo notebook at `{nbrel}`, using motrace: cells marked '
|
|
204
204
|
f'`#| export <module>` are written to `{lib}/<module>.py`, and every other cell is a test.\n\nThe package should provide:')
|
|
205
205
|
for mod, idxs in mods.items():
|
|
206
206
|
api = ', '.join(f'`{n}`' + (f' ({d.rstrip(".")})' if d else '') for n, d in _api(cells, idxs))
|
|
207
207
|
lines.append(f'- `{lib}/{mod.replace(".", "/")}.py`: {api}')
|
|
208
|
-
lines.append('\nWrite tests as ordinary notebook cells next to the code they check, and finish with `
|
|
208
|
+
lines.append('\nWrite tests as ordinary notebook cells next to the code they check, and finish with `motrace-prepare` passing.')
|
|
209
209
|
task = '\n'.join(lines)
|
|
210
210
|
|
|
211
|
-
tmp = Path(tempfile.mkdtemp(prefix='
|
|
211
|
+
tmp = Path(tempfile.mkdtemp(prefix='motrace_convert_'))
|
|
212
212
|
try:
|
|
213
213
|
for f in cfg.root.iterdir(): # the project as the agent finds it: top-level files only, no notebooks, no package
|
|
214
214
|
if f.is_file() and not f.name.startswith('.'): shutil.copy(f, tmp/f.name)
|
|
@@ -247,15 +247,15 @@ def rollout(nb, cwd=None):
|
|
|
247
247
|
if k == 0 or not (e := _edit_for(text, new)): turn(say, 'write', {'path': nbrel, 'content': new}, think)
|
|
248
248
|
else: turn(say, 'edit', {'path': nbrel, 'edits': [e]}, think)
|
|
249
249
|
text = new
|
|
250
|
-
out, err = turn('', 'bash', {'command': '
|
|
251
|
-
if err: raise RuntimeError(f'step {k} of {nb.name} fails
|
|
250
|
+
out, err = turn('', 'bash', {'command': 'motrace-prepare'})
|
|
251
|
+
if err: raise RuntimeError(f'step {k} of {nb.name} fails motrace-prepare:\n{out}')
|
|
252
252
|
mod_names = list(mods)
|
|
253
253
|
check = f'python -c "import importlib\nfor m in {mod_names!r}: print(m, importlib.import_module(\'{lib}.\' + m).__all__)"'
|
|
254
254
|
out, err = turn('All steps pass. Checking that the generated package imports cleanly.', 'bash', {'command': check})
|
|
255
255
|
if err: raise RuntimeError(f'generated package does not import:\n{out}')
|
|
256
256
|
summary = '\n'.join(f'- `{lib}/{m.replace(".", "/")}.py`: ' + ', '.join(f'`{n}`' for n, _ in _api(cells, idxs))
|
|
257
257
|
for m, idxs in mods.items())
|
|
258
|
-
turn(f'Done. `{nbrel}` builds the `{lib}` package with
|
|
258
|
+
turn(f'Done. `{nbrel}` builds the `{lib}` package with motrace, and `motrace-prepare` passes.\n\n{summary}')
|
|
259
259
|
final = (tmp/nbrel).read_text()
|
|
260
260
|
finally: shutil.rmtree(tmp, ignore_errors=True)
|
|
261
261
|
return {'system': pi_system_prompt(cwd), 'tools': TOOLS, 'messages': msgs, 'snapshots': snaps, 'cwd': cwd,
|
|
@@ -270,13 +270,13 @@ def to_pi_session(ro):
|
|
|
270
270
|
t0 = ro['messages'][0]['timestamp'] - 1000
|
|
271
271
|
lines = [{'type': 'session', 'version': 3, 'id': f'{sid[:8]}-{sid[8:12]}-{sid[12:16]}-{sid[16:20]}-{sid[20:32]}',
|
|
272
272
|
'timestamp': iso(t0), 'cwd': ro['cwd']},
|
|
273
|
-
{'type': 'custom', 'id': sid[:8], 'parentId': None, 'timestamp': iso(t0), 'customType': '
|
|
273
|
+
{'type': 'custom', 'id': sid[:8], 'parentId': None, 'timestamp': iso(t0), 'customType': 'motrace-convert',
|
|
274
274
|
'data': {'source': ro['notebook'], 'sha256': ro['source_sha256'], 'pi_version': PI_VERSION,
|
|
275
275
|
'note': 'synthetic rollout replayed from a marimo notebook; tool results are real executions'}}]
|
|
276
276
|
usage = {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'totalTokens': 0,
|
|
277
277
|
'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'total': 0}}
|
|
278
278
|
for i, m in enumerate(ro['messages']):
|
|
279
|
-
if m['role'] == 'assistant': m = {**m, 'api': 'openai-completions', 'provider': '
|
|
279
|
+
if m['role'] == 'assistant': m = {**m, 'api': 'openai-completions', 'provider': 'motrace', 'model': 'notebook-replay', 'usage': usage}
|
|
280
280
|
eid = hashlib.sha256(f'{sid}{i}'.encode()).hexdigest()[:8]
|
|
281
281
|
lines.append({'type': 'message', 'id': eid, 'parentId': lines[-1]['id'], 'timestamp': iso(m['timestamp']), 'message': m})
|
|
282
282
|
return [json.dumps(l) for l in lines]
|
|
@@ -24,18 +24,18 @@ class Config:
|
|
|
24
24
|
def lib_name(self): return self.lib_path.name
|
|
25
25
|
|
|
26
26
|
def get_config(path=None) -> Config:
|
|
27
|
-
"Read `[tool.
|
|
27
|
+
"Read `[tool.motrace]` from the nearest pyproject.toml at or above `path`"
|
|
28
28
|
d = Path(path or '.').resolve()
|
|
29
29
|
if d.is_file(): d = d.parent
|
|
30
30
|
for p in [d, *d.parents]:
|
|
31
31
|
f = p/'pyproject.toml'
|
|
32
32
|
if not f.exists(): continue
|
|
33
33
|
cfg = tomllib.loads(f.read_text())
|
|
34
|
-
if '
|
|
35
|
-
m = cfg['tool']['
|
|
34
|
+
if 'motrace' not in cfg.get('tool', {}): continue
|
|
35
|
+
m = cfg['tool']['motrace']
|
|
36
36
|
lib = m.get('lib_path') or cfg.get('project', {}).get('name', '').replace('-', '_')
|
|
37
37
|
return Config(p, p/lib, p/m.get('nbs_path', 'jobs'))
|
|
38
|
-
raise SystemExit('
|
|
38
|
+
raise SystemExit('motrace: no pyproject.toml with a [tool.motrace] table found')
|
|
39
39
|
|
|
40
40
|
# ---------------------------------------------------------------- notebooks
|
|
41
41
|
|
|
@@ -274,7 +274,7 @@ def nb_update(path=None):
|
|
|
274
274
|
# Marimo files carry no stable cell ids, so cells are addressed by position: verify it's still the same cell
|
|
275
275
|
if not kind or (view[idx].dirs[kind.pop()] or default) != mod:
|
|
276
276
|
raise ValueError(f'{nb}: cell #{idx} is not an exported cell of `{mod}`; the notebook changed since '
|
|
277
|
-
'the last export. Re-run
|
|
277
|
+
'the last export. Re-run motrace-export, then make your edit again.')
|
|
278
278
|
if code != view[idx].body: ir.cells[idx].code = '\n'.join(view[idx].hdr + [code])
|
|
279
279
|
if write_nb(nb, ir, text) != text: changed.append(nb)
|
|
280
280
|
return changed
|
|
@@ -289,7 +289,7 @@ def test_nb(nb, timeout=None):
|
|
|
289
289
|
tmp = None
|
|
290
290
|
if any(map(_skipped, cells)): # run a copy without the skipped cells; otherwise the notebook itself (exact line numbers)
|
|
291
291
|
src = generate_filecontents_from_ir(replace(ir, cells=[ir.cells[c.idx] for c in cells if not _skipped(c)]))
|
|
292
|
-
with tempfile.NamedTemporaryFile('w', dir=nb.parent, prefix=f'.
|
|
292
|
+
with tempfile.NamedTemporaryFile('w', dir=nb.parent, prefix=f'.motrace_{nb.stem}_', suffix='.py', delete=False) as f:
|
|
293
293
|
f.write(src)
|
|
294
294
|
tmp = f.name
|
|
295
295
|
start = time.time()
|
|
@@ -315,7 +315,7 @@ def nb_test(path=None, n_workers=None, timing=False, timeout=None):
|
|
|
315
315
|
for f, (_, t, _) in sorted(zip(files, results), key=lambda o: -o[1][1]): print(f'{f.name}: {t:.1f} secs')
|
|
316
316
|
if all(ok for ok, _, _ in results): print('Success.'); return True
|
|
317
317
|
failed = '\n\t'.join(f.name for f, (ok, _, _) in zip(files, results) if not ok)
|
|
318
|
-
sys.stderr.write(f"\
|
|
318
|
+
sys.stderr.write(f"\nmotrace Tests Failed On The Following Notebooks:\n{'=' * 50}\n\t{failed}\n")
|
|
319
319
|
return False
|
|
320
320
|
|
|
321
321
|
# ---------------------------------------------------------------- clean
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "mo-trace"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "nbdev-style literate programming for marimo notebooks"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -12,11 +12,11 @@ license = "Apache-2.0"
|
|
|
12
12
|
dependencies = ["marimo>=0.25,<0.26"]
|
|
13
13
|
|
|
14
14
|
[project.scripts]
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
motrace = "motrace.cli:main_cli"
|
|
16
|
+
motrace-export = "motrace.cli:export_cli"
|
|
17
|
+
motrace-prepare = "motrace.cli:prepare_cli"
|
|
18
|
+
motrace-clean = "motrace.cli:clean_cli"
|
|
19
|
+
motrace-convert = "motrace.cli:convert_cli"
|
|
20
20
|
|
|
21
21
|
[project.optional-dependencies]
|
|
22
22
|
tinker = ["tinker>=0.39", "tinker-cookbook>=0.6", "tml-renderers>=0.4"]
|
|
@@ -25,7 +25,7 @@ tinker = ["tinker>=0.39", "tinker-cookbook>=0.6", "tml-renderers>=0.4"]
|
|
|
25
25
|
dev = ["pytest", "nbdev>=3.3", "numpy", "mo-trace[tinker]"]
|
|
26
26
|
|
|
27
27
|
[tool.hatch.build.targets.sdist]
|
|
28
|
-
include = ["
|
|
28
|
+
include = ["motrace", "tests", "README.md"]
|
|
29
29
|
|
|
30
30
|
[tool.hatch.build.targets.wheel]
|
|
31
|
-
packages = ["
|
|
31
|
+
packages = ["motrace"]
|
|
@@ -34,14 +34,14 @@ def mk_ipynb(path, codes):
|
|
|
34
34
|
|
|
35
35
|
@pytest.fixture
|
|
36
36
|
def projects(tmp_path):
|
|
37
|
-
"Twin projects for library `mylib`: (nbdev project dir,
|
|
38
|
-
nbd, mat = tmp_path/'nbdev_proj', tmp_path/'
|
|
39
|
-
for d, tool in ((nbd, 'nbdev'), (mat, '
|
|
37
|
+
"Twin projects for library `mylib`: (nbdev project dir, motrace project dir)"
|
|
38
|
+
nbd, mat = tmp_path/'nbdev_proj', tmp_path/'motrace_proj'
|
|
39
|
+
for d, tool in ((nbd, 'nbdev'), (mat, 'motrace')):
|
|
40
40
|
(d/('nbs' if tool == 'nbdev' else 'jobs')).mkdir(parents=True)
|
|
41
41
|
(d/'pyproject.toml').write_text(f'[project]\nname = "mylib"\nrequires-python = ">=3.11"\n\n[tool.{tool}]\n')
|
|
42
42
|
return nbd, mat
|
|
43
43
|
|
|
44
44
|
def normalize(text):
|
|
45
|
-
"Make nbdev and
|
|
45
|
+
"Make nbdev and motrace module text comparable: notebook suffix, folder and cell ids differ by design"
|
|
46
46
|
text, n = text.replace('.ipynb', '.py').replace('/jobs/', '/nbs/'), iter(range(10**6))
|
|
47
47
|
return re.sub(r'^# %% (?!auto )(\S+) #\S+$', lambda m: f'# %% {m[1]} #{next(n)}', text, flags=re.M)
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""motrace-convert: notebook -> Pi rollout -> Tinker data for Inkling 2 Small."""
|
|
2
2
|
import json
|
|
3
3
|
from pathlib import Path
|
|
4
4
|
|
|
5
5
|
import pytest
|
|
6
6
|
from conftest import mk_marimo, run
|
|
7
|
-
from
|
|
7
|
+
from motrace.convert import _edit_for, load_sft, opd_datum, rollout, to_chat, to_pi_session
|
|
8
8
|
|
|
9
9
|
TINYLM = Path(__file__).parent.parent/'examples/tinylm/jobs/tinylm.py'
|
|
10
10
|
|
|
@@ -20,7 +20,7 @@ def test_rollout_rebuilds_the_notebook(ro):
|
|
|
20
20
|
assert [c['id'] for c in calls] == [r['toolCallId'] for r in results]
|
|
21
21
|
assert not any(r['isError'] for r in results)
|
|
22
22
|
assert [c['name'] for c in calls].count('bash') >= 5 and {'write', 'edit', 'read'} <= {c['name'] for c in calls}
|
|
23
|
-
assert sum(r['content'][0]['text'] == 'Success.' for r in results) == 4 #
|
|
23
|
+
assert sum(r['content'][0]['text'] == 'Success.' for r in results) == 4 # motrace-prepare after each step
|
|
24
24
|
assert msgs[-1]['role'] == 'assistant' and msgs[-1]['stopReason'] == 'stop'
|
|
25
25
|
assert len(ro['snapshots']) == sum(m['role'] == 'assistant' for m in msgs)
|
|
26
26
|
|
|
@@ -57,15 +57,15 @@ def test_edit_for(old, new):
|
|
|
57
57
|
assert e['oldText'] and old.count(e['oldText']) == 1 and old.replace(e['oldText'], e['newText']) == new
|
|
58
58
|
|
|
59
59
|
def test_failing_notebook_is_rejected(tmp_path):
|
|
60
|
-
(tmp_path/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.
|
|
60
|
+
(tmp_path/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.motrace]\n')
|
|
61
61
|
nb = mk_marimo(tmp_path/'jobs/bad.py', ['#| default_exp core', '#| export\ndef f(): return 1', 'assert f() == 2'])
|
|
62
|
-
with pytest.raises(RuntimeError, match='fails
|
|
62
|
+
with pytest.raises(RuntimeError, match='fails motrace-prepare'): rollout(nb)
|
|
63
63
|
|
|
64
|
-
# ---------------------------------------------------------------- Tinker rendering (needs
|
|
64
|
+
# ---------------------------------------------------------------- Tinker rendering (needs motrace[tinker])
|
|
65
65
|
|
|
66
66
|
def test_render_for_inkling(ro):
|
|
67
67
|
pytest.importorskip('tinker_cookbook')
|
|
68
|
-
from
|
|
68
|
+
from motrace.convert import _renderer, render
|
|
69
69
|
sft, opd = render(ro)
|
|
70
70
|
toks, ins = sft['model_input'], sft['loss_fn_inputs']
|
|
71
71
|
assert len(toks) == len(ins['target_tokens']) == len(ins['weights'])
|
|
@@ -74,7 +74,7 @@ def test_render_for_inkling(ro):
|
|
|
74
74
|
tok = _renderer(sft['model']).tokenizer
|
|
75
75
|
trained = tok.decode([t for t, w in zip(ins['target_tokens'], ins['weights']) if w])
|
|
76
76
|
shown = tok.decode(toks)
|
|
77
|
-
assert '
|
|
77
|
+
assert 'motrace-prepare' in trained and '"name":"edit"' in trained # tool calls are trained on
|
|
78
78
|
thinking = [b['thinking'] for m in ro['messages'] if m['role'] == 'assistant' for b in m['content'] if b['type'] == 'thinking']
|
|
79
79
|
assert all(t in trained for t in thinking) # reasoning from the markdown is trained on
|
|
80
80
|
assert 'Successfully replaced' in shown and 'Successfully replaced' not in trained # tool results are context only
|
|
@@ -87,7 +87,7 @@ def test_render_for_inkling(ro):
|
|
|
87
87
|
|
|
88
88
|
def test_cli_and_loaders(tmp_path):
|
|
89
89
|
pytest.importorskip('tinker_cookbook')
|
|
90
|
-
r = run(['
|
|
90
|
+
r = run(['motrace-convert', str(TINYLM), '-o', str(tmp_path/'out')], tmp_path)
|
|
91
91
|
assert '12 assistant turns' in r.stdout
|
|
92
92
|
[d] = load_sft(tmp_path/'out/sft.jsonl')
|
|
93
93
|
assert d.model_input.length == len(d.loss_fn_inputs['weights'].data)
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""motrace's three commands, checked directly and against nbdev itself on equivalent .ipynb notebooks."""
|
|
2
2
|
import json, os, subprocess, sys, time
|
|
3
3
|
from pathlib import Path
|
|
4
4
|
|
|
5
5
|
import pytest
|
|
6
6
|
from conftest import mk_ipynb, mk_marimo, normalize, run
|
|
7
|
-
from
|
|
7
|
+
from motrace.core import read_nb
|
|
8
8
|
|
|
9
9
|
CORE = [
|
|
10
10
|
'import marimo as mo',
|
|
@@ -36,7 +36,7 @@ def test_export_matches_nbdev(projects):
|
|
|
36
36
|
nbd, mat = projects
|
|
37
37
|
make_twins(nbd, mat)
|
|
38
38
|
run(['nbdev-export'], nbd)
|
|
39
|
-
run(['
|
|
39
|
+
run(['motrace-export'], mat)
|
|
40
40
|
want, got = modules(nbd), modules(mat)
|
|
41
41
|
assert set(want) == set(got) == {'core.py', 'utils.py', 'sub/deep.py'}
|
|
42
42
|
for k in want: assert normalize(got[k]) == normalize(want[k]), k
|
|
@@ -52,7 +52,7 @@ def test_export_matches_nbdev(projects):
|
|
|
52
52
|
def test_exported_package_imports(projects):
|
|
53
53
|
_, mat = projects
|
|
54
54
|
make_twins(mat, mat, NBS)
|
|
55
|
-
run(['
|
|
55
|
+
run(['motrace-export'], mat)
|
|
56
56
|
r = subprocess.run([sys.executable, '-c', 'from mylib.sub.deep import X; from mylib.utils import shout; print(X, shout("a"))'],
|
|
57
57
|
cwd=mat, capture_output=True, text=True, check=True)
|
|
58
58
|
assert r.stdout.strip() == 'hello deep HELLO A'
|
|
@@ -62,7 +62,7 @@ def test_exported_package_imports(projects):
|
|
|
62
62
|
def test_cells_choose_their_module(tmp_path):
|
|
63
63
|
proj = tmp_path/'p'
|
|
64
64
|
(proj/'jobs').mkdir(parents=True)
|
|
65
|
-
(proj/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.
|
|
65
|
+
(proj/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.motrace]\n')
|
|
66
66
|
mk_marimo(proj/'jobs'/'one.py', [
|
|
67
67
|
'#| default_exp core\nimport math',
|
|
68
68
|
'#| export\ndef area(r): return math.pi * r * r',
|
|
@@ -70,11 +70,11 @@ def test_cells_choose_their_module(tmp_path):
|
|
|
70
70
|
'#| export report\ndef report(r): return fmt(area(r))',
|
|
71
71
|
'assert report(1) == "3.14"',
|
|
72
72
|
])
|
|
73
|
-
run(['
|
|
73
|
+
run(['motrace-export'], proj)
|
|
74
74
|
lib = proj/'pkg'
|
|
75
75
|
assert sorted(p.relative_to(lib).as_posix() for p in lib.rglob('*.py')) == \
|
|
76
76
|
['__init__.py', 'core.py', 'io/__init__.py', 'io/fmt.py', 'report.py']
|
|
77
|
-
# marimo forbids redefining `area`/`fmt` in the report cell, so
|
|
77
|
+
# marimo forbids redefining `area`/`fmt` in the report cell, so motrace derives the imports from marimo's dataflow graph
|
|
78
78
|
assert '# %% auto #1\nfrom .core import area\nfrom .io.fmt import fmt\n' in (lib/'report.py').read_text()
|
|
79
79
|
assert '# %% auto #1\nimport math\n' in (lib/'core.py').read_text() # setup-cell import, cell itself not exported
|
|
80
80
|
r = subprocess.run([sys.executable, '-c', 'from pkg.report import report; print(report(2))'], cwd=proj,
|
|
@@ -89,12 +89,12 @@ def _edit(path, old, new):
|
|
|
89
89
|
def test_update_matches_nbdev(projects):
|
|
90
90
|
nbd, mat = projects
|
|
91
91
|
make_twins(nbd, mat)
|
|
92
|
-
run(['nbdev-export'], nbd); run(['
|
|
92
|
+
run(['nbdev-export'], nbd); run(['motrace-export'], mat)
|
|
93
93
|
for proj in (nbd, mat):
|
|
94
94
|
_edit(proj/'mylib/utils.py', 'greet(n).upper()', 'greet(n).title() + "!"')
|
|
95
95
|
_edit(proj/'mylib/core.py', 'return f"hello {name}"', 'return f"hi {name}"')
|
|
96
96
|
run(['nbdev-update'], nbd)
|
|
97
|
-
run(['
|
|
97
|
+
run(['motrace-export', '--update'], mat)
|
|
98
98
|
for name, idxs in (('01_utils', [1]), ('00_core', [4])):
|
|
99
99
|
nb = json.loads((nbd/'nbs'/f'{name}.ipynb').read_text())['cells']
|
|
100
100
|
mcells = read_nb(mat/'jobs'/f'{name}.py')[2]
|
|
@@ -103,35 +103,35 @@ def test_update_matches_nbdev(projects):
|
|
|
103
103
|
assert mcells[i].code == want
|
|
104
104
|
assert mcells[4].code.startswith('#| export\ndef greet') # directives kept
|
|
105
105
|
assert 'from mylib.core import greet' in read_nb(mat/'jobs/01_utils.py')[2][1].code # import made absolute again
|
|
106
|
-
run(['
|
|
106
|
+
run(['motrace-export'], mat) # and it round-trips
|
|
107
107
|
assert 'greet(n).title() + "!"' in (mat/'mylib/utils.py').read_text()
|
|
108
108
|
|
|
109
109
|
def test_export_then_update_is_a_noop(projects):
|
|
110
110
|
_, mat = projects
|
|
111
111
|
make_twins(mat, mat)
|
|
112
|
-
run(['
|
|
112
|
+
run(['motrace-clean'], mat)
|
|
113
113
|
before = {p: p.read_text() for p in (mat/'jobs').glob('*.py')}
|
|
114
|
-
run(['
|
|
115
|
-
assert run(['
|
|
114
|
+
run(['motrace-export'], mat)
|
|
115
|
+
assert run(['motrace-export', '--update'], mat).stdout == ''
|
|
116
116
|
assert {p: p.read_text() for p in (mat/'jobs').glob('*.py')} == before
|
|
117
117
|
|
|
118
118
|
def test_update_refuses_stale_cell_ids(projects):
|
|
119
119
|
_, mat = projects
|
|
120
120
|
make_twins(mat, mat, {'01_utils': UTILS})
|
|
121
|
-
run(['
|
|
121
|
+
run(['motrace-export'], mat)
|
|
122
122
|
mk_marimo(mat/'jobs/01_utils.py', ['x = 1'] + UTILS) # a cell was inserted after export
|
|
123
123
|
_edit(mat/'mylib/utils.py', '.upper()', '.lower()')
|
|
124
|
-
r = run(['
|
|
124
|
+
r = run(['motrace-export', '--update'], mat, check=False)
|
|
125
125
|
assert r.returncode and 'not an exported cell' in r.stderr
|
|
126
126
|
|
|
127
127
|
def test_update_refuses_cell_moved_to_other_module(projects):
|
|
128
128
|
_, mat = projects
|
|
129
129
|
codes = ['#| default_exp a', '#| export\ndef f(): return 1', '#| export b\ndef g(): return 2']
|
|
130
130
|
make_twins(mat, mat, {'n': codes})
|
|
131
|
-
run(['
|
|
131
|
+
run(['motrace-export'], mat)
|
|
132
132
|
mk_marimo(mat/'jobs/n.py', [codes[0], codes[2], codes[1]]) # cells swapped after export
|
|
133
133
|
_edit(mat/'mylib/a.py', 'return 1', 'return 10')
|
|
134
|
-
r = run(['
|
|
134
|
+
r = run(['motrace-export', '--update'], mat, check=False)
|
|
135
135
|
assert r.returncode and 'not an exported cell of `a`' in r.stderr
|
|
136
136
|
|
|
137
137
|
# ------------------------------------------------------------------ tests in notebooks: parity with nbdev-test
|
|
@@ -147,31 +147,31 @@ def test_test_outcome_matches_nbdev(projects, scenario):
|
|
|
147
147
|
nbd, mat = projects
|
|
148
148
|
make_twins(nbd, mat, {scenario: SCENARIOS[scenario]})
|
|
149
149
|
want = run(['nbdev-test'], nbd, check=False).returncode == 0
|
|
150
|
-
r = run(['
|
|
150
|
+
r = run(['motrace-prepare'], mat, check=False)
|
|
151
151
|
assert (r.returncode == 0) == want == (scenario != 'fail')
|
|
152
152
|
if scenario == 'fail': assert 'fail.py' in r.stderr and 'y should be 2' in r.stderr
|
|
153
153
|
|
|
154
154
|
def test_tests_run_in_parallel_in_notebook_dir(tmp_path):
|
|
155
155
|
proj = tmp_path/'p'
|
|
156
156
|
(proj/'jobs').mkdir(parents=True)
|
|
157
|
-
(proj/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.
|
|
157
|
+
(proj/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.motrace]\n')
|
|
158
158
|
(proj/'jobs/data.txt').write_text('ok')
|
|
159
159
|
for i in range(4):
|
|
160
160
|
mk_marimo(proj/'jobs'/f'nb{i}.py', ['import time', 'time.sleep(3)', 'assert open("data.txt").read() == "ok"'])
|
|
161
161
|
mk_marimo(proj/'jobs'/'_draft.py', ['assert False']) # skipped, like nbdev: leading underscore
|
|
162
162
|
start = time.time()
|
|
163
|
-
r = run(['
|
|
163
|
+
r = run(['motrace-prepare', '--n_workers', '4', '--timing'], proj)
|
|
164
164
|
elapsed = time.time() - start
|
|
165
165
|
assert 'Success.' in r.stdout and r.stdout.count('secs') == 4
|
|
166
166
|
assert elapsed < 9, elapsed # serial would be >= 12s of sleeping alone
|
|
167
|
-
assert not list((proj/'jobs').glob('.
|
|
167
|
+
assert not list((proj/'jobs').glob('.motrace_*')) # temp files cleaned up
|
|
168
168
|
|
|
169
169
|
# ------------------------------------------------------------------ guide
|
|
170
170
|
|
|
171
171
|
@pytest.mark.parametrize('args', [[], ['--help']])
|
|
172
172
|
def test_guide(tmp_path, args):
|
|
173
|
-
r = run(['
|
|
174
|
-
for s in ('IN A MARIMO NOTEBOOK', 'IN THE CLI', 'ORGANIZING NOTEBOOKS', '#| export io.fmt', '
|
|
173
|
+
r = run(['motrace', *args], tmp_path) # works outside a motrace project
|
|
174
|
+
for s in ('IN A MARIMO NOTEBOOK', 'IN THE CLI', 'ORGANIZING NOTEBOOKS', '#| export io.fmt', 'motrace-export --update'):
|
|
175
175
|
assert s in r.stdout
|
|
176
176
|
|
|
177
177
|
# ------------------------------------------------------------------ clean
|
|
@@ -179,15 +179,15 @@ def test_guide(tmp_path, args):
|
|
|
179
179
|
def test_clean(tmp_path):
|
|
180
180
|
proj = tmp_path/'p'
|
|
181
181
|
(proj/'pyproject.toml').parent.mkdir(parents=True)
|
|
182
|
-
(proj/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.
|
|
182
|
+
(proj/'pyproject.toml').write_text('[project]\nname = "pkg"\n\n[tool.motrace]\n')
|
|
183
183
|
nb = mk_marimo(proj/'jobs/a.py', ['#| export\ndef f(): return 1 ', 'x = f() \n\n'])
|
|
184
184
|
nb.write_text(nb.read_text().replace('__generated_with = "', '__generated_with = "0.1.0-old'))
|
|
185
|
-
r = run(['
|
|
185
|
+
r = run(['motrace-clean'], proj)
|
|
186
186
|
assert 'cleaned' in r.stdout
|
|
187
187
|
text = nb.read_text()
|
|
188
188
|
assert '__generated_with = "0.1.0-old' in text # don't churn the version line
|
|
189
189
|
assert not any(l != l.rstrip() for l in text.splitlines()) # trailing whitespace gone
|
|
190
|
-
assert run(['
|
|
191
|
-
assert subprocess.run([str(Path(sys.executable).parent/'
|
|
190
|
+
assert run(['motrace-clean'], proj).stdout == '' # idempotent
|
|
191
|
+
assert subprocess.run([str(Path(sys.executable).parent/'motrace-clean'), '--stdin'], input=text,
|
|
192
192
|
capture_output=True, text=True).stdout == text
|
|
193
193
|
assert subprocess.run([sys.executable, str(nb)], capture_output=True).returncode == 0 # still a working notebook
|
|
File without changes
|
|
File without changes
|