Metadata-Version: 2.4
Name: lg-flink-state-saver
Version: 0.2.0
Summary: LangGraph and LangChain agent checkpoints backed by Flink managed keyed state
Project-URL: Homepage, https://github.com/Sud0x67/lg-flink-state-saver
Project-URL: Repository, https://github.com/Sud0x67/lg-flink-state-saver
Project-URL: Issues, https://github.com/Sud0x67/lg-flink-state-saver/issues
License-Expression: MIT
License-File: LICENSE
Keywords: agent,checkpoint,flink,langchain,langgraph,pyflink
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: langgraph-checkpoint<5,>=4.3.2
Requires-Dist: langgraph<2,>=1.2.25
Provides-Extra: agent
Requires-Dist: langchain-openai<2,>=1.8.5; extra == 'agent'
Requires-Dist: langchain<2,>=1.5.2; extra == 'agent'
Requires-Dist: pydantic<3,>=2.7.4; extra == 'agent'
Requires-Dist: python-dotenv<2,>=1.2; extra == 'agent'
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy<2,>=1.15; extra == 'dev'
Requires-Dist: pydantic<3,>=2.7.4; extra == 'dev'
Requires-Dist: pytest<10,>=8; extra == 'dev'
Requires-Dist: ruff<1,>=0.14; extra == 'dev'
Requires-Dist: twine<7,>=6; extra == 'dev'
Provides-Extra: flink
Requires-Dist: apache-flink<2.3,>=2.2.1; extra == 'flink'
Description-Content-Type: text/markdown

# lg-flink-state-saver

English | [简体中文](https://github.com/Sud0x67/lg-flink-state-saver/blob/main/README.md)

Run LangGraph graphs and LangChain agents inside PyFlink operators, with their
checkpoints stored in **Flink managed keyed state**. No separate checkpoint database
is required. Agent state is restored with Flink checkpoints and savepoints, and
redistributed when the job is rescaled.

The package provides two entry points:

- `LangGraphProcessFunction`: wrap a graph or agent as a PyFlink operator.
- `FlinkStateSaver`: add LangGraph checkpointing to an existing keyed operator.


## Quick start

The local examples require Python 3.11 and Java. The tested combination is Java 21,
PyFlink 2.2.1, LangGraph 1.2.25, langgraph-checkpoint 4.3.2, and LangChain 1.5.2.

```bash
git clone https://github.com/Sud0x67/lg-flink-state-saver.git
cd lg-flink-state-saver
python3.11 -m venv .venv
source .venv/bin/activate
pip install -e '.[flink,agent,dev]'
```

Alternatively, use uv:

```bash
uv sync --locked --python 3.11 --extra flink --extra agent --extra dev
```

The repository includes `uv.lock` to reproduce dependencies for the examples and
development environment. `--locked` checks that it matches `pyproject.toml`.
When installing this package with pip, dependency ranges come from `pyproject.toml`.

With uv, prefix the commands below with `uv run`, for example `uv run python` or
`uv run pytest`.

An example that needs no model or API key:

```bash
python examples/graph_job.py
```

Its output includes `alice:1`, `bob:10`, and `alice:3`, demonstrating isolation
between keys and accumulation across records for the same key.

## Pause and resume execution

The [resume example](https://github.com/Sud0x67/lg-flink-state-saver/blob/main/examples/resume_job.py) demonstrates an approval workflow
without a model or API key:

```bash
python examples/resume_job.py
```

Alice and Bob submit amounts of 120 and 80. The graph saves its state at
`interrupt()` and returns an approval request, leaving the operator free to process
later events. Bob's rejection and Alice's approval resume their respective graphs
through `Command(resume=False)` and `Command(resume=True)`:

```json
{"session_id": "alice", "status": "pending", "request": {"question": "Approve this amount?", "amount": 120}}
{"session_id": "bob", "status": "pending", "request": {"question": "Approve this amount?", "amount": 80}}
{"session_id": "bob", "status": "rejected", "amount": 80}
{"session_id": "alice", "status": "approved", "amount": 120}
```

The `input_mapper` turns a `submit` event into initial state and a `resume` event
into a `Command`. A resume event must use the original request's `session_id`,
which `key_by()` maps to the same `thread_id`. Default latest retention preserves
the state needed to resume interrupted tasks.

The example simulates approval events with an in-memory source. Production jobs
can receive human decisions from Kafka or another source. On resume, the paused
node runs again from its beginning, and `interrupt()` returns the resume value;
avoid non-repeatable side effects before it. This example demonstrates pausing
and resuming a business workflow. Recovery after a Flink failure still requires
persistent checkpoints and recoverable sources and sinks.

## Connect a real model

The [agent example](https://github.com/Sud0x67/lg-flink-state-saver/blob/main/examples/agent_job.py) uses a real model with tool calling to
look up local shipping rates and remember the user's city. The complete job is:
in-memory source → key by session → agent operator → print sink.

Copy the configuration template on first use. If `.env` already exists, edit it
instead of overwriting it:

```bash
cp -n .env.example .env
```

Configure `.env` in the project root:

```dotenv
OPENAI_API_KEY=your-api-key
OPENAI_MODEL=your-model-name
# Set this for an OpenAI-compatible service; omit it for the official service.
# OPENAI_BASE_URL=https://your-endpoint/v1
```

```bash
python examples/agent_job.py
```

The example loads `.env` from the project root regardless of the working directory.
Existing environment variables take precedence.

Alice and Bob send interleaved messages. The output has this form; the wording
depends on the model. The example prompts and responses are in Chinese:

```json
{"session_id": "alice", "answer": "杭州运费为8元。"}
{"session_id": "bob", "answer": "上海运费为12元。"}
{"session_id": "alice", "answer": "您刚才说住在杭州。"}
```

The last response recalls that Alice lives in Hangzhou. Shipping rates come from a
local demo table; the model chooses the tool and generates the responses.

## Use an agent as an operator

Given a `records` stream whose records contain `session_id` and `text`:

```python
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from pyflink.common import Types

from lg_flink_state_saver import LangGraphProcessFunction


def build_agent(saver):
    return create_agent(
        ChatOpenAI(model="your-model"),
        tools=[],
        checkpointer=saver,
    )


result = (
    records.key_by(lambda r: r["session_id"], key_type=Types.STRING())
    .process(
        LangGraphProcessFunction(
            build_agent,
            input_mapper=lambda r: {"messages": [{"role": "user", "content": r["text"]}]},
            output_mapper=lambda r, s: s["messages"][-1].content,
        ),
        output_type=Types.STRING(),
    )
    .uid("my-agent-v1")
)
```

`build_agent(saver)` runs once in each worker's `open()` method. Create model clients
there and pass the supplied saver to `create_agent(checkpointer=...)` or
`builder.compile(checkpointer=...)`. Factories and mappers must be serializable.

Both mappers are optional. Without them, the operator passes each record directly
to the graph and emits the complete graph result. Set `output_type` to match the
actual output. Flink keys must be non-empty strings; each key maps to one LangGraph
`thread_id`.

## Integrate with an existing operator

Use the saver in the lifecycle of a custom `KeyedProcessFunction`:

```python
from lg_flink_state_saver import FlinkStateSaver

# open(runtime_context)
self.saver = FlinkStateSaver.from_runtime_context(runtime_context)
self.graph = builder.compile(checkpointer=self.saver)

# process_element(value, ctx)
result = self.saver.invoke(self.graph, graph_input, thread_id=ctx.get_current_key())

# close()
self.saver.close()
```

`invoke()` binds the current key and uses `durability="sync"`, so persistence writes
finish before it returns. Pass metadata, recursion limits, or checkpoint namespaces
through `config=`. An explicit checkpoint ID must identify that namespace's latest checkpoint.

To inspect retained checkpoints or use other graph methods, call
`saver.bind(thread_id)` first, then execute the operation inside `saver.run(lambda: ...)`.
Consume iterators such as `graph.stream()` and `saver.list()` fully inside that
callback. Wait for any child tasks before the callback returns.

Supported features include incremental channel blobs, idempotent pending writes,
parallel nodes, subgraph namespaces, and interrupt/resume.
The default `JsonPlusSerializer` restricts deserialization of custom types. Supply
a suitable serializer through `serde=` for custom types or encryption.

## Latest recoverable state by default

`LangGraphProcessFunction` and `saver.invoke()` use latest retention automatically:

1. Execute the graph with synchronous persistence.
2. After a successful return, call `prune(strategy="keep_latest")` on the operator thread.
3. Retain the latest checkpoint and required blobs, pending writes, and indexes;
   collect unreferenced data.

Ordinary v4 checkpoints retain one latest record per live namespace. Completed
transient subgraph namespaces are collected with their calling history, while
`checkpointer=True` subgraphs keep their current state. Interrupted subgraphs remain
resumable. `DeltaChannel` retains the ancestor chain and writes needed to replay
from the nearest snapshot, so latest does not mean exactly one stored row.
Legacy checkpoints may also need their direct parent. Imported subgraphs with
unknown ownership are retained conservatively; unknown cross-language delta layouts
retain their entire dependency chain.

If execution raises, automatic pruning is skipped so successful nodes' pending
writes remain available for retry. Pruning validates live blob and write references
before deletion. Backend failures propagate to the caller for Flink recovery.
Deleted checkpoints are unavailable for time travel or forks; `list()` exposes only
retained recovery records.

Low-level `put()` / `run()` operations do not trigger pruning. Custom integrations
call it explicitly on the operator thread for the current key, after graph work
has completely finished. Call `prune()` outside `run()`:

```python
saver.prune([thread_id], strategy="keep_latest")
# When the application explicitly ends the entire session:
saver.prune([thread_id], strategy="delete")
```

A saver can prune only its currently bound Flink key, not other keys in a batch.
Pruning scans that key's state entries; allow for the initial cost when migrating
a key with a large existing history. Latest retention bounds historical versions,
not the size of the current message list. Trim or summarize messages separately.
Cleanup affects current managed state; existing Flink checkpoints and savepoints
remain subject to their own snapshot retention policies.

## Pydantic 2 and type checking

The agent example uses Pydantic 2 `ConfigDict` and `StringConstraints` to validate
tool arguments. City names are trimmed and must be non-empty strings. Numbers and
extra fields are rejected.

By default, the serializer restores an untrusted custom `BaseModel` as a dictionary.
To preserve the model type in checkpoints, explicitly allow that class and use the
same serializer configuration after recovery:

```python
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
from my_app.models import Profile

serde = JsonPlusSerializer(allowed_msgpack_modules=[(Profile.__module__, Profile.__name__)])
saver = FlinkStateSaver.from_runtime_context(runtime_context, serde=serde)
```

Validate data with `Profile.model_validate(...)` before it enters the graph and
export it with `model_dump()`. Checkpoint reconstruction does not replace input
validation. Allow only trusted model classes that workers can import.

Public APIs are annotated and the wheel includes `py.typed`. Ruff checks naming,
imports, annotations, and PEP 257 docstrings; Mypy checks package code. Untyped
external APIs and arbitrary graph inputs, outputs, and channel values remain dynamic.

## Recovery and limitations

- Use the saver after `key_by()`. Each instance belongs to one operator worker and
  cannot process multiple inputs concurrently. The graph runs on a worker thread;
  the operator thread performs Flink state access. Only synchronous APIs are supported.
- Production jobs need persistent checkpoint storage, a restart strategy, and
  recoverable sources and sinks. Keep operator UIDs, key rules, `state_prefix`,
  and max parallelism compatible when restoring.
- Model calls and tool side effects are outside Flink transactions. Recovery may
  repeat them. Tools that write to external systems must provide their own idempotency.
- `invoke()` prunes old history automatically; native Flink TTL remains disabled.
  Applications decide when a session expires and call `saver.clear_key()` on the
  operator thread for the current key to remove all saver state.
- Do not configure TTL on individual MapState entries: new checkpoints can still
  reference older blobs. Implement whole-key expiration in a custom operator timer.
- Examples use bounded sources and exit after running in a MiniCluster. The print
  sink is not transactional. A short job can finish before its first checkpoint,
  so these examples alone do not demonstrate failure recovery.
- State names use `lg-flink-v1-*` and are not directly compatible with the original
  examples' `langgraph-*-v2` layout. Plan a separate migration before replacing an
  existing job.

## Installation options and publishing

Install from PyPI:

```bash
pip install 'lg-flink-state-saver[flink,agent]'
```

The base package includes LangGraph and the saver. The `flink` extra adds PyFlink;
`agent` adds LangChain, langchain-openai, and python-dotenv; `dev` adds testing and
packaging tools. Omit `flink` if a compatible PyFlink installation is already
available. Importing the base saver does not start a JVM.

```bash
pytest -m 'not integration'
pytest -m integration  # Requires PyFlink and Java; starts a JVM, with no external model calls.
ruff check .
ruff format --check .
mypy
python -m build
python -m twine check --strict dist/*
```

References: [LangGraph checkpoint API](https://reference.langchain.com/python/langgraph/checkpoints),
[PyFlink keyed MapState](https://nightlies.apache.org/flink/flink-docs-release-2.2/api/python/reference/pyflink.datastream/api/pyflink.datastream.functions.RuntimeContext.get_map_state.html).
