Working with states in YTsaurus Flow (C++)
Note
This page describes the specifics of working with states in C++. For a language-agnostic description of the concept, see the Stateful processing section.
All user-logic examples on this page use process functions. Don’t create a custom Computation subclass to work with state.
Internal State
This is the simplest way to store a state inside a Computation. Data is automatically loaded at the start of the epoch and written on commit. You don’t need to create tables yourself — Flow manages them automatically.
Usage
To work with Internal State, you need to:
You can use any type as a state type, as long as it has serialization and deserialization functions defined. By default, all types with standard Serialize/Deserialize functions defined in YT are supported (including TYsonStruct subclasses); for a custom type, you just need to provide overloads for these functions.
By default, a state is considered empty if it equals the default value (TMyState{}), and clearing it recreates it. To override this behavior, the state type can inherit optional mixins from NYT::NFlow:
ICustomStateOps— custom logic forClear()andIsEmpty()(specified as a pair);ICustomYsonView— custom representation forToYsonView()for read-state introspection.
You need to:
- Declare a
TMutableStateKeyClient<TMyState> MyStateClient_field in your process function. - Override
Init(const IRuntimeInitContextPtr& initContext)and callinitContext->InitClient<TMyState>(MyStateClient_, "my_state")in it. Use a string that’s unique within the computation as the name. - To get the state by key, use
MyStateClient_.GetState(message->Key). The returned accessorTStateAccessor<TMyState>behaves like a smart pointer toTMyState(state->...,*state) and is valid only within the current epoch — you can’t store it in fields. - To clear the state (delete the row from the table), call
state.Clear()on the accessor.
If the state is empty, the corresponding row will be deleted.
Example:
struct TMyState
: public NYTree::TYsonStruct
{
std::optional<ui64> SomeValue;
REGISTER_YSON_STRUCT(TMyState);
static void Register(TRegistrar registrar)
{
registrar.Parameter("some_value", &TThis::SomeValue)
.Default();
}
};
class TMyFunction
: public IProcessFunction
{
public:
void Init(const IRuntimeInitContextPtr& initContext) override
{
initContext->InitClient(MyStateClient_, "my_state");
}
void ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/) override
{
auto state = MyStateClient_.GetState(message->Key);
state->SomeValue = 42;
// ...
}
void ProcessTimer(
const TInputTimerConstPtr& timer,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/) override
{
auto state = MyStateClient_.GetState(timer->Key);
// Clear the state (delete the row from the table):
state.Clear();
}
private:
TMutableStateKeyClient<TMyState> MyStateClient_;
};
Compression
Internal State supports data compression. You configure it in DynamicSpec for each state separately — in the state_manager section of the computation, in overrides/<state_name>/format:
compress— enable compression (defaultfalse);recode_probability— probability to recode the state to the specified format during the next processing; this ensures gradual migration of states after changing the format (default0.1).
Yson State Reader
Warning
This functionality is not yet implemented.
External State
External State is a state stored in a user-defined dynamic table in YTsaurus. Unlike Internal State, the tables are created and managed by the user.
The external state manager is declared in the Computation spec under a unique name in the external_state_managers section and connected to the Computation via a typed client TMutableStateKeyClient<TState>. The names in the spec must start with / (for example, "/state") and match the name passed to InitExternalStateClient. The implementation is looked up in the registry by external_state_manager_class_name.
Usage
To work with External State, you need to:
- Declare a
TMutableStateKeyClient<TState> StateClient_field in your process function, whereTStateis the state type returned by the corresponding external state manager (see below for specific implementations). - Override
Init(const IRuntimeInitContextPtr& initContext)and callinitContext->InitExternalStateClient(StateClient_, "/state")in it. Use a string that’s unique within the computation as the name — this same name must appear in the spec. - To get the state by key, use
StateClient_.GetState(message->Key). The returned accessorTStateAccessor<TState>behaves like a smart pointer toTStateand is valid only within the current epoch.
Example:
class TMyFunction
: public IProcessFunction
{
public:
void Init(const IRuntimeInitContextPtr& initContext) override
{
initContext->InitExternalStateClient(StateClient_, "/state");
}
void ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/) override
{
auto state = StateClient_.GetState(message->Key);
i64 count = state->GetColumnValue<std::optional<i64>>("count").value_or(0);
TPayloadBuilder builder(state->Schema);
builder.Set(count + 1, "count");
state->Payload = builder.Finish();
}
private:
TMutableStateKeyClient<TSimpleExternalState> StateClient_;
};
Computation spec with TSimpleExternalStateManager connected:
"external_state_managers" = {
"/state" = {
"external_state_manager_class_name" = "NYT::NFlow::TSimpleExternalStateManager";
"parameters" = {
"path" = "//path/to/state/table";
};
};
};
Preload and auto_preload
By default (auto_preload = %true), the framework preloads every external state manager before processing an epoch with all message, timer, and visit keys — one lookup per key. With "auto_preload" = %false;, the process function loads only the keys it needs through the client: PreloadKeyStates(THashSet<TKey>), PreloadKeyStates(IInputContextPtr), or PreloadKeyStates(IInputContextPtr, TExtractKeysOptions). The options select the entity kinds whose keys are taken, for example {.Visits = false} for a state that a visit handler doesn’t read. Preload is incremental: it may be called several times within an epoch, only keys not loaded yet are fetched, and an already loaded, possibly modified state is left as is. GetState on a key that wasn’t preloaded in the epoch throws. auto_preload = %false isn’t allowed for companion computations.
In IBatchProcessFunction::Process, dispatch entities through the helpers described in Process functions:
void Process(const IInputContextPtr& input, const IOutputCollectorPtr& output, const IRuntimeContextPtr& context) override
{
if (!context->GetSpec()->ExternalStateManagers.at("/state")->AutoPreload) {
WaitFor(StateClient_.PreloadKeyStates(input, {.Visits = false})).ThrowOnError();
}
ProcessMessages(input, output, context, BIND(&TMyFunction::ProcessMessage, MakeStrong(this)));
ProcessVisits(input, output, context, BIND(&TMyFunction::ProcessVisit, MakeStrong(this)));
}
Deleting without reading: EraseState
StateClient_.EraseState(key) stages the deletion of a row without preloading or reading it — a key visitor that expires rows by a key column (say, a timestamp) never pays a lookup for them. Erase is terminal for the epoch: afterwards GetState throws and PreloadKeyStates does not bring the key back, whether or not it was loaded before. TSimpleExternalStateManager, TProfileStateManager and the internal per-key state delete by key alone; a user-defined manager that does not override EraseKeyState rejects the call.
for (const auto& visit : input->GetVisits()) {
if (GetColumnValue<ui64>(visit->Key, "ts") + Week < now) {
StateClient_.EraseState(visit->Key); // No lookup.
}
}
TSimpleExternalStateManager
TSimpleExternalStateManager is the standard implementation of an external state manager. It works with a single dynamic table whose keys match the group_by_schema. GetState returns an accessor over TSimpleExternalState with Payload and Schema fields; columns are retrieved and written via GetColumn[Value]<T> / TPayloadBuilder by name or index. State caching happens automatically via the shared StateCache.
You don’t need to register TSimpleExternalStateManager in register.cpp — it’s already registered in the Flow library itself.
Spec:
Source: yt/yt/flow/library/cpp/computation/simple_external_state_manager.h
|
Parameter |
Description |
|
|
Type: |
Dynamic spec:
Source: yt/yt/flow/library/cpp/computation/simple_external_state_manager.h
This structure has no main parameters.
For a complete example of using TSimpleExternalStateManager, see the breakdown of the word_count example.
External State Joiner
Use the External State Joiner to get read-only access to external states via a key-based join. You cache the loaded states in the shared StateCache with a TTL. Before the TTL expires, repeated requests for the same key are served from the cache without contacting YT.
You declare an external state joiner in the Computation spec under a unique name in the external_state_joiners section. Connect it to the Computation using the typed client TJoinedStateKeyClient<TState>. The names in the spec must start with / (for example, "/reference") and match the name you pass to InitExternalStateClient. The system looks up the implementation in the registry by external_state_joiner_class_name.
Usage
This works similarly to the external state manager:
class TMyFunction
: public IProcessFunction
{
public:
void Init(const IRuntimeInitContextPtr& initContext) override
{
initContext->InitExternalStateClient(StateReaderClient_, "/reference");
}
void ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/) override
{
auto state = StateReaderClient_.GetState(message->Key);
// state is a read-only accessor TConstStateAccessor<TSimpleExternalState> (valid within the epoch).
}
private:
TJoinedStateKeyClient<TSimpleExternalState> StateReaderClient_;
};
Here is a Computation spec with TSimpleExternalStateJoiner attached:
"external_state_joiners" = {
"/reference" = {
"external_state_joiner_class_name" = "NYT::NFlow::TSimpleExternalStateJoiner";
"parameters" = {
"path" = "//path/to/reference/table";
};
};
};
TSimpleExternalStateJoiner
TSimpleExternalStateJoiner is the standard implementation of an external state joiner. Its interface is similar to TSimpleExternalStateManager: it reads rows from a single dynamic table whose keys match the group_by_schema. The GetState method returns a read-only accessor over TSimpleExternalState, which contains TPayload and the schema of the table’s value columns. You retrieve columns via GetColumn[Value]<T> by name or index.
You don’t need to register TSimpleExternalStateJoiner in register.cpp; it’s already registered in the Flow library.
Spec:
Source: yt/yt/flow/library/cpp/computation/simple_external_state_manager.h
|
Parameter |
Description |
|
|
Type: |
Dynamic spec (set the cache TTL via the cache section):
Source: yt/yt/flow/library/cpp/computation/simple_external_state_manager.h
|
Parameter |
Description |
|
|
Type: |
TStaticTableKeyVisitorJoiner
TStaticTableKeyVisitorJoiner is an external state joiner over a static sorted table. It works only with the key-visitor stream. Unlike TSimpleExternalStateJoiner, it doesn’t perform random reads. The background visitor scan reads the table sequentially using the same key ranges as the internal state, and the table row becomes available in ProcessVisit as a read-only state for the visit key. If a key isn’t in the table, it returns an empty state (IsEmpty() == true).
You bind the joiner to a visit stream by listing its name in the external_names field (table keys take part in the scan) or the weak_external_names field (they don’t: a left join against the state’s own keys) of the key_visitor_streams section (see static spec parameters). You can bind one joiner to no more than one visit stream (the system checks this when you submit the spec). join_on/key_schema_override isn’t supported; the key is always the joiner’s own group_by_schema.
Requirements for the source table:
- It must be static; the system rejects a dynamic table when reading the schema.
- It must be sorted so that the prefix of its key columns matches the
group_by_schemaof theComputationby name and type. The table can reside on another cluster (<cluster=...>in the rich path).
Warning
The system doesn’t validate computed column expressions. The source’s partition column must be materialized with values that match the expression in group_by_schema (usually farm_hash(key)). The framework can’t distinguish a differently materialized table from a correct one; each visit key silently resolves as missing.
The canonical pattern is mirroring (reconciliation). The table’s keys participate in the scan alongside the keys of your own state. That means a visit arrives for a key that isn’t yet in the state (you need to create it) and for a key that’s no longer in the table (you need to delete it). A periodic scan thus aligns the Computation’s state with the external table:
class TMirrorFunction
: public IProcessFunction
{
public:
void Init(const IRuntimeInitContextPtr& initContext) override
{
initContext->InitClient<TMirrorState>(MirroredState_, "/mirror");
initContext->InitExternalStateClient(SourceState_, "/source");
}
void ProcessVisit(
const TInputVisitConstPtr& visit,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/) override
{
auto src = SourceState_.GetState(visit->Key);
if (!src.IsInitialized()) {
// The source range wasn’t read (mark_unreadable): the key’s state is unknown.
return;
}
auto mirror = MirroredState_.GetState(visit->Key);
if (src.IsEmpty()) {
mirror.Clear();
} else {
mirror->Payload = src->GetColumnValue<std::optional<std::string>>("payload").value_or(std::string{});
}
}
private:
TMutableStateKeyClient<TMirrorState> MirroredState_;
TJoinedStateKeyClient<TSimpleExternalState> SourceState_;
};
Here is the Computation spec for this example:
"external_state_joiners" = {
"/source" = {
"external_state_joiner_class_name" = "NYT::NFlow::TStaticTableKeyVisitorJoiner";
"parameters" = {
"path" = "//path/to/source";
};
};
};
"key_visitor_streams" = {
"visit_iter" = {
"names" = ["/mirror"];
"external_names" = ["/source"];
};
};
The unavailable_source_policy defines the behavior when the source is unavailable. A read is considered unsuccessful if it exhausts the read_attempts limit:
retry(default): the error fails the scan iteration, and the read retries. The scan doesn’t advance past the unread range.mark_unreadable: the error is ignored, and the scan continues. Keys in the unread range resolve to an uninitialized accessor:IsInitialized() == false, and dereferencing throws an exception. TheComputationdecides how to handle a key whose state is unknown in the source (usually you skip the visit, as shown in the example above).
After an unsuccessful read, the source is marked unavailable for unavailable_source_backoff. While this flag is active, the system doesn’t contact the source; reads immediately resolve according to the policy. The first read after the window expires tries the source again. You can see the joiner’s state in the worker sensors static_table_key_visitor_joiner/{source_unavailable,failed_reads,reader_opens,listed_size} with the tag external_state_joiner=<name>.
You don’t need to register TStaticTableKeyVisitorJoiner in register.cpp; it’s already registered in the Flow library.
Spec:
Source: yt/yt/flow/library/cpp/computation/static_table_key_visitor_joiner.h
|
Parameter |
Description |
|
|
Type: |
|
|
Type: NYT::NFlow::EUnavailableSourcePolicy |
Dynamic spec:
Source: yt/yt/flow/library/cpp/computation/static_table_key_visitor_joiner.h
|
Parameter |
Description |
|
|
Type: |
|
|
Type: TDuration |
State Joiner
Use the State Joiner to get read-only access to the internal state of another Computation. One Computation can enrich its data with the state that another Computation accumulates, even when the join key doesn’t match its own group_by_schema.
You declare the Joiner in the Computation spec under a unique name in the state_joiners section and connect it via the typed client TJoinedStateKeyClient<TState>. Names in the spec must start with / and match the name you pass to InitClient. You don’t need a separate implementation or registration—this is a built-in Flow feature.
In the spec, you specify:
computation_id— theComputationwhose internal state is read.state_name— the state client name of the targetComputation(the prefix it passed toInitClient; it must start with/).join_on/key_schema_override— the columns in the current row that define the key. If you don’t set this, theComputationuses its owngroup_by_schema(join on the same key).join_on/key_provider_streams— the streams from which keys are taken from messages and timers (nulloptmeans all input streams).auto_preload— iftrue(the default), the framework loads the keys before eachDoProcess; otherwise, theComputationcallsPreloadKeyStatesitself.
Warning
The framework checks key types at startup: key_schema_override (or the Computation’s own group_by_schema if you don’t set an override) must match the target Computation’s group_by_schema in the number of columns and their types. The Joiner calculates the full key for the target state. Column names and expressions can differ.
You’re responsible for the following (the framework doesn’t check them):
- Value mapping — you must ensure each column maps correctly so the calculated key points to the right row in the other
Computation’s state. TStatemust match the state type of the targetComputation. The Joiner deserializes its rows the same wayTMutableStateKeyClient<TState>does on the owner side.
Usage
class TMyFunction
: public IProcessFunction
{
public:
void Init(const IRuntimeInitContextPtr& initContext) override
{
initContext->InitClient(UpstreamClient_, "/upstream");
}
void ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/) override
{
auto state = UpstreamClient_.GetState(message);
// state — read-only accessor TConstStateAccessor<TUpstreamState> (valid within the epoch).
}
private:
TJoinedStateKeyClient<TUpstreamState> UpstreamClient_;
};
Spec for a Computation with a Joiner connected using a key that differs from its own group_by_schema:
"state_joiners" = {
"/upstream" = {
"computation_id" = "accumulator";
"state_name" = "/total";
"join_on" = {
"key_schema_override" = [
{name = "Hash"; expression = "farm_hash(UserId)"; type = "uint64"; required = %true;};
{name = "UserId"; type = "string"; required = %true;};
];
};
};
};
By default, the cache is disabled (ttl = 0). The Joiner reads the target Computation’s state at SyncLastCommittedTimestamp each epoch, so you always see the latest commits. You enable a cache with TTL in the dynamic spec via the cache section (loaded states stay valid until ttl expires; repeated reads for the same key are served without contacting YT). For Swift computations that require strict determinism, you must consider the cache and reading at SyncLastCommittedTimestamp.
Spec:
Source: yt/yt/flow/library/cpp/common/spec.h
|
Parameter |
Description |
|
|
Type: NYT::NFlow::TComputationId |
|
|
Type: |
|
|
Type: |
|
|
Type: |
Dynamic spec (set cache TTL via the cache section):
Source: yt/yt/flow/library/cpp/common/spec.h
|
Parameter |
Description |
|
|
Type: |
StateCache
Flow provides a shared two-level (uncompressed + compressed) LRU cache for states. You configure it via /dynamic_spec/job_tracker/state_cache. It’s primarily used for manager states; Joiners have the cache disabled by default, and data is loaded at SyncLastCommittedTimestamp.
Source: yt/yt/flow/library/cpp/common/spec.h
|
Parameter |
Description |
|
|
Type: NYT::NYTree::TSize |
|
|
Type: NYT::NYTree::TSize |
For more details on group_by_schema consistency and general principles for working with states, see Stateful processing.