Metadata-Version: 2.5
Name: redroot
Version: 0.10.0
Summary: Value-level lineage for Python: trace where every output came from, and propagate input edits to every output without re-running
Project-URL: Homepage, https://github.com/gagan-gaurav/redthread
Project-URL: Documentation, https://github.com/gagan-gaurav/redthread#readme
Project-URL: Repository, https://github.com/gagan-gaurav/redthread
Project-URL: Issues, https://github.com/gagan-gaurav/redthread/issues
Project-URL: Changelog, https://github.com/gagan-gaurav/redthread/blob/main/CHANGELOG.md
Author: Gagan Gaurav
License-Expression: MIT
License-File: LICENSE
Keywords: audit,dag,data-engineering,data-provenance,incremental-computation,lineage,llm,provenance,pydantic,tracing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: all
Requires-Dist: flask>=3.0; extra == 'all'
Requires-Dist: graphviz>=0.20; extra == 'all'
Requires-Dist: networkx>=3.0; extra == 'all'
Requires-Dist: pydantic>=2.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: hypothesis>=6.100; extra == 'dev'
Requires-Dist: mypy==2.3.1; extra == 'dev'
Requires-Dist: pre-commit>=3.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff==0.16.10; extra == 'dev'
Provides-Extra: pydantic
Requires-Dist: pydantic>=2.0; extra == 'pydantic'
Provides-Extra: viz
Requires-Dist: graphviz>=0.20; extra == 'viz'
Requires-Dist: networkx>=3.0; extra == 'viz'
Provides-Extra: web
Requires-Dist: flask>=3.0; extra == 'web'
Description-Content-Type: text/markdown

<div align="center">

# <img width="128" height="128" alt="RedRoot logo" src="https://github.com/user-attachments/assets/82d895e5-a7ba-447e-a3dc-dfeb36c4c1dd" /> RedRoot
### Trace Every Value to Its Roots

[![CI](https://github.com/gagan-gaurav/redthread/actions/workflows/ci.yml/badge.svg)](https://github.com/gagan-gaurav/redthread/actions/workflows/ci.yml)
[![PyPI Version](https://img.shields.io/pypi/v/redroot?color=red)](https://pypi.org/project/redroot/)
[![Python Versions](https://img.shields.io/pypi/pyversions/redroot)](https://pypi.org/project/redroot/)
[![License](https://img.shields.io/pypi/l/redroot)](https://opensource.org/licenses/MIT)

**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?** &nbsp;·&nbsp; **What does every output become if this input changes?**

</div>

---

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.

```python
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`, `TracedStr` and the date types `TracedDate`, `TracedDatetime` and `TracedTimedelta` are 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 `stale` rather 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.instrument` closes 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.** `@traced` turns a function (a tax-table lookup, a geocoder) into one re-callable node. `@traced_llm` marks 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

```bash
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.

```python
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:

```python
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(...)` |

### Keeping lineage only

If you only ask where outputs came from, and never propagate edits or save the trace, pass `keep="lineage"` to `rr.run` or `rr.Trace`. The trace then keeps the inputs and the steps that outputs, or values the program still holds, were computed from. Everything else is freed as soon as the program drops it: the comparisons of a matching loop, truth tests, intermediates nobody kept.

```python
def match(ext):
    total = 0
    for row in ext["rows"]:
        if row["ref"] == ext["ref"]:  # a decision per row; none is an output
            total = total + row["amount"]
    return {"total": total}


rows = [{"ref": "R1", "amount": 5}, {"ref": "R2", "amount": 7}]
trace, _ = rr.run(match, {"ref": "R2", "rows": rows}, input_root="ext", keep="lineage")
print([n.key for n in trace.sources("out:total")])  # ['ext:rows[1].amount']
print(sorted(trace.guard_inputs))  # ['ext:ref', 'ext:rows[0].ref', 'ext:rows[1].ref']
print(trace.recorded)  # 8
```

`sources`, `explain`, `ancestors`, `node`, `inputs` and `outputs` answer exactly as with the default `keep="all"`. The guards themselves are not kept: `guard_inputs` lists the inputs any decision depended on. What needs every step raises `rr.LineageOnlyError`: `nodes`, `guards`, `descendants`, `dependents`, `propagate`, saving and validation. On a matching loop of 815,000 steps, few of which reach an output, peak memory goes from 273 MB to 28 MB.

### 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:

```python
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](docs/design.md#why-a-flipped-guard-makes-every-output-stale).

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:

```python
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.

```python
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.

```python
@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:

```python
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:

```python
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`, `datetime` and `timedelta` values 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`/`finditer` and 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)` or `state 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

```python
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
```

```bash
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:

```python
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 `bool`s (recorded as guards) and boolean inputs are untracked. Pass `bools=True` to trace them too:

```python
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 `bool`s. 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](docs/design.md). For an end-to-end review workflow (record, review, edit, verify), see [docs/integration.md](docs/integration.md).

Overhead is about 0.7 µs per traced operation (0.9 µs for `Decimal`) and about 245 bytes per recorded node (`python benchmarks/overhead.py`).

## Limitations

- `int`, `float`, `Decimal`, `str`, `date`, `datetime` and `timedelta` are traced, and `bool` with `bools=True`. `None` inputs (and `bool` inputs otherwise) are recorded as untracked: editing them requires re-execution.
- Traced values are found inside lists, tuples, dicts, and `OrderedDict`, `defaultdict` and `Counter`. 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`, or `instrumented` for a function). `redroot.validation` finds them. [docs/design.md](docs/design.md#what-remains-invisible) lists what remains invisible even with it.
- Lineage does not cross threads unless the context is propagated (`contextvars.copy_context()`), nor processes, nor `pickle`.
- `type(x) is float` is `False` for traced values (instrumented code is unaffected).

## Contributing

Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md), and [AGENTS.md](AGENTS.md) for the architecture's invariants.

## License

MIT. See [LICENSE](LICENSE).
