jellycell 1.0.0__py3-none-any.whl
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.
- jellycell/__init__.py +8 -0
- jellycell/__main__.py +14 -0
- jellycell/_version.py +29 -0
- jellycell/agent-guide.md +233 -0
- jellycell/api.py +375 -0
- jellycell/cache/__init__.py +28 -0
- jellycell/cache/function_cache.py +130 -0
- jellycell/cache/hashing.py +93 -0
- jellycell/cache/index.py +194 -0
- jellycell/cache/manifest.py +144 -0
- jellycell/cache/store.py +101 -0
- jellycell/cli/__init__.py +0 -0
- jellycell/cli/app.py +90 -0
- jellycell/cli/commands/__init__.py +0 -0
- jellycell/cli/commands/cache.py +296 -0
- jellycell/cli/commands/checkpoint.py +403 -0
- jellycell/cli/commands/export.py +173 -0
- jellycell/cli/commands/init.py +71 -0
- jellycell/cli/commands/lint.py +115 -0
- jellycell/cli/commands/new.py +82 -0
- jellycell/cli/commands/prompt.py +35 -0
- jellycell/cli/commands/render.py +109 -0
- jellycell/cli/commands/run.py +133 -0
- jellycell/cli/commands/view.py +80 -0
- jellycell/cli/journal.py +159 -0
- jellycell/config.py +170 -0
- jellycell/export/__init__.py +20 -0
- jellycell/export/ipynb.py +132 -0
- jellycell/export/myst.py +112 -0
- jellycell/export/tearsheet.py +327 -0
- jellycell/format/__init__.py +24 -0
- jellycell/format/cells.py +77 -0
- jellycell/format/parse.py +106 -0
- jellycell/format/pep723.py +121 -0
- jellycell/format/static_deps.py +97 -0
- jellycell/format/tags.py +95 -0
- jellycell/lint/__init__.py +13 -0
- jellycell/lint/rules.py +374 -0
- jellycell/paths.py +168 -0
- jellycell/py.typed +0 -0
- jellycell/render/__init__.py +11 -0
- jellycell/render/manuscript.py +218 -0
- jellycell/render/markdown.py +31 -0
- jellycell/render/outputs.py +113 -0
- jellycell/render/renderer.py +462 -0
- jellycell/render/templates/index.html.j2 +129 -0
- jellycell/render/templates/manuscript.html.j2 +104 -0
- jellycell/render/templates/manuscripts_index.html.j2 +98 -0
- jellycell/render/templates/page.html.j2 +85 -0
- jellycell/render/templates/partials/cell.html.j2 +43 -0
- jellycell/render/templates/partials/script.js.j2 +50 -0
- jellycell/render/templates/partials/styles.css.j2 +403 -0
- jellycell/run/__init__.py +8 -0
- jellycell/run/capture.py +53 -0
- jellycell/run/context.py +57 -0
- jellycell/run/env_hash.py +68 -0
- jellycell/run/kernel.py +114 -0
- jellycell/run/pool.py +87 -0
- jellycell/run/runner.py +525 -0
- jellycell/server/__init__.py +21 -0
- jellycell/server/app.py +338 -0
- jellycell/server/sse.py +71 -0
- jellycell/server/watch.py +72 -0
- jellycell-1.0.0.dist-info/METADATA +218 -0
- jellycell-1.0.0.dist-info/RECORD +68 -0
- jellycell-1.0.0.dist-info/WHEEL +4 -0
- jellycell-1.0.0.dist-info/entry_points.txt +2 -0
- jellycell-1.0.0.dist-info/licenses/LICENSE +201 -0
jellycell/__init__.py
ADDED
jellycell/__main__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Entry point for ``python -m jellycell`` — delegates to :mod:`jellycell.cli.app`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from jellycell.cli.app import app
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
"""Entry for ``python -m jellycell``."""
|
|
10
|
+
app()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
if __name__ == "__main__":
|
|
14
|
+
main()
|
jellycell/_version.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Version and cache-key-version constants.
|
|
2
|
+
|
|
3
|
+
``__version__`` is the public semver string. Hatchling reads it for build
|
|
4
|
+
metadata. The versioning policy lives in
|
|
5
|
+
:doc:`docs/development/releasing.md` — tl;dr: **patch-bump freely, minor
|
|
6
|
+
for additive features, major only for breaking contracts**.
|
|
7
|
+
|
|
8
|
+
``MINOR_VERSION`` is a separate counter baked into the cache key so stale
|
|
9
|
+
entries invalidate cleanly when the hash algorithm changes. It is **not**
|
|
10
|
+
semver — it only moves when something in :mod:`jellycell.cache.hashing`
|
|
11
|
+
(normalization, which inputs go in, or how they're combined) changes, or
|
|
12
|
+
when a cached pydantic schema gains/renames a field.
|
|
13
|
+
|
|
14
|
+
See CLAUDE.md and spec §10 for the full contract.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
__version__ = "1.0.0"
|
|
20
|
+
|
|
21
|
+
MINOR_VERSION: int = 1
|
|
22
|
+
"""Spec §10.2 cache-key counter. Bump on any cache/hashing behavior change.
|
|
23
|
+
|
|
24
|
+
Post-1.0 bumps should be rare and each one gets a one-line note below with
|
|
25
|
+
the date and what changed — so future agents can trace the history.
|
|
26
|
+
|
|
27
|
+
- v1 (2026-04-18, initial): source + sorted dep keys + env_hash (lockfile
|
|
28
|
+
preferred, PEP-723 fallback) + MINOR_VERSION.
|
|
29
|
+
"""
|
jellycell/agent-guide.md
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# Agent guide
|
|
2
|
+
|
|
3
|
+
:::{important}
|
|
4
|
+
Spec §10.3 stability contract. Content here is what `jellycell prompt` emits.
|
|
5
|
+
Patch-version releases MUST NOT change this page. Minor-version releases can
|
|
6
|
+
update it; every change gets a CHANGELOG entry.
|
|
7
|
+
:::
|
|
8
|
+
|
|
9
|
+
## What jellycell is
|
|
10
|
+
|
|
11
|
+
**jellycell** is a reproducible-analysis notebook tool. You write `.py` files
|
|
12
|
+
in jupytext percent format with optional PEP-723 dependency blocks; jellycell
|
|
13
|
+
runs them via a subprocess Jupyter kernel, caches cell outputs by content hash,
|
|
14
|
+
and serves a live HTML catalogue.
|
|
15
|
+
|
|
16
|
+
Agents: run `jellycell prompt` at the start of any new jellycell project to
|
|
17
|
+
pull this guide into your context.
|
|
18
|
+
|
|
19
|
+
## Project layout
|
|
20
|
+
|
|
21
|
+
Every jellycell project has a `jellycell.toml` at the root and this canonical
|
|
22
|
+
directory layout (all paths configurable via `[paths]` in `jellycell.toml`):
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
my-project/
|
|
26
|
+
├── jellycell.toml # project config
|
|
27
|
+
├── notebooks/ # .py source notebooks (jupytext percent format)
|
|
28
|
+
├── data/ # input data, read by jc.load
|
|
29
|
+
├── artifacts/ # writable output files (images, parquet, json, ...)
|
|
30
|
+
├── site/ # rendered HTML output
|
|
31
|
+
├── manuscripts/ # narrative docs (optional)
|
|
32
|
+
└── .jellycell/
|
|
33
|
+
└── cache/ # content-addressed cache (git-ignored)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## File format
|
|
37
|
+
|
|
38
|
+
A notebook is a single `.py` file in jupytext percent format:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
# /// script
|
|
42
|
+
# requires-python = ">=3.11"
|
|
43
|
+
# dependencies = ["pandas"]
|
|
44
|
+
# ///
|
|
45
|
+
|
|
46
|
+
# %% [markdown]
|
|
47
|
+
# # Analysis title
|
|
48
|
+
|
|
49
|
+
# %% tags=["jc.load", "name=raw"]
|
|
50
|
+
import pandas as pd
|
|
51
|
+
df = pd.read_csv("data/input.csv")
|
|
52
|
+
|
|
53
|
+
# %% tags=["jc.step", "name=summary", "deps=raw"]
|
|
54
|
+
summary = df.describe()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Rules:
|
|
58
|
+
|
|
59
|
+
- The **PEP-723 block** (if present) must be at the top of the file. A lint
|
|
60
|
+
rule rejects mid-file blocks with a `--fix` that moves them.
|
|
61
|
+
- Cells are separated by `# %%` markers. Markdown cells use `# %% [markdown]`.
|
|
62
|
+
- Cell metadata (especially `tags=[...]`) goes in the marker line.
|
|
63
|
+
- The file is valid Python — `uv run --script notebook.py` works.
|
|
64
|
+
|
|
65
|
+
## Cell tags
|
|
66
|
+
|
|
67
|
+
Tags live in the `tags=[...]` list on the cell marker:
|
|
68
|
+
|
|
69
|
+
| Tag | Meaning | Extra attrs |
|
|
70
|
+
| ------------ | --------------------------------------------- | -------------------- |
|
|
71
|
+
| `jc.load` | Loads input data (conventionally from `data/`) | `name=` |
|
|
72
|
+
| `jc.step` | Default — transform or compute | `name=`, `deps=a,b` |
|
|
73
|
+
| `jc.figure` | Writes an image artifact | `name=` |
|
|
74
|
+
| `jc.table` | Writes a tabular artifact | `name=` |
|
|
75
|
+
| `jc.setup` | No deps; not cached; runs first | — |
|
|
76
|
+
| `jc.note` | Markdown-only; not executable | — |
|
|
77
|
+
|
|
78
|
+
`deps=a,b` declares that this cell depends on cells named `a` and `b`. The
|
|
79
|
+
cache key incorporates dep cells' hashes so invalidation propagates correctly.
|
|
80
|
+
|
|
81
|
+
Untagged code cells default to `jc.step` with an auto-generated name like
|
|
82
|
+
`<notebook>:<ordinal>`.
|
|
83
|
+
|
|
84
|
+
## The `jc.*` API
|
|
85
|
+
|
|
86
|
+
What you import inside a notebook cell:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import jellycell.api as jc
|
|
90
|
+
|
|
91
|
+
# writes — all take optional caption=/notes=/tags= metadata
|
|
92
|
+
jc.save(obj, "artifacts/summary.json", caption="Headline stats")
|
|
93
|
+
jc.save(df, "artifacts/data.parquet")
|
|
94
|
+
jc.figure(
|
|
95
|
+
"artifacts/plot.png",
|
|
96
|
+
fig=plt.gcf(),
|
|
97
|
+
caption="Figure 1: mortality by country",
|
|
98
|
+
notes="DE stands out; JP lowest.",
|
|
99
|
+
tags=["result", "figure"],
|
|
100
|
+
)
|
|
101
|
+
jc.table(df, name="results", caption="Table 1: per-country totals")
|
|
102
|
+
|
|
103
|
+
# reads (registers a dep edge on the producing cell when inside a run)
|
|
104
|
+
jc.load("artifacts/summary.json")
|
|
105
|
+
|
|
106
|
+
# explicit deps — AST-walked statically, so they enter the cache key
|
|
107
|
+
# before the cell runs (the runner parses jc.deps(...) out of cell source).
|
|
108
|
+
jc.deps("raw", "processed")
|
|
109
|
+
|
|
110
|
+
# function-level memoization — uses the same CacheStore as cells.
|
|
111
|
+
@jc.cache
|
|
112
|
+
def expensive(x, y):
|
|
113
|
+
return heavy_compute(x, y)
|
|
114
|
+
|
|
115
|
+
# cache context (read-only)
|
|
116
|
+
jc.ctx.notebook # "notebooks/foo.py"
|
|
117
|
+
jc.ctx.cell_id # "foo:3"
|
|
118
|
+
jc.ctx.cell_name # "summary" or None
|
|
119
|
+
jc.ctx.project # the jellycell.paths.Project
|
|
120
|
+
jc.ctx.inside_run # True inside `jellycell run`; False standalone
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
All `jc.*` calls work standalone (plain file ops) OR inside `jellycell run`
|
|
124
|
+
(path resolution relative to the project root; artifacts tracked in the
|
|
125
|
+
cell's manifest).
|
|
126
|
+
|
|
127
|
+
Supported `jc.save` formats: `.parquet`, `.csv`, `.json`, `.pkl`, `.png`.
|
|
128
|
+
|
|
129
|
+
## CLI commands
|
|
130
|
+
|
|
131
|
+
| Command | Purpose |
|
|
132
|
+
| ---------------------------------- | ------------------------------------------------ |
|
|
133
|
+
| `jellycell init <path>` | Scaffold a new project |
|
|
134
|
+
| `jellycell lint [path] [--fix]` | Run lint rules; auto-fix where possible |
|
|
135
|
+
| `jellycell run <notebook>` | Execute a notebook (cached cells skipped) |
|
|
136
|
+
| `jellycell render [notebook]` | Render HTML to `site/` |
|
|
137
|
+
| `jellycell view` | Serve live catalogue (requires `[server]` extra) |
|
|
138
|
+
| `jellycell cache list` | List cached cell executions |
|
|
139
|
+
| `jellycell cache prune` | Remove old entries (`--older-than`, `--keep-last`) |
|
|
140
|
+
| `jellycell cache clear` | Wipe the cache |
|
|
141
|
+
| `jellycell cache rebuild-index` | Rebuild SQLite index from manifests |
|
|
142
|
+
| `jellycell export ipynb <nb>` | Export to `.ipynb` with cached outputs |
|
|
143
|
+
| `jellycell export md <nb>` | Export to MyST markdown (full notebook + outputs) |
|
|
144
|
+
| `jellycell export tearsheet <nb>` | Curated markdown tearsheet → `manuscripts/tearsheets/<stem>.md` |
|
|
145
|
+
| `jellycell checkpoint create` | Reproducible `.tar.gz` snapshot of the project |
|
|
146
|
+
| `jellycell checkpoint list` | Show existing checkpoints |
|
|
147
|
+
| `jellycell checkpoint restore` | Extract a checkpoint to a new sibling directory |
|
|
148
|
+
| `jellycell new <name>` | Scaffold a new notebook |
|
|
149
|
+
| `jellycell prompt` | Emit this guide to stdout |
|
|
150
|
+
|
|
151
|
+
Every command supports `--json` for machine-readable output with
|
|
152
|
+
`schema_version: 1`.
|
|
153
|
+
|
|
154
|
+
## Idiomatic patterns
|
|
155
|
+
|
|
156
|
+
- **Name every cell** (`name=foo`). Named cells are referenceable from
|
|
157
|
+
`deps=...`, discoverable in manifests, and easier to re-run selectively.
|
|
158
|
+
- **Declare deps explicitly**. Running `jellycell lint` with
|
|
159
|
+
`enforce_declared_deps = true` catches undeclared implicit deps.
|
|
160
|
+
- **Write artifacts under `artifacts/`**, not inline to the notebook's
|
|
161
|
+
directory. The `enforce_artifact_paths` rule catches mistakes.
|
|
162
|
+
- **Inter-cell data goes through `jc.save`/`jc.load`.** Cells that are
|
|
163
|
+
cached don't re-execute — their in-memory variables aren't available to
|
|
164
|
+
re-executed dependent cells. The `jellycell run` CLI warns when a run
|
|
165
|
+
mixes cache hits and re-executions.
|
|
166
|
+
- **Commit a lockfile for reproducibility.** `env_hash` prefers
|
|
167
|
+
`uv.lock` / `poetry.lock` bytes over the PEP-723 `dependencies` list, so
|
|
168
|
+
two environments with matching dep names but different resolved versions
|
|
169
|
+
don't silently share caches.
|
|
170
|
+
- **Keep cells small**. One logical operation per cell means the cache is
|
|
171
|
+
granular. Change one summary → only the summary re-runs.
|
|
172
|
+
- **PEP-723 `[tool.jellycell]` overrides** apply at file scope. Supported
|
|
173
|
+
keys: `project.name`, `run.kernel`, `run.timeout_seconds`. Unknown keys
|
|
174
|
+
raise a lint error (no silent typos).
|
|
175
|
+
- **Don't mock the cache**. If tests need the cache, use a real
|
|
176
|
+
`CacheStore` against `tmp_path`.
|
|
177
|
+
- **Share results via tearsheets.** `jellycell export tearsheet <nb>`
|
|
178
|
+
writes a curated markdown file to `manuscripts/tearsheets/<stem>.md`:
|
|
179
|
+
prose from markdown cells, inlined figures via relative paths, JSON
|
|
180
|
+
summaries flattened to two-column tables. The `tearsheets/` subfolder
|
|
181
|
+
convention keeps auto-generated files separate from hand-authored
|
|
182
|
+
writeups (paper drafts, memos, thesis chapters) that live at the root
|
|
183
|
+
of `manuscripts/`. GitHub renders the result inline — no HTML preview
|
|
184
|
+
service needed; commit it alongside the notebook so reviewers see the
|
|
185
|
+
latest run without cloning.
|
|
186
|
+
- **Pick an artifact layout that matches the project.** `[artifacts]
|
|
187
|
+
layout` in `jellycell.toml` controls where path-less `jc.figure()` /
|
|
188
|
+
`jc.table()` writes: `"flat"` (default), `"by_notebook"` →
|
|
189
|
+
`artifacts/<notebook>/<name>.<ext>`, or `"by_cell"` →
|
|
190
|
+
`artifacts/<notebook>/<cell>/<name>.<ext>`. `"by_cell"` makes every
|
|
191
|
+
artifact self-identifying — handy for agents that need to trace
|
|
192
|
+
"which cell produced this file?" without opening manifests.
|
|
193
|
+
- **Commit the story, git-ignore the bulk.** For datasets too big to
|
|
194
|
+
commit, set `[artifacts] max_committed_size_mb` and let `jellycell
|
|
195
|
+
run` warn you when an artifact crosses the line. Commit a tiny
|
|
196
|
+
`headline.json` summary instead, git-ignore (or Git-LFS) the bytes,
|
|
197
|
+
and reviewers regenerate from the seed + notebook locally. See
|
|
198
|
+
`examples/large-data/` for the full pattern.
|
|
199
|
+
- **Caption your artifacts.** `jc.save`, `jc.figure`, and `jc.table`
|
|
200
|
+
all accept `caption="..."`, `notes="..."`, `tags=[...]`. Captions
|
|
201
|
+
become figure/table headings in tearsheets; notes render as an
|
|
202
|
+
italic subcaption; tags are free-form labels for filtering. All
|
|
203
|
+
optional — empty by default, no nagging. See `examples/paper/` and
|
|
204
|
+
`examples/ml-experiment/` for the full metadata flow.
|
|
205
|
+
- **Record the trajectory.** `jellycell run -m "fixed sign on yoy"`
|
|
206
|
+
appends a timestamped entry to `manuscripts/journal.md` with the
|
|
207
|
+
cell summary, any new artifacts, and your message. Opt-out via
|
|
208
|
+
`[journal] enabled = false`; append-only from jellycell's side so
|
|
209
|
+
hand-edited commentary survives future runs. The journal is the
|
|
210
|
+
fastest way for a reviewer (or you in six months) to answer
|
|
211
|
+
"why did the numbers change?".
|
|
212
|
+
- **Snapshot a known-good state.** `jellycell checkpoint create -m
|
|
213
|
+
"submitted for review"` bundles the project into a
|
|
214
|
+
`.tar.gz` under `.jellycell/checkpoints/`. `jellycell checkpoint
|
|
215
|
+
restore <name>` extracts into a sibling directory by default — the
|
|
216
|
+
live project is never touched unless you explicitly opt in with
|
|
217
|
+
`--force`. Good for reproducibility handoffs and "safe rollback to
|
|
218
|
+
before I fixed the sign error" moves.
|
|
219
|
+
|
|
220
|
+
## Invariants (§10 contracts)
|
|
221
|
+
|
|
222
|
+
Three contracts, stable across patch releases. Living statement +
|
|
223
|
+
ceremony in [reference/contracts](reference/contracts.md):
|
|
224
|
+
|
|
225
|
+
1. **§10.1 `--json` schemas** carry `schema_version: 1`. Additive
|
|
226
|
+
fields (optional + default) are patch- or minor-safe; renames,
|
|
227
|
+
removals, and type changes force a major bump.
|
|
228
|
+
2. **§10.2 Cache key algorithm** (`jellycell.cache.hashing`) is frozen
|
|
229
|
+
unless `MINOR_VERSION` in `_version.py` is bumped — which forces
|
|
230
|
+
every cache to invalidate cleanly and rides a major release.
|
|
231
|
+
3. **§10.3 Agent guide content** (what `jellycell prompt` emits).
|
|
232
|
+
Typo / clarification edits ride a patch; additive sections ride a
|
|
233
|
+
minor; rewrites that change existing guidance force a major.
|
jellycell/api.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""The ``jc.*`` API — what notebook cells import (spec §2.4).
|
|
2
|
+
|
|
3
|
+
Every call has two modes:
|
|
4
|
+
|
|
5
|
+
- **Inside a run** (``jellycell.run.context.get_context()`` returns a non-None):
|
|
6
|
+
resolves paths relative to the project root, and side effects
|
|
7
|
+
(artifacts, declared deps, caption/notes/tags metadata) are picked up
|
|
8
|
+
by the runner.
|
|
9
|
+
- **Standalone** (no run context): falls back to a plain file op, no
|
|
10
|
+
manifest side effect.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import pickle
|
|
18
|
+
import uuid
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from jellycell.run.context import RunContext, get_context
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# ---------------------------------------------------------------------- writes
|
|
26
|
+
def save(
|
|
27
|
+
obj: Any,
|
|
28
|
+
path: str | Path,
|
|
29
|
+
*,
|
|
30
|
+
format: str | None = None,
|
|
31
|
+
caption: str | None = None,
|
|
32
|
+
notes: str | None = None,
|
|
33
|
+
tags: list[str] | None = None,
|
|
34
|
+
) -> Path:
|
|
35
|
+
"""Write ``obj`` to ``path``. Format inferred from suffix unless overridden.
|
|
36
|
+
|
|
37
|
+
Supported formats: ``parquet``, ``csv``, ``json``, ``pkl``, ``png``.
|
|
38
|
+
Duck-typed — the caller's object must support the corresponding method
|
|
39
|
+
(e.g., ``to_parquet`` for pandas DataFrames).
|
|
40
|
+
|
|
41
|
+
``caption`` / ``notes`` / ``tags`` are optional metadata — inside a run
|
|
42
|
+
they're attached to the produced artifact's :class:`ArtifactRecord` and
|
|
43
|
+
surfaced in tearsheets. Standalone: ignored (no manifest to write to).
|
|
44
|
+
"""
|
|
45
|
+
target = _resolve_out(path)
|
|
46
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
fmt = format or target.suffix.lstrip(".")
|
|
48
|
+
_write_by_format(obj, target, fmt)
|
|
49
|
+
_record_artifact_metadata(target, caption=caption, notes=notes, tags=tags)
|
|
50
|
+
return target
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def figure(
|
|
54
|
+
path: str | Path | None = None,
|
|
55
|
+
*,
|
|
56
|
+
caption: str | None = None,
|
|
57
|
+
notes: str | None = None,
|
|
58
|
+
tags: list[str] | None = None,
|
|
59
|
+
fig: Any = None,
|
|
60
|
+
) -> Path:
|
|
61
|
+
"""Save a matplotlib figure. If ``path`` is ``None``, a sensible default is chosen.
|
|
62
|
+
|
|
63
|
+
When no path is given inside a run, the default location respects the
|
|
64
|
+
project's ``[artifacts] layout`` setting (``flat`` / ``by_notebook`` /
|
|
65
|
+
``by_cell``). Explicit paths are always taken verbatim.
|
|
66
|
+
|
|
67
|
+
``caption`` / ``notes`` / ``tags`` flow into the artifact's
|
|
68
|
+
:class:`ArtifactRecord` and show up in tearsheets alongside the image.
|
|
69
|
+
"""
|
|
70
|
+
ctx = get_context()
|
|
71
|
+
if path is None:
|
|
72
|
+
stem = "figure"
|
|
73
|
+
if ctx is not None and ctx.cell_name:
|
|
74
|
+
stem = ctx.cell_name
|
|
75
|
+
elif ctx is not None:
|
|
76
|
+
stem = ctx.cell_id.replace(":", "_")
|
|
77
|
+
path_ = _layout_path(ctx, stem, "png")
|
|
78
|
+
else:
|
|
79
|
+
path_ = str(path)
|
|
80
|
+
|
|
81
|
+
target = _resolve_out(path_)
|
|
82
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
if fig is None:
|
|
84
|
+
import matplotlib.pyplot
|
|
85
|
+
|
|
86
|
+
fig = matplotlib.pyplot.gcf()
|
|
87
|
+
fig.savefig(target, bbox_inches="tight")
|
|
88
|
+
_record_artifact_metadata(target, caption=caption, notes=notes, tags=tags)
|
|
89
|
+
return target
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def table(
|
|
93
|
+
df: Any,
|
|
94
|
+
*,
|
|
95
|
+
caption: str | None = None,
|
|
96
|
+
notes: str | None = None,
|
|
97
|
+
tags: list[str] | None = None,
|
|
98
|
+
name: str | None = None,
|
|
99
|
+
) -> Path:
|
|
100
|
+
"""Save a tabular (pandas DataFrame) to a parquet artifact.
|
|
101
|
+
|
|
102
|
+
Like :func:`figure`, the default path honors ``[artifacts] layout`` and
|
|
103
|
+
``caption`` / ``notes`` / ``tags`` flow into the artifact's manifest record.
|
|
104
|
+
"""
|
|
105
|
+
ctx = get_context()
|
|
106
|
+
stem = name or (ctx.cell_name if ctx and ctx.cell_name else "table")
|
|
107
|
+
target = _resolve_out(_layout_path(ctx, stem, "parquet"))
|
|
108
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
df.to_parquet(target)
|
|
110
|
+
_record_artifact_metadata(target, caption=caption, notes=notes, tags=tags)
|
|
111
|
+
return target
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _record_artifact_metadata(
|
|
115
|
+
target: Path,
|
|
116
|
+
*,
|
|
117
|
+
caption: str | None,
|
|
118
|
+
notes: str | None,
|
|
119
|
+
tags: list[str] | None,
|
|
120
|
+
) -> None:
|
|
121
|
+
"""Stash caption/notes/tags for the runner to pick up.
|
|
122
|
+
|
|
123
|
+
Writes a small JSON into ``<cache_dir>/pending-meta/<uuid>.json`` inside
|
|
124
|
+
a run; no-op in standalone mode. Runner scans the directory after each
|
|
125
|
+
cell execution, enriches the corresponding :class:`ArtifactRecord`, and
|
|
126
|
+
cleans up. The filename is a uuid so two cells producing artifacts at
|
|
127
|
+
the same path in the same run don't step on each other.
|
|
128
|
+
"""
|
|
129
|
+
if caption is None and notes is None and not tags:
|
|
130
|
+
return
|
|
131
|
+
ctx = get_context()
|
|
132
|
+
if ctx is None:
|
|
133
|
+
return
|
|
134
|
+
try:
|
|
135
|
+
rel = str(target.resolve().relative_to(ctx.project.root.resolve()))
|
|
136
|
+
except ValueError:
|
|
137
|
+
return
|
|
138
|
+
meta_dir = ctx.project.cache_dir / "pending-meta"
|
|
139
|
+
meta_dir.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
# Prefix with a short path-hash so debugging is easier but uniqueness is
|
|
141
|
+
# still guaranteed by the uuid suffix.
|
|
142
|
+
prefix = hashlib.sha256(rel.encode("utf-8")).hexdigest()[:8]
|
|
143
|
+
target_file = meta_dir / f"{prefix}-{uuid.uuid4().hex}.json"
|
|
144
|
+
payload = {
|
|
145
|
+
"path": rel,
|
|
146
|
+
"caption": caption,
|
|
147
|
+
"notes": notes,
|
|
148
|
+
"tags": list(tags) if tags else [],
|
|
149
|
+
}
|
|
150
|
+
target_file.write_text(json.dumps(payload), encoding="utf-8")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _layout_path(ctx: RunContext | None, stem: str, ext: str) -> str:
|
|
154
|
+
"""Pick the default artifact path per ``[artifacts] layout``.
|
|
155
|
+
|
|
156
|
+
Standalone (no RunContext): always flat — we don't know notebook/cell
|
|
157
|
+
context. Inside a run: ``flat`` / ``by_notebook`` / ``by_cell``.
|
|
158
|
+
"""
|
|
159
|
+
if ctx is None:
|
|
160
|
+
return f"artifacts/{stem}.{ext}"
|
|
161
|
+
artifacts_dir = ctx.project.config.paths.artifacts
|
|
162
|
+
layout = ctx.project.config.artifacts.layout
|
|
163
|
+
notebook_stem = Path(ctx.notebook).stem if ctx.notebook else ""
|
|
164
|
+
cell = ctx.cell_name or ctx.cell_id.replace(":", "_")
|
|
165
|
+
if layout == "by_cell":
|
|
166
|
+
return f"{artifacts_dir}/{notebook_stem}/{cell}/{stem}.{ext}"
|
|
167
|
+
if layout == "by_notebook":
|
|
168
|
+
return f"{artifacts_dir}/{notebook_stem}/{stem}.{ext}"
|
|
169
|
+
return f"{artifacts_dir}/{stem}.{ext}"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ----------------------------------------------------------------------- reads
|
|
173
|
+
def load(path: str | Path) -> Any:
|
|
174
|
+
"""Load an object from ``path``. Format inferred from suffix.
|
|
175
|
+
|
|
176
|
+
Inside a run, also registers a dep edge on the producing cell (looked up
|
|
177
|
+
via :meth:`CacheIndex.find_producer`) so the caller's cache key
|
|
178
|
+
incorporates the producer's state. Best-effort: if the artifact has no
|
|
179
|
+
recorded producer yet, the load still succeeds without a dep edge.
|
|
180
|
+
"""
|
|
181
|
+
src = _resolve_out(path)
|
|
182
|
+
ctx = get_context()
|
|
183
|
+
if ctx is not None:
|
|
184
|
+
_register_producer_dep(ctx, path)
|
|
185
|
+
return _read_by_format(src, src.suffix.lstrip("."))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def path(name: str) -> Path:
|
|
189
|
+
"""Resolve a named artifact path.
|
|
190
|
+
|
|
191
|
+
If ``name`` matches a known cell's name (via the artifact lineage index),
|
|
192
|
+
returns the path of the artifact that cell produced. Otherwise falls back
|
|
193
|
+
to ``<artifacts>/<name>``.
|
|
194
|
+
"""
|
|
195
|
+
ctx = get_context()
|
|
196
|
+
if ctx is None:
|
|
197
|
+
return Path("artifacts") / name
|
|
198
|
+
# Try to resolve by producer cell name via the cache index.
|
|
199
|
+
try:
|
|
200
|
+
from jellycell.cache.index import CacheIndex
|
|
201
|
+
|
|
202
|
+
with CacheIndex(ctx.project.cache_dir / "state.db") as idx:
|
|
203
|
+
producer = _find_by_cell_name(idx, name, ctx.notebook)
|
|
204
|
+
except Exception:
|
|
205
|
+
producer = None
|
|
206
|
+
if producer:
|
|
207
|
+
return ctx.project.root / producer
|
|
208
|
+
return ctx.project.artifacts_dir / name
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _register_producer_dep(ctx: RunContext, artifact_path: str | Path) -> None:
|
|
212
|
+
"""Best-effort: add the producing cell's name to ``ctx.declared_deps``.
|
|
213
|
+
|
|
214
|
+
No-op on any exception — dep tracking is an enhancement, not a requirement
|
|
215
|
+
for the load to succeed.
|
|
216
|
+
"""
|
|
217
|
+
try:
|
|
218
|
+
from jellycell.cache.index import CacheIndex
|
|
219
|
+
except Exception:
|
|
220
|
+
return
|
|
221
|
+
|
|
222
|
+
rel = str(artifact_path)
|
|
223
|
+
if Path(rel).is_absolute():
|
|
224
|
+
try:
|
|
225
|
+
rel = str(Path(rel).resolve().relative_to(ctx.project.root.resolve()))
|
|
226
|
+
except ValueError:
|
|
227
|
+
return
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
with CacheIndex(ctx.project.cache_dir / "state.db") as idx:
|
|
231
|
+
producer = idx.find_producer(rel)
|
|
232
|
+
except Exception:
|
|
233
|
+
return
|
|
234
|
+
if not producer:
|
|
235
|
+
return
|
|
236
|
+
name = producer.get("cell_name")
|
|
237
|
+
if name and name not in ctx.declared_deps:
|
|
238
|
+
ctx.declared_deps.append(name)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _find_by_cell_name(index: object, cell_name: str, notebook: str) -> str | None:
|
|
242
|
+
"""Return the artifact path produced by ``cell_name`` in ``notebook``, if any."""
|
|
243
|
+
try:
|
|
244
|
+
cur = index._conn.execute( # type: ignore[attr-defined]
|
|
245
|
+
"SELECT a.path FROM artifacts a "
|
|
246
|
+
"JOIN cells c ON a.producer_cache_key = c.cache_key "
|
|
247
|
+
"WHERE c.cell_name = ? AND c.notebook = ? "
|
|
248
|
+
"ORDER BY c.executed_at DESC LIMIT 1",
|
|
249
|
+
(cell_name, notebook),
|
|
250
|
+
)
|
|
251
|
+
row = cur.fetchone()
|
|
252
|
+
except Exception:
|
|
253
|
+
return None
|
|
254
|
+
return row[0] if row else None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def deps(*names: str) -> None:
|
|
258
|
+
"""Declare explicit deps for this cell (spec §2.4).
|
|
259
|
+
|
|
260
|
+
At runtime this is a no-op — the runner AST-walks cell source statically
|
|
261
|
+
to find these calls before execution (spec §2.5). Runtime tracking is kept
|
|
262
|
+
as a fallback for dynamic cases.
|
|
263
|
+
"""
|
|
264
|
+
ctx = get_context()
|
|
265
|
+
if ctx is not None:
|
|
266
|
+
for n in names:
|
|
267
|
+
if n not in ctx.declared_deps:
|
|
268
|
+
ctx.declared_deps.append(n)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def cache(fn: Any) -> Any:
|
|
272
|
+
"""Memoize an expensive function via the cache store (spec §2.4).
|
|
273
|
+
|
|
274
|
+
Inside a run: keys on ``(qualname, normalized source, pickled args)`` and
|
|
275
|
+
persists the pickled return value alongside cell outputs.
|
|
276
|
+
|
|
277
|
+
Standalone (no RunContext): identity passthrough — no caching.
|
|
278
|
+
"""
|
|
279
|
+
from jellycell.cache.function_cache import cache_function
|
|
280
|
+
|
|
281
|
+
return cache_function(fn)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# ----------------------------------------------------------------------- ctx
|
|
285
|
+
class _Ctx:
|
|
286
|
+
"""Read-only accessor for the current :class:`RunContext`."""
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def notebook(self) -> str | None:
|
|
290
|
+
c = get_context()
|
|
291
|
+
return c.notebook if c else None
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def cell_id(self) -> str | None:
|
|
295
|
+
c = get_context()
|
|
296
|
+
return c.cell_id if c else None
|
|
297
|
+
|
|
298
|
+
@property
|
|
299
|
+
def cell_name(self) -> str | None:
|
|
300
|
+
c = get_context()
|
|
301
|
+
return c.cell_name if c else None
|
|
302
|
+
|
|
303
|
+
@property
|
|
304
|
+
def project(self) -> Any:
|
|
305
|
+
c = get_context()
|
|
306
|
+
return c.project if c else None
|
|
307
|
+
|
|
308
|
+
@property
|
|
309
|
+
def inside_run(self) -> bool:
|
|
310
|
+
"""True iff there's an active :class:`RunContext`."""
|
|
311
|
+
return get_context() is not None
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
ctx = _Ctx()
|
|
315
|
+
"""Singleton for ``jc.ctx`` access from cell code."""
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ----------------------------------------------------------------------- impl
|
|
319
|
+
def _resolve_out(path: str | Path) -> Path:
|
|
320
|
+
"""Resolve ``path`` against project root when inside a run, else CWD."""
|
|
321
|
+
p = Path(path)
|
|
322
|
+
ctx = get_context()
|
|
323
|
+
if ctx is None:
|
|
324
|
+
return p.resolve() if p.is_absolute() else (Path.cwd() / p).resolve()
|
|
325
|
+
if p.is_absolute():
|
|
326
|
+
raise ValueError("Absolute paths are not permitted inside a run.")
|
|
327
|
+
return ctx.project.resolve(p)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _write_by_format(obj: Any, target: Path, fmt: str) -> None:
|
|
331
|
+
"""Dispatch a write based on the file extension/format."""
|
|
332
|
+
if fmt == "parquet":
|
|
333
|
+
obj.to_parquet(target)
|
|
334
|
+
elif fmt == "csv":
|
|
335
|
+
obj.to_csv(target, index=False)
|
|
336
|
+
elif fmt == "json":
|
|
337
|
+
if hasattr(obj, "model_dump"):
|
|
338
|
+
target.write_text(obj.model_dump_json(indent=2), encoding="utf-8")
|
|
339
|
+
else:
|
|
340
|
+
target.write_text(json.dumps(obj, default=str, indent=2), encoding="utf-8")
|
|
341
|
+
elif fmt in ("pkl", "pickle"):
|
|
342
|
+
target.write_bytes(pickle.dumps(obj))
|
|
343
|
+
elif fmt == "png":
|
|
344
|
+
obj.savefig(target, bbox_inches="tight")
|
|
345
|
+
else:
|
|
346
|
+
raise ValueError(f"Unsupported format for jc.save: {fmt!r}")
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _read_by_format(src: Path, fmt: str) -> Any:
|
|
350
|
+
"""Dispatch a read based on the file extension/format."""
|
|
351
|
+
if fmt == "parquet":
|
|
352
|
+
import pandas as pd
|
|
353
|
+
|
|
354
|
+
return pd.read_parquet(src)
|
|
355
|
+
if fmt == "csv":
|
|
356
|
+
import pandas as pd
|
|
357
|
+
|
|
358
|
+
return pd.read_csv(src)
|
|
359
|
+
if fmt == "json":
|
|
360
|
+
return json.loads(src.read_text(encoding="utf-8"))
|
|
361
|
+
if fmt in ("pkl", "pickle"):
|
|
362
|
+
return pickle.loads(src.read_bytes())
|
|
363
|
+
raise ValueError(f"Unsupported format for jc.load: {fmt!r}")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
__all__ = [
|
|
367
|
+
"cache",
|
|
368
|
+
"ctx",
|
|
369
|
+
"deps",
|
|
370
|
+
"figure",
|
|
371
|
+
"load",
|
|
372
|
+
"path",
|
|
373
|
+
"save",
|
|
374
|
+
"table",
|
|
375
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Content-addressed cache for jellycell cell executions.
|
|
2
|
+
|
|
3
|
+
Exports:
|
|
4
|
+
- :mod:`jellycell.cache.hashing` — key derivation (§10.2 contract).
|
|
5
|
+
- :class:`Manifest` / :class:`OutputRecord` / :class:`ArtifactRecord`
|
|
6
|
+
— on-disk manifest schema.
|
|
7
|
+
- :class:`CacheStore` — the blob + manifest store.
|
|
8
|
+
- :class:`CacheIndex` — the SQLite catalogue accelerator.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from jellycell.cache.hashing import env_hash_from_deps, key, normalize_source, source_hash
|
|
14
|
+
from jellycell.cache.index import CacheIndex
|
|
15
|
+
from jellycell.cache.manifest import ArtifactRecord, Manifest, OutputRecord
|
|
16
|
+
from jellycell.cache.store import CacheStore
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ArtifactRecord",
|
|
20
|
+
"CacheIndex",
|
|
21
|
+
"CacheStore",
|
|
22
|
+
"Manifest",
|
|
23
|
+
"OutputRecord",
|
|
24
|
+
"env_hash_from_deps",
|
|
25
|
+
"key",
|
|
26
|
+
"normalize_source",
|
|
27
|
+
"source_hash",
|
|
28
|
+
]
|