Skip to main content

evaleval

Security: see SECURITY.md for the threat model, the dual-eval design, and why raw Eval/Text/f-string JS are footguns.

Browser DOM is modified ONLY through javascript code snippets sent over the wire to the browers eval function.

Backend actions execute ONLY through python code snippets sent over the wire to python's eval function.

import { Idiomorph } from 'idiomorph';
window.Idiomorph = Idiomorph;

const es = new EventSource('/sse');
es.addEventListener('exec', e => eval(e.data));

document.addEventListener('submit', async e => {
  e.preventDefault();
  const r = await fetch(e.target.action, { method: 'POST', body: new FormData(e.target) });
  const t = await r.text();
  if (r.ok && t) eval(t);
});
from evaleval import SnippetExecutionError

@app.post("/")
async def do(request):
    form = await request.form()
    try:
        # Form values are bound as locals — never spliced into source.
        return signer.verify_snippet(form).eval(globals())

    except SnippetExecutionError as e:
        return PlainTextResponse(e.message, status_code=e.status_code)

Example: evaleval-todo

evaleval also includes a quick implementation of clojure's hiccup, a data-driven embedded DSL for rendering DOM nodes in an ergonomic way.

Observe this example:

from evaleval import Signer
from evaleval.depth import Three, Two
from evaleval.patch import Selector, MORPH, APPEND, REMOVE

signer = Signer()

def add_form():
    return ["form", {"action": "/", "method": "post"},
        *signer.snippet_hidden("add($new-todo-body)"),
        ["input", {"type": "text", "name": "new-todo-body", "placeholder": "what needs doing?"}],
        ["button", {"type": "submit"}, "add"],
    ]

All forms have a handler. In a traditional stack, it would be pointed to by a url which points to a routing table which points to a handler function. In evaleval, the handler is embedded into the form itself.

The signed template add($new-todo-body) is verified, then $new-todo-body is bound as a Python local (not spliced into source via repr). That avoids classic nested-$ breakouts: form data never becomes code. The expression is evaluated and — as you'll see later — the result is returned directly to the client.

So the handler function from the form is called directly with form arguments. And it returns javscript code. Now how do you write js snippets ergonomically in python? You could write them directly:

def add(text):
    t = {"id": uuid.uuid4().hex[:8], "text": text, "done": False}
    TODOS.append(t)
    escaped = t["text"].replace("`", "\\`")
    return PlainTextResponse(f"""
Idiomorph.morph(document.querySelector('#add-form'), `<form id="add-form">...</form>`);
document.querySelector('#todo-list').insertAdjacentHTML('beforeend', `<li id="todo-{t["id"]}">{escaped}</li>`);
Idiomorph.morph(document.querySelector('p.count'), `<p class="count">...</p>`);
console.log('todo added', {text!r});
""")

Ew.

However, I have instead built an embedded data-driven DSL much like specter, which lets you construct js snippets in fluent python. The number we are indexing into is the arity of how deep we can index into until it executes the path, rendering it into a js string. The details of this process are fairly simple and are described here. The indexable arity objects are also just very cool.

The most common arity path pattern is Three[dom selector][action][hiccup data].

def add(text):
    t = {"id": uuid.uuid4().hex[:8], "text": text, "done": False}
    TODOS.append(t)
    return PlainTextResponse(";".join([
        Three[Selector("#add-form")][MORPH][add_form()],
        Three[Selector("#todo-list")][APPEND][todo_item(t)],
        Three[Selector("p.count")][MORPH][remaining_count()],
        # Never do this: f"console.log('todo added', {text})"
        # `text` is attacker-controlled and an f-string into JS is XSS.
        # Strings go through Str()/hiccup, which json.dumps / escape.
    ]))

def delete(todo_id):
    TODOS.remove(_find(todo_id))
    # Selector.id validates [A-Za-z0-9_-]+; an attacker todo_id like
    # `*` or `a, #add-form` fails closed instead of widening the selector.
    return PlainTextResponse(";".join([
        Two[Selector.id(f"todo-{todo_id}")][REMOVE],
        Three[Selector("p.count")][MORPH][remaining_count()],
    ]))

These js snippets go directly into the browser's eval function, so the only thing standing between user text and XSS is the escaping in hiccup + js_ir.Str — never build JS with f-strings.

# Safe: `width` is coerced to int first, so it cannot contain a quote.
width = int(width)
Two[Selector("#progress-bar")][EvalOn(f"=> $.style.width = '{width}%'")]

Security

Full discussion: SECURITY.md. This is the short version.

Verify snippet consumes the nonce, so for each GET you can only press each button once. Verify snippet checks the HMAC against the provided snippet, restricting code running on the server to be only code that the server itself produces. So if a user can't do an action, don't sign a snippet with that action for them.

$placeholders are rewritten to synthetic locals (__ee_arg_N__); form values are passed through eval's locals mapping. Values are data, never source — a value containing $x cannot trigger further substitution or break out of a string literal.

Notice this line in the todo submit form handler:

Three[Selector("#add-form")][MORPH][add_form()],

This is neceseary. Because each action is only allowed exactly once per GET. But you don't want to have to reGET the page to send another todo. So a new nonce is required to be generated by add_form(), which returns hiccup, which is rendered to an htmlstring, which is morphed into the dom at #add-form.

Each snippet is not only a continuation, but also a capability ticket.

uv install evaleval

Durable state

