pysxLearn by building

Runtime and resilience · Lesson 23 of 28

Explicit durable state

Declare a typed state root, validate its codec and rebuild it through a real store.

Explicit durable UI state names the data that can cross a reconstruction boundary. A codec converts that typed root to bounded JSON and validates JSON on the way back. It must not serialize handlers, effects or arbitrary Python objects.

A store retains versioned snapshots and ownership information. New graphs rebuild callbacks and resources from application code. A schema change needs a declared migration or an explicit unavailable/reset policy.

Understand the moving parts

The durable playground is a real DurableApplication with a SQLite ownership store. Edit its declared draft, increment and keep the document open through a server restart. The setup marker changes while the committed root is reconstructed.

Its codec accepts bounded JSON data, not Python source. Persisting a UI draft still does not make an external payment or account write exactly-once; those operations need the application's own transactional design.

Walk through the code

from __future__ import annotations

from dataclasses import dataclass, replace
from pathlib import Path
from typing import TYPE_CHECKING
from uuid import uuid4

from pysx import (
    DurableApplication,
    Fragment,
    HostConfig,
    Signal,
    SQLiteOwnershipStore,
    StateCodec,
    derived,
    project,
    pysx,
)

if TYPE_CHECKING:
    from pysx.runtime.wire import JSONValue

STORE = Path(__file__).parent / ".state" / "durable" / "store.sqlite3"


@dataclass(frozen=True)
class State:
    count: int = 0
    draft: str = "My saved draft"


def encode(state: State) -> JSONValue:
    return {"count": state.count, "draft": state.draft}


def decode(value: JSONValue) -> State:
    if not isinstance(value, dict):
        raise ValueError("expected state object")
    count, draft = value.get("count"), value.get("draft")

    if type(count) is not int or not isinstance(draft, str) or len(draft) > 512:
        raise ValueError("invalid counter or draft")

    return State(count, draft)


def view(state: Signal[State]) -> Fragment:
    setup = uuid4().hex[:12]
    count = derived(lambda: state().count)
    draft = project(
        state, lambda value: value.draft, lambda value, text: replace(value, draft=text[:512])
    )

    def increment(_event: object) -> None:
        value = state()
        state.set(replace(value, count=value.count + 1))

    return pysx(t"""
        main:
            h1: "Durable declared state"
            p: "Only declared state is persisted. Handlers and resources are rebuilt."
            label(htmlFor="draft"): "Saved draft"
            input(id="draft" bindValue={draft})
            p:
                "Counter: "
                span(id="count"): {count}
            button(id="increment" type="button" onClick={increment}): "Increment"
            p:
                "Setup marker: "
                span(id="setup"): {setup}
            h2: "Try it"
            ol:
                li: "Edit the draft and increment the counter."
                li: "Stop the server with Ctrl+C, leaving this tab open."
                li: "Start the same command again. The draft and counter reconstruct."
                li: "The setup marker changes, because the application graph is new."
            p: "This local demonstration identity is not production authentication."
    """)


STORE.parent.mkdir(parents=True, exist_ok=True)

app = DurableApplication(
    view,
    initial=State,
    codec=StateCodec[State](encode, decode),
    store=SQLiteOwnershipStore(STORE),
    application="playground-durable",
    config=HostConfig(principal=lambda _request: "local-playground"),
)

State declares the two saved fields: draft and count. Its StateCodec encodes and validates those fields, and SQLiteOwnershipStore retains them at STORE. project writes draft edits back into the state root; increment replaces that root with an updated count. The setup marker is created inside view, outside the declared root, so reconstruction creates a new marker without replacing the saved data.

Try it locally

Use Python 3.14 or newer. In your project's activated virtual environment, run:

pip install pysx-framework
pysx-playground durable
pysx --app playgrounds.durable

Open the local URL printed in the terminal. Keep that terminal open while you try the playground.

Scaffold once. To restart, repeat only the pysx --app command; scaffolding again resets the playground's saved state.

What you'll do

  1. Edit the draft and increment the counter. Wait for the counter to update.
  2. Stop the server with Ctrl+C, leaving this tab open.
  3. Start the same run command again, using the same project directory.
  4. Compare the restored draft and counter with the setup marker.

What you'll see

The draft and counter reconstruct from the declared state. The setup marker changes because the application graph is new. No separate Save action is needed in this playground; delivered edits update the declared root.

Take this with you

Declare data and schema explicitly; rebuild behavior from trusted code.