Working with states in YTsaurus Flow (Python)
Note
This page describes the Python API for working with states. For general state concepts, see the Stateful processing section.
YSON State
The simplest way to work with a state is using the YSON format. You store the state as a Python Map, which is automatically serialized to YSON:
state = ctx.state("state-name", message)
This returns a YsonStateAccessor with the following methods:
get()— get the current value (dictorNone).set(dict)— save the value.clear()— delete the state.get_or_default(dict)— get the current value or return the default value.
Example from WordCount:
class WordCountMapper(RowFunction):
"""Processes Word messages and maintains word count state."""
def on_message(self, message, output, ctx):
state = ctx.state("word-state", message)
data = state.get_or_default({"word": message.payload["word"], "count": 0})
data["count"] += 1
state.set(data)
Here, the state is tied to the message key, which is defined via group_by_schema in the spec. Each unique key has its own independent state.
Raw State
To store a state as raw bytes:
state = ctx.raw_state("state-name", message)
This returns a RawStateAccessor with the following methods:
get()— get the value (bytesorNone).set(bytes)— save the value.clear()— delete the state.get_or_default(bytes)— get the value or return the default value.
Proto State
To store a state as a Protobuf message:
state_accessor = ctx.proto_state("state-name", message, TJoinState)
This returns a ProtoStateAccessor with the following methods:
get()— deserialize and return the Protobuf object (orNone).set(proto_message)— serialize and save the value.clear()— delete the state.get_or_default(default=None)— get the value or return the default. If you don’t specify a default, it returns an empty instance of the Proto class.
External State
Row-format external state works like a Payload and gives you dict-like access to fields:
state = ctx.external_state("/state-name", message)
The state name must start with / and match the key in external_state_managers in the static spec. If you call ctx.external_state("state-name", message) without the leading /, it raises a ValueError.
This returns an ExternalStateAccessor, which is also a Payload:
state.get("field")— read a field.state["field"]— dict-like read of a field.state.to_builder()— get aPayloadBuilderwith the current values.state.set(payload)— save a new value (it accepts a Payload frombuilder.finish()).state.clear()— delete the state.
Example from Shuffle (EventReducer):
class EventReducer(RowFunction):
"""Counts events per key using external state."""
def on_message(self, message, output, ctx):
state = ctx.external_state("/shuffle-state", message)
builder = state.to_builder()
builder.set("count", (state.get("count") or 0) + 1)
state.set(builder.finish())
The pattern for working with an external state is:
- Get the current state using
ctx.external_state(...). - Create a builder with
state.to_builder(). - Update the required fields with
builder.set(...). - Save the changes with
state.set(builder.finish()).
For protobuf external state, use ctx.proto_external_state(name, message_or_timer, proto_class). Its get() returns an independent message snapshot or None; get_or_default() returns a snapshot or a fresh empty message without creating state. Save edits explicitly with set(value); clear() resets the state. This requires a protobuf-capable manager and a matching message class. Choosing this accessor does not change a row-format manager. See protobuf external state for prerequisites, availability, and errors.
For read-only joins, use ctx.joined_external_state(...) for rows or ctx.joined_proto_external_state(...) for protobuf. Both reject set() and clear() with ReadOnlyExternalStateError; declare the joiner in external_state_joiners.
State in timers
The API for working with a state in a timer handler is the same — you pass the timer object instead of message:
def on_timer(self, timer, output, ctx):
state = ctx.external_state("/join-state", timer)
# Read the state
show_time = state.get("show_time")
hit_payload = state.get("hit_payload")
# Clear the state after processing
state.clear()
Example from WaitClickJoin (JoinProcessFunction):
def on_timer(self, timer, output, ctx):
hit_id = timer.key["hit_id"]
log.debug("Process timer (KeyHitId: %s, Timer: %s)", hit_id, timer)
state = ctx.external_state("/join-state", timer)
log.debug("Process state (KeyHitId: %s, State: %s)", hit_id, state)
if timer.stream_id == "timer":
show_time = state.get("show_time")
hit_payload = state.get("hit_payload")
if show_time is not None and hit_payload is not None and show_time != 0:
log.debug("Click join: %s", state)
hit_time = timer.key["hit_time"]
click_time = state.get("click_time")
builder = ctx.message_builder("joined_action")
builder.set("hit_id", hit_id)
builder.set("hit_time", hit_time)
builder.set("show_time", show_time)
builder.set("hit_payload", hit_payload)
if click_time is not None and click_time != 0:
builder.set("is_click", True)
builder.set("click_time", click_time)
else:
builder.set("is_click", False)
builder.set("click_time", 0)
output.add_message(builder.finish())
state.clear()
else:
raise ValueError(f"Unknown streamId: {timer.stream_id}")
Binding a state to a key
In TTransformCompanionComputation, state binds to the message key defined by group_by_schema in the computation spec. Messages with the same key share one state.
TTransformOrderedSourceCompanionComputation does not support group_by_schema. Its internal state uses the source partition key, so messages from one partition share that state. See Computation (Python) for choosing a SourceComputation class, and Stateful processing for key configuration.
Configuring states in the spec
Internal states (YSON, Raw, Proto) must be declared in the computation parameters in the internal_states section. The state name in your code (the first argument of ctx.state(...)) must match the name declared in the spec.
External states are configured via external_state_managers in the computation spec, or external_state_joiners for read-only joins. The key (for example, "/shuffle-state") sets the state name and must start with /. For row-format state, use "NYT::NFlow::TSimpleExternalStateManager" as external_state_manager_class_name; its schema describes the available columns. Protobuf external state requires a compatible implementation and protobuf descriptor. See row-format configuration, protobuf prerequisites, and the C++ documentation.