RedRoot
Trace Every Value to Its Roots
RedRoot records how every value in a Python computation was produced, at the level of individual values, so you can ask, in both directions:
Where did this output come from? · What does every output become if this input changes?
Run a computation once under RedRoot and you get a graph from inputs to outputs. Click a number that looks wrong and see the exact inputs and arithmetic behind it. Correct one input and every output that used it is recomputed from the graph, instantly and together, without running your code again. When the graph cannot be sure (a branch would go the other way, an LLM call would need re-running), RedRoot says so instead of guessing.
import redroot as rr
def workflow(ext):
a, b = ext["A"], ext["B"]
return {
"form1": {"line_12": a + b},
"form2": {"line_7": a * b},
"table3": {"amount": a},
"table4": {"total": b},
}
trace, _ = rr.run(workflow, {"A": 1200, "B": 300}, input_root="ext")
print(trace.sources("out:form1.line_12")) # [<Node #0 leaf ext:A=1200>, <Node #1 leaf ext:B=300>]
print(trace.explain("out:form2.line_7")) # ext:A * ext:B
print(trace.dependents("ext:A")) # ['out:form1.line_12', 'out:form2.line_7', 'out:table3.amount']
result = trace.propagate({"ext:A": 1300})
for key, change in result.outputs.items():
print(key, change.status.value, change.old, "->", change.new)
# out:form1.line_12 updated 1500 -> 1600
# out:form2.line_7 updated 360000 -> 390000
# out:table3.amount updated 1200 -> 1300
# out:table4.total unchanged 300 -> 300
Features
- Drop-in traced values.
TracedInt,TracedFloat,TracedDecimal,TracedStrand the date typesTracedDate,TracedDatetimeandTracedTimedeltaare real instances of the builtins they trace. Results, types and errors are exactly those of plain Python. - Re-evaluable graph. Every operand is recorded in order, constants included, so any node can be recomputed, not just read.
- Guards. Comparisons, branches, conversions and lookups are recorded. If an edit would change one, every output is reported
stalerather than shown with a value that may be wrong. - Semantic keys. Inputs and outputs are named by their path, e.g.
ext:bank.line_items[3].amount. - No cooperation needed from the code. Tracing happens through operator overloading. For code you run from source, such as generated code,
redroot.instrumentcloses the remaining gaps, including date parsing, regular expressions and lookups in fixed tables. - Fast on large runs. Recalculation visits only what an edit reaches: one edit in a run of 120,000 steps takes about 2 ms.
- Fix calculated values. Override any calculated step and everything after it is recalculated.
- Re-execution as the arbiter. Built-in tools compare the graph's answers with a real re-run, and measure coverage on your workloads.
- Safe to load. Traces record which version of each helper they used, and recalculation is bounded against tampered traces.
- Opaque steps.
@tracedturns a function (a tax-table lookup, a geocoder) into one re-callable node.@traced_llmmarks LLM calls as not replayable. - Persistable. Traces serialize to versioned JSON, ship with a CLI, and come with a web viewer plus GraphViz and NetworkX exports.
- Zero dependencies in the core. Pydantic, visualization and the web viewer are optional extras.
Installation
pip install redroot # core, no dependencies
pip install "redroot[pydantic]" # traced types as Pydantic fields
pip install "redroot[viz,web]" # GraphViz/NetworkX exports and the web viewer
Python 3.10 or newer is required.
Guide
Recording a trace
Operations on traced values are recorded while a Trace is active. Outside one, traced values behave exactly like plain values and nothing is recorded, so nothing accumulates in long-running processes.
from decimal import Decimal
import redroot as rr
extracted = {"bank": {"balance": Decimal("12450.00"), "fee": Decimal("12.50")}, "married": True}
with rr.Trace("run-42") as trace:
ext = trace.track(extracted, root="ext") # traced copy; inputs keyed by path
net = ext["bank"]["balance"] - ext["bank"]["fee"] * 12
trace.collect({"summary": {"net": net, "year": 2025}}, root="out")
print(list(trace.inputs)) # ['ext:bank.balance', 'ext:bank.fee']
print(trace.explain("out:summary.net")) # ext:bank.balance - (ext:bank.fee * 12)
# bool and None cannot be traced; such inputs are listed instead:
print(dict(trace.untracked_inputs)) # {'ext:married': True}
# 2025 was not computed from any input:
print(trace.outputs["out:summary.year"].linked) # False
rr.run(workflow, inputs, input_root=..., output_root=...) does the track, call and collect steps for you.
Extracted values often arrive wrapped with their provenance. envelope=rr.Envelope() keys each wrapped value by its field, traces it in place (the workflow sees the same shape) and stores the source on the input:
extracted = {"balance": {"value": Decimal("12450.00"), "source": {"file": "stmt.pdf", "page": 2}}}
with rr.Trace() as trace:
ext = trace.track(extracted, root="ext", envelope=rr.Envelope())
print(list(trace.inputs)) # ['ext:balance']
print(trace.inputs["ext:balance"].meta) # {'source': {'file': 'stmt.pdf', 'page': 2}}
track(..., meta=lambda key, value: {...}) attaches any other metadata.
Navigating backwards and forwards
| Question | Call |
|---|---|
| Which inputs produced this output? | trace.sources("out:form1.line_12") |
| Show me the computation. | trace.explain("out:form1.line_12") |
| Which outputs use this input? | trace.dependents("ext:A") |
| Every node involved | trace.ancestors(...), trace.descendants(...) |
Propagating an edit
trace.propagate(edits) re-evaluates only the nodes downstream of the edited inputs and reports, for every output:
| Status | Meaning |
|---|---|
UPDATED |
New value, computed exactly from the graph. |
UNCHANGED |
The edit does not affect this output. |
STALE |
The graph cannot be sure. Re-execute to get the value. |
UNLINKED |
The output is not linked to any traced input: a constant, or, in code that is not instrumented, a value computed where RedRoot cannot see (see below). |
The graph is only trusted while execution would follow the same path. Branches are the case a pure graph gets wrong:
def guarded(ext):
a, b = ext["A"], ext["B"]
line_12 = a + b if a > 1000 else 0
return {"line_12": line_12, "other": b * 2}
trace, _ = rr.run(guarded, {"A": 1200, "B": 300}, input_root="ext")
print(trace.propagate({"ext:A": 1100}).exact) # True
result = trace.propagate({"ext:A": 800}) # A > 1000 no longer holds
print(result.exact) # False
print(result.reasons[0].message) # ext:A > 1000 was True, now False
print(result.outputs["out:other"].status.value) # stale
When a guard flips, every output is reported stale, not just those computed under the branch. A trace only records the path that ran: writes on the other path are invisible to it, so no output can be vouched for. See docs/design.md.
Exceptions count as branches too: an operation that raised (and was caught) is recorded with its outcome, so an edit that makes it stop raising flips it. Other reasons for re-execution include an edit to an untracked input or to an input the run did not have (a new row), a value that changes type, an operation that would now raise, and an input change reaching a non-replayable step. Each is reported in result.reasons.
On large runs, trace.propagate(edits, changed_only=True) reports only the outputs that changed: recalculation itself already visits only what the edit reaches.
Fixing a calculated value
A reviewer may find that a calculated value is wrong rather than an input. Override it, and everything after it is recalculated, with decisions re-checked as usual:
def taxes(ext):
total = ext["wages"] + ext["interest"]
return {"total_income": total, "tax": (total * Decimal("0.2")).quantize(Decimal("0.01"))}
trace, _ = rr.run(
taxes, {"wages": Decimal("5000.00"), "interest": Decimal("120.00")}, input_root="ext"
)
result = trace.propagate({}, overrides={"out:total_income": Decimal("9000.00")})
for key, change in result.outputs.items():
print(key, change.status.value, change.new)
# out:total_income overridden 9000.00
# out:tax updated 1800.00
The overridden step keeps its value even if its own inputs are edited. A re-execution cannot apply an override, so verify() skips what overrides reach.
Verifying with re-execution
Re-execution on the edited inputs is the source of truth. The graph is the instant path.
inputs = {"A": 1200, "B": 300}
edits = {"ext:A": 1100}
trace, _ = rr.run(guarded, inputs, input_root="ext")
result = trace.propagate(edits)
retrace, _ = rr.run(guarded, rr.apply_edits(inputs, edits, root="ext"), input_root="ext")
assert result.verify(retrace.output_values()).ok
A mismatch on an output the graph claimed to know is a tracing gap. redroot.validation.check_perturbation runs this experiment in one call.
Lookups, external services and LLM calls
Decorate a step to record each call as one node. Deterministic functions are re-called during propagation; the others keep their recorded result until their inputs change.
@rr.traced(name="irs.national_standard")
def national_standard(household_size: int) -> Decimal:
return {1: Decimal("785"), 2: Decimal("1410"), 3: Decimal("1617")}[household_size]
@rr.traced(name="geo.county", deterministic=False) # e.g. a web lookup
def county_for_zip(zip_code: str) -> str:
return "Travis"
@rr.traced_llm(model="gpt-4o", task="summarize")
def summarize(text: str) -> str:
rr.annotate(prompt_tokens=len(text) // 4) # stored on the node
return text[:40]
with rr.Trace() as trace:
size = trace.leaf(3, "ext:household_size")
trace.output("out:allowance", national_standard(size) * 12)
print(trace.propagate({"ext:household_size": 2}).outputs["out:allowance"].new) # 16920
For results computed elsewhere, rr.derive(value, inputs, "op-name") records the link manually.
Running generated or untrusted-shape code: instrumentation
Operator overloading cannot see everything. CPython computes 0.8 * income (a plain float times a traced int), float(text), ", ".join(parts) and sorted([income, 20000.5]) in C, without consulting the traced value, so those results would lose their lineage. For code you execute from source, exec_source rewrites the syntax tree first (as pytest does for assert) and closes these gaps. Calls into code it cannot see into (third-party libraries, json.dump to a file) that consume traced values but return none are guarded, so editing their inputs requires re-execution rather than producing a stale value:
from redroot.instrument import exec_source
generated = """
def main(ext):
gross = float(ext["gross"].replace(",", ""))
return {"net": 0.8 * gross, "label": f"{gross:,.2f} USD"}
"""
namespace = exec_source(generated)
trace, _ = rr.run(namespace["main"], {"gross": "5,200.50"}, input_root="ext")
print(trace.explain("out:net")) # 0.8 * float(ext:gross.replace(',', ''))
A workflow written as a function in a module is instrumented from its source with redroot.instrument.instrumented: rr.run(instrumented(main), extracted, input_root="ext"), or @instrumented above its def to instrument it wherever it is called. The functions it calls are instrumented only if they are decorated too.
Instrumentation also records plain json.dumps(...) as one repeatable step, and turns x if cond else y with literal or variable branches ("Yes" if married else "Off", picking one of two rates) into a choice step, so a flipped condition updates outputs exactly instead of requiring re-execution.
Workflow code also parses dates, picks text apart with regular expressions and looks rates up in tables. In instrumented code these are steps that recalculate:
generated = r"""
import re
from datetime import datetime, timedelta
RATES = {"CA": 0.0725, "NY": 0.04, "TX": 0.0625}
def main(ext):
due = datetime.strptime(ext["due"], "%m/%d/%Y").date()
invoice = re.search(r"INV-(\d+)", ext["memo"])
return {
"tax": round(ext["amount"] * RATES[ext["state"]], 2),
"reminder": (due - timedelta(days=7)).isoformat(),
"invoice": int(invoice.group(1)) if invoice else 0,
}
"""
extracted = {"amount": 1200.0, "state": "CA", "due": "03/31/2025", "memo": "INV-1042 rent"}
invoices, _ = rr.run(exec_source(generated)["main"], extracted, input_root="ext")
print(invoices.explain("out:tax")) # round(ext:amount * RATES[ext:state], 2)
print(invoices.explain("out:invoice")) # int(re.search('INV-(\\d+)', ext:memo).group(1))
result = invoices.propagate({"ext:state": "NY", "ext:due": "04/15/2025", "ext:memo": "INV-2291"})
print(result.exact) # True
print(result.outputs["out:reminder"].new, result.outputs["out:invoice"].new) # 2025-04-08 2291
reason = invoices.propagate({"ext:memo": "paid in cash"}).reasons[0]
print(reason.message) # bool(re.search('INV-(\\d+)', ext:memo)) was True, now False
- Dates.
date,datetimeandtimedeltavalues are traced like numbers: arithmetic,.year,strftime(),isoformat()and comparisons. Instrumentation records parsing and construction (datetime.strptime,date.fromisoformat,date(year, 1, 1),timedelta(days=n)); date inputs are editable. - Regular expressions.
re.sub,re.split,re.findall,re.search/match/fullmatch/finditerand the methods of compiled patterns are steps, and so is reading a match (group(),span(),m[1]...). Whether a match was found is a guard: code branches on it. - Fixed tables. A lookup by a traced key,
RATES[state],RATES.get(state, 0)orstate in EXEMPT, is a step on a snapshot of the table, so an edited key finds its new row. This holds for dicts, lists, tuples, sets and strings of plain, immutable values (numbers, strings, dates, tuples of them), up to 10,000 items for lists, dicts and sets. Lookups into other containers keep guarding the key: a dict of lists that the code appends to, or a list of traced values (indexing one returns the traced value itself, with exact lineage).
Steps that read the machine's time zone or locale (datetime.fromtimestamp(t), strftime("%B")) are recalculated only where both are the same as in the run, and reported stale elsewhere.
Instrumented code behaves exactly like the original. exec_source executes the code it is given: only use it on code you would run anyway.
Saving, inspecting and viewing traces
data = trace.to_json() # versioned format; store it with the run
restored = rr.Trace.from_json(data)
# For large traces, write_json(file) writes the same text without holding it.
print(restored.propagate({"ext:gross": "6,000"}).outputs["out:net"].new) # 4800.0
redroot explain trace.json out:summary.net # expression and source inputs
redroot coverage trace.json # coverage report + re-evaluation check
redroot visualize trace.json # web viewer (needs redroot[web])
To re-evaluate a loaded trace, the modules defining its @traced functions must be imported, since they register those operations. A trace records a fingerprint of each one (a hash of its source, or @traced(version="...")). If the registered function differs from the one the run used, its results are reported stale (reason FUNCTION_CHANGED) instead of being recomputed with new code; trace.changed_functions() lists them up front.
Recalculating a trace runs the operations it names, so a tampered trace could ask for something huge (10 ** 10**9). Size limits are on by default; for traces from untrusted places add a budget, e.g. trace.propagate(edits, limits=rr.Limits(max_seconds=2)). Exceeding a limit raises rr.LimitExceeded. A regular expression's running time cannot be bounded in advance, so for traces whose patterns you do not trust also pass regex=False: steps that use one are then reported stale.
The viewer and to_graphviz() stay readable on large runs: inputs that differ only by list index are grouped (ext:deposits[*].amount · 11 inputs), and clicking an output shows its lineage up to other outputs, which you can open in turn (redroot.visualizer.graph_data(trace, focus=...)).
Measuring whether tracing covers your workload
Before relying on propagation, measure it on real runs:
from redroot.validation import check_identity, check_perturbation, coverage
# Linked and replayable outputs, guards, and the inputs that feed guards:
print(coverage(trace))
assert check_identity(trace).ok # every node re-evaluates to its recorded value
report = check_perturbation(guarded, {"A": 1200, "B": 300}, {"ext:A": 1100}, input_root="ext")
assert report.consistent # graph agrees with re-execution wherever it claimed to know
Booleans
Python does not allow subclassing bool, so by default comparisons return plain bools (recorded as guards) and boolean inputs are untracked. Pass bools=True to trace them too:
def form(ext):
eligible = ext["income"] > 30000
return {"eligible": eligible, "credit": 500 * eligible + 100 * ext["married"]}
trace, _ = rr.run(form, {"income": 25000, "married": True}, input_root="ext", bools=True)
print(trace.explain("out:eligible")) # ext:income > 30000
result = trace.propagate({"ext:income": 40000}) # the comparison flips...
print(result.exact, result.outputs["out:credit"].new) # True 600
A comparison then returns a TracedBool, which is data: a flag that is stored, counted or multiplied propagates exactly when it changes. A guard is recorded only where its truth value is used (if, while, and/or), and boolean inputs such as checkboxes become editable inputs.
A TracedBool is an int subclass that prints, formats, hashes and compares like True/False. In code you do not instrument, isinstance(x, bool) and x is True are false and json.dumps writes 1/0. Instrumented code gets all three right: external calls receive real bools. Use redroot.validation.check_fidelity(workflow, inputs, bools=True) to confirm that tracing leaves a workflow's outputs unchanged.
Pydantic
With redroot[pydantic], traced types work as model fields. Traced values pass through validation with their lineage, plain values become inputs, and models serialize to plain values.
How it works
Traced types subclass the builtins and override their operators. Each operation computes its result with the same function the graph later uses to re-evaluate it, so recomputation reproduces execution exactly. Results that leave tracking (a bool from a comparison, an int() conversion, a hash) are recorded as guards. Propagation re-checks guards, and any change means execution could have diverged. Details, guarantees and limits are in docs/design.md. For an end-to-end review workflow (record, review, edit, verify), see docs/integration.md.
Overhead is about 0.7 µs per traced operation (0.9 µs for Decimal) and about 240 bytes per recorded node (python benchmarks/overhead.py).
Limitations
int,float,Decimal,str,date,datetimeandtimedeltaare traced, andboolwithbools=True.Noneinputs (andboolinputs otherwise) are recorded as untracked: editing them requires re-execution.- Traced values are found inside lists, tuples, dicts, and
OrderedDict,defaultdictandCounter. A call on other container subclasses holding traced values is guarded, so editing those values requires re-execution. - Without instrumentation, a few C-level operations lose lineage (see above): instrument the workflow (
exec_source, orinstrumentedfor a function).redroot.validationfinds them. docs/design.md lists what remains invisible even with it. - Lineage does not cross threads unless the context is propagated (
contextvars.copy_context()), nor processes, norpickle. type(x) is floatisFalsefor traced values (instrumented code is unaffected).
Contributing
Contributions are welcome. See CONTRIBUTING.md, and AGENTS.md for the architecture's invariants.
License
MIT. See LICENSE.
Metadata
Release files for redroot 0.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| redroot-0.9.0.tar.gz | 179.8 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| redroot-0.9.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 298.6 kB
Release files / redroot-0.9.0.tar.gz
| Download URL | redroot-0.9.0.tar.gz |
|---|---|
| Size | 179.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
04a5d06dd1775ce7651fcd1cf51b1a9ecd15b71aaf1c2ba6fd8459b57e7a1145
|
|
BLAKE2b-256 checksum How to use checksums |
7251ae083f32019c9f4d2e4455e1cb80fefa9a0408718b614db044fa46649a85
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 9, 2026.
Transparency logRelease files / redroot-0.9.0-py3-none-any.whl
| Download URL | redroot-0.9.0-py3-none-any.whl |
|---|---|
| Size | 118.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
97c31fb6518af559396fec3675d6b0b4d4ee77eea3ca4945e7730ed26c26de1e
|
|
BLAKE2b-256 checksum How to use checksums |
c933dc856b7ccb8012b508e2d50ea4d7af15cb4c80458dc46e822a41b896a6af
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 9, 2026.
Transparency log