Metadata-Version: 2.5
Name: redroot
Version: 0.3.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` and `TracedStr` are real `int`/`float`/`Decimal`/`str` instances. 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.
- **Re-execution as the arbiter.** Built-in tools compare the graph's answers with a real re-run, and measure coverage on your workloads.
- **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.

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

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

### 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 (`date.fromisoformat`, `json.dumps`, third-party libraries) 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(',', ''))
```

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)
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.

### 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 240 bytes per recorded node (`python benchmarks/overhead.py`).

## Limitations

- `int`, `float`, `Decimal` and `str` are traced, and `bool` with `bools=True`. `None` inputs (and `bool` inputs otherwise) are recorded as untracked: editing them requires re-execution.
- Without instrumentation, a few C-level operations lose lineage (see above). `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).