evaleval also includes a Python-native path/reified-operation layer over rocksdict — the same paths as data idea as the Rust durable crate, idiomatic in Python. The Python layer mirrors the Rust crate at 0.3.0 (the v0.2.0-to-0.3.0 update adds the reified push_op/push_back_op/push_front_op constructors, the public codec module with self-describing tag helpers, Write::ranges() watch information, and a pluggable storage-backend trait; the on-disk key/value layout and the SyncWal/WalOnly/DisableWal durability set are unchanged). The Rust crate has no Python bindings, so evaleval is the Python surface for the crate's paths-as-data projection layer; it intentionally does not mirror the crate's newer event-sourced Runtime/Query/dynpath layers above that projection.

Paths both select and transform. Selectors read only the addressed key/prefix; transformations return plain-data operations applied atomically.

from evaleval import (
    Record, Map, Leaf, Sum, List, Deque, Durability, RocksDb,
)

Store = Record(
    nodes=Map(Leaf()),
    scores=Map(Sum()),
    log=List(Leaf()),
)

db = RocksDb.open("scores.rocks")
root = Store.root()

db.apply([
    root.scores.key("alice").add(10),   # reified Add (RMW under single-writer lock)
    root.scores.key("alice").add(5),
    root.nodes.key("alice").set("Alice"),
], Durability.SYNC_WAL)

assert root.scores.key("alice").get(db) == 15
assert root.nodes.key("alice").get(db) == "Alice"
assert "alice" in root.nodes.keys(db)

Schema markers

Type Meaning Selectors Transforms
Leaf() one CBOR value get set, delete
Map(V) CBOR keys → sub-schema key, keys, entries, iter, paginated variants, len, contains clear, leaf/sum set/delete/add, transform_values
List(V) index-addressed sequence at, get, iter, len push, pop, clear
Deque(V) double-ended queue front, back, iter, len push_back/front, pop_front/back, clear
Sum() numeric accumulator get (0 if absent) add, set, delete
Record(...) named fields (stable declaration-order ids) field navigation clear

Nest freely. Record field ids come from declaration order — add new fields at the end; reordering changes the layout.

Name notes vs the Rust crate: the reified Add op is Rust's Op::Merge (exported here as both Add and Merge). The reified collection pushes are push/push_back/push_front here but push_op/push_back_op/ push_front_op in Rust (where push commits immediately); the Rust *_op names are provided as aliases. Record here is a schema (like a Rust #[derive(Durable)] struct), not the crate's runtime::Record event envelope.

Cost model

  • Blind (no read at construction): Leaf.set/delete, Sum.add/set/delete, collection clear. Ops are plain data (Put / Delete / DeletePrefix / Add).
  • Read-modify-write: list/deque push and pop. Operations are interpreted in exact sequence against an in-batch view, then committed in one atomic write. (The Rust crate instead resolves batches in three phases — point writes, prefix deletes, then collection appends — so a DeletePrefix always wins over same-batch point writes. evaleval keeps sequential semantics: later writes win. See state.py.)
  • Scan: Map.keys / iter / len / contains / transform_values.

For large maps, use bounded selectors rather than materializing the map:

page = root.nodes.iter_page(db, limit=100)
while True:
    for key, value in page.items:
        process(key, value)
    if page.cursor is None:
        break
    page = root.nodes.iter_page(db, cursor=page.cursor, limit=100)

keys_page, entries_page, and iter_page return Page(items, cursor) in encoded-key order. The cursor is opaque. Backends also expose scan_prefix(prefix, start=..., limit=...); its raw-key start is inclusive.

rocksdict has no custom merge operators, so Add is interpreted as read-modify-write under the same single-writer lock and atomic batch. The reified Add API is preserved so a native-merge backend can be swapped later.

Durability

Every batch commits with an explicit policy:

  • Durability.SYNC_WAL — WAL + fsync (survives power loss)
  • Durability.WAL_ONLY — WAL without forced fsync
  • Durability.DISABLE_WAL — skip WAL (rebuildable projections only)

Single-writer

Not multi-process safe. One writer process; serialize writes at the application layer. The rocksdict backend holds a process-local lock so concurrent threads in the same process do not interleave batches.

Metadata

Release files for evaleval 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for evaleval 0.5.0
File Size Uploaded Provenance Actions
evaleval-0.5.0.tar.gz 83.7 kB With provenance Details for evaleval-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for evaleval 0.5.0
File Interpreter ABI Platform Actions
evaleval-0.5.0-py3-none-any.whl Python 3 none any Details for evaleval-0.5.0-py3-none-any.whl

Total release size: 117.2 kB

Release files / evaleval-0.5.0.tar.gz

Download URL evaleval-0.5.0.tar.gz
Size 83.7 kB
Tags Source
SHA-256 checksum
How to use checksums
17a018393729b93fc17df55a4f591ba7cb0164e5e7a2149b2d20b6d3baa7caf9
BLAKE2b-256 checksum
How to use checksums
7ae1d621782acc16374f3791f9c300a33fdc129c4131bb8beab0221679c99628
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 7, 2026.

Transparency log

Release files / evaleval-0.5.0-py3-none-any.whl

Download URL evaleval-0.5.0-py3-none-any.whl
Size 33.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
45d411ffa3f5f8326da01102e8c7e5013ce43c9c4986349b28703f12d36d321f
BLAKE2b-256 checksum
How to use checksums
875fdd76c0eb55ce3dd54a14fff518afb1e6e90a50a480f6a53cda1aed1afa0f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 7, 2026.

Transparency log

Security for evaleval 0.5.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for evaleval-0.5.0.tar.gz

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 Nov 7, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page