Saving and loading¶
Saving a model¶
The code that builds a model runs once. Save the definition, and from then on load it:
model.save("retail.model.json") # dimensions, items, formulas, checks
model.to_jsonl("retail.values.jsonl") # values, kept apart
model = tm.load("retail.model.json")
model.load_jsonl("retail.values.jsonl")
- The definition and the values are separate files, as in XBRL (taxonomy vs instance): one agent defines the model, another enters values against it.
- A formula or check is saved as its lambda's source, with the values it uses beside it:
"formula": "lambda x: max(0, FLOOR - x['cash'])", "env": {"FLOOR": 25000}. Loading checks it against the formula allow-list and compiles it with RestrictedPython, asadd_itemdoes; nothing else in the file runs, andallow_codeisn't needed (it is accepted and ignored, with aDeprecationWarning). - Files saved by earlier versions load: expression text (
"cost * 0.6"), checks saved per label (expect_by_label) and{"python": ...}formulas are converted to lambdas, and saving again writes the lambdas. A saved formula that used the model itself ({"$model": true}) raises: rewrite it to read cells throughx. tm.load(path, formulas="off")loads the dimensions, items, checks and values but keeps formulas as text: nothing is compiled or run, formula cells have no value and checks don't run. Use it to read a file you don't trust; to calculate one, also run tracemodel in a sandbox such as gVisor (issue #7). RestrictedPython is one barrier, not a sandbox.tm.ANYis saved as"ANY". Item names must be Python identifiers (add_itemchecks), and attrs must hold JSON values.- Loading validates everything, as building the model in code does.
Values file format¶
to_jsonl writes one object per value:
{"line_item": "revenue", "coords": {"region": "/north", "period": "Q1"}, "value": 700, "source": {"document": "Q2 sales report", "url": "https://example.com/q2.pdf", "section": "Table 1"}}
A date is written as an ISO string ("value": "2026-03-31"). A nil cell is written with "value": null; a cell formula with "formula": "lambda x: ..." (and "env" when it uses values) instead of "value". A value that overrides a formula adds "overrides_formula": true.
Excel export¶
model.to_excel(path) writes the model for people who read models in Excel (needs
pip install "pytracemodel[excel]"):
model.to_excel("apple.xlsx", title="Apple FY2024-FY2025 (Form 10-K)", sections={
"Income statement": ["net_sales", "cost_of_sales", "gross_margin", "operating_expenses", "net_income"],
"Balance sheet": ["balance_sheet"],
"Cash flow": ["cash_flow"],
})
- Grids. Items are blocks one under the other, sharing the columns:
columns, elseperiod, else each item's last dim that isn't a hierarchy. A block's title is the item'sdescription(else its name in words); its rows are its other dims, in the first column, hierarchies indented and grouped so they collapse. With more than one dim down, they nest there as a pivot table's compact form: each label of the other dims is a group row, with the hierarchy's tree beneath it (version / contract: Plan, then the contracts, then Actual, ...); a group with no values is left out. Items with only hierarchy dims go across instead, one column each. - Sections group items, e.g. a statement each; items in no section group by their dims.
With
layout="sheet"the sections that share the columns go on one sheet, one after the other, each under a banner and, withpage_breaks, on its own printed page; withlayout="sheets"each section has its own sheet. - Cells follow the modelling convention: blue is entered, black is calculated; a yellow
fill is a value entered over a formula, a red fill a cell a failing check reads or found
missing. Nil shows as
—; a cell with no value is blank. Each cell's note gives its source, or its formula.split_after=("month", "2026-03")draws a line after a column, e.g. between actuals and forecast. - Tables follow the grids: Dimensions, Items, Checks, Check results, and Values, every entered value with its source and a link to it. A Summary sheet comes first, with the check status, a legend and links.
The workbook is a report: it holds values, not Excel formulas, and isn't read back.
The persistent store¶
A persistent store is one file of named models that a write updates like a spreadsheet: a write recalculates only what it
reaches, readers in any process never wait for the writer, and a page of a large model costs the page. It uses orjson
for fast loads when it is installed (it is a dependency, and built into Pyodide); without it the standard library gives the same results, only slower. It sits behind the Store interface, so the engine can change without changing the code that uses it.
import tracemodel.store as ts
with ts.open_store("models.store", write=True) as store: # keep_log=True by default
store.import_model("retail", model.to_dict(), rows)
store.append("retail", [{"line_item": "sales", "coords": {"t": "Q2"}, "value": 120, "source": {}}], "Q2 corrected")
with ts.open_store("models.store") as store: # read-only unless write=True
store.read_cells("retail", ["sales"], where={"company": ["acme"]}, limit=100) # a page: a seek and 100 rows
store.read_cells("retail", ["sales"], after=store.cursor(last_cell), limit=100) # the next page
- Labels are stored once. Each dimension keeps its labels in a dictionary, each distinct set of labels is stored once however
many measures share it, and a cell is a number beside a reference to it. By default every dimension is indexed (
index_dimensionsnarrows that), sowhere(the cells whose dimension has one of some labels) and a page of an item are seeks, not scans. The current value of each cell is one row; every value ever entered stays in a separate history table, so a restated cell keeps its earlier values. Cells come back in the order they were first stored, a page at a time. - The layout is replaceable. The store keeps its file, log, commits and definitions itself and keeps the cells through a
Layout. Each layout is a folder of its own undertracemodel/store/layouts/with a manifest that names its dependencies; the one that ships (sqlite/) keeps them in the same file and needs nothing installed. Another arrangement (a columnar file, a sparse-array engine) is a new folder, or an installed plugin, that passes the same tests, and a file is opened by the layout that made it (layout="name"chooses one for a new store). - The log. With
keep_log(on by default) every write is appended first to<file>.log, a JSONL record of what was written. The file is then derived:PersistentStore.rebuild("models.store")makes it again from the log, which is how a new schema or storage format is adopted, and a write that reached the log but not the file (a crash between the two) is applied when the store is next opened for writing. Without the log (keep_log=False) the file is the only record. The setting is made when the store is created; it can be turned off later, not back on. - Errors.
UnknownModel(no model of that name),NotCalculated(a read of a model whose calculated values are behind its latest commit),LogProblem(a log and its file disagree beyond repair, and the message says which),PermissionError(a write to a store opened read-only),tm.InvalidValue(a value a store cannot keep, such as a NaN) andValueError(an argument that is not valid: a cursor that is not this store's, a badlimit, an imported row that does not fit its model). A write that fails changes nothing. - Limits. One machine and a local disk (WAL needs shared memory), one writer at a time, and a file several times the size
of the same data in Parquet (4.2 million cells of a wide fact table: 295 MB, against 12 MB). Back up the file together with
its
-wal, or copy the log. - It has no branches, hashes or review: a model has one line of commits.
- Other engines.
Store.capabilitiessays which ofappend,read_cells,read_cellandcheck_failuresan engine fills in;tests/test_store_contract.pyis the suite a new engine must pass.