Companion in YTsaurus Flow
In Flow, you can run user code in a separate process. This process is called a companion process.
Companion use cases
Currently used
- Supporting computations in languages other than C++, such as Python, Java and Kotlin, and Go.
- Running user C++ code in a separate process through the C++ companion.
Planned
- Hot updating user code without stopping the pipeline.
Workflow
When you use a companion, the Computation consists of two parts: a specialized Computation on the Worker side and a lightweight Computation on the companion side.
Note
You develop all business logic in the chosen programming language on the companion side, while the pipeline structure is still configured via the spec. In this workflow, the worker becomes an infrastructure binary that doesn’t depend on the pipeline logic. So, when you use Python, Go, Java, or Kotlin, you don’t need to write any C++ user code.
The Computation on the Worker side collects a batch of messages, enriches it with all the information needed for processing (states, parameters, watermark values, and so on), and sends it to the companion via gRPC locally, within a single host.
The batch is formed without regard to keys — one request may contain messages with different keys; this is how the worker collects batches for all computations. There is no per-key grouping in the companion protocol: if the business logic needs per-key processing, it is done in the companion code — see the Python example.
The companion returns its output in groups; each group carries lineage — the list of ids of the input messages of the batch its output was derived from (lineage is unrelated to keys). For when lineage must be set explicitly and what exactly to pass, see When to set lineage explicitly.
In the future, you’ll also be able to use Unix sockets.
You manage the companion process through the resource CompanionManager.
Configuration
Here’s an example of declaring the resource in a static spec for Java:
"CompanionManager" = {
"resource_class_name" = "NYT::NFlow::NCompanion::TJavaCompanionManager";
"parameters" = {
"timeout" = "10s";
"jdk_bin_path" = "/app/ytflow/jdk/bin/java";
"main_class" = "tech.ytsaurus.flow.examples.wordcount.WordCountApplication";
"classpath" = "/app/ytflow/lib/*";
};
"dependencies" = {};
};
For a detailed description of all TCompanionManagerParameters parameters, see the section CompanionManager resource configuration.
The Python companion configuration is described in the section CompanionManager resource configuration (Python).
Here’s an example of declaring a Computation in a static spec:
"computations" = {
"mapper" = {
"computation_class_name" = "NYT::NFlow::NCompanion::TTransformCompanionComputation";
"group_by_schema" = [
{"name" = "hash"; "expression" = "farm_hash(word)"; "type" = "uint64"; required = %true;};
{"name" = "word"; "type" = "string";};
];
"input_stream_ids" = ["words"];
"output_stream_ids" = [];
"required_resource_ids" = {
"CompanionManager" = {
"controller" = false;
"worker" = true;
};
};
"parameters" = {
"internal_states" = ["word-state"];
};
};
};
The key point in this example is using the CompanionManager resource to launch the companion process and the specialized Computation class NYT::NFlow::NCompanion::TTransformCompanionComputation.
C++ companion
You can move user C++ code out of the worker into a separate process as well. The SDK is located in yt/yt/flow/library/cpp/companion/server: you declare the served Computations in TPipeline, specifying the process function type (this typed declaration replaces YT_FLOW_DEFINE_PROCESS_FUNCTION), and build a separate binary with the RunCompanionMain entry point:
int main(int argc, const char** argv)
{
NYT::NFlow::NCompanionServer::TPipeline pipeline;
pipeline.AddSource<TMyReadFunction, TMyReadParameters>("reader");
pipeline.AddTransform<TMyMapFunction>("mapper");
return NYT::NFlow::NCompanionServer::RunCompanionMain(argc, argv, std::move(pipeline));
}
The function is selected by the name from the processing_function field of the Computation spec, the same way as in the in-process TProcessFunctionComputation adapters. The worker launches the binary through the generic TCompanionManager resource:
"CompanionManager" = {
"resource_class_name" = "NYT::NFlow::NCompanion::TCompanionManager";
"parameters" = {
"entrypoint" = {
"executable" = "/path/to/my_companion";
};
};
};
A process function in a companion can take the HTTP clients from IRuntimeInitContext in Init (GetHttpClient(), GetHttpsClient()). The clients are configured by the http_client_config, https_client_config and http_poller_threads fields of the companion block of the worker node config (TCompanionConfig).
Limitations of the C++ companion:
- sync process functions aren’t supported (the companion protocol has no Sync phase): a function that overrides
Syncis rejected during initialization; - process function graphs aren’t supported;
- distributed throttlers (
GetThrottlerOrThrow,TryGetThrottler) aren’t available; AsPartition()andAsKey()of the init context, as well as joins by internal state (CreateJoinedStateKeyProvider), aren’t supported and throw an exception;AddFailedMessageisn’t supported;TProcessFunctionContexthas onlyInitContext,ComputationSpec,LoggerandStatusProfilerset.ClientsCache,InvokerandRetryableClientarenullptr;- an internal state must be declared in the computation's
internal_statesparameter, and its holder must support YSON serialization; - mutable internal and external state is accessible only for keys of messages, timers, and visits in the current batch. Reading or erasing another key raises an error. The worker sends state with the batch.
PreloadKeyStatesonly checks the requested keys and returns a completed future. The future succeeds for a batch key even if it has no stored value, and fails if any requested key is outside the batch; GetStreamSpecs()->ComputeKey()can’t compute a key whengroup_by_schemahas computed columns: a companion doesn’t evaluate expressions. The key arrives with the message — usemessage->Key;- external states are supported only as
TSimpleExternalState; - output timers can only reference the key of one of the parent entities of the batch;
- when the dynamic spec changes, the companion creates the process function anew and calls
Initagain, so data held in the function's memory isn't preserved; - the companion runs as a single multithreaded process.
For an example, see yt/yt/flow/examples/cpp/companion_word_count.
For registration, build dependencies and worker wiring, see Running C++ process functions in a companion. Companion-hosted resources are available through GetStaticResource; resources that exist only in the worker are not transferred automatically.
Companion resource wiring
A companion-hosted resource is an object created inside the companion and shared by the jobs served by that process. The worker holds a proxy and sends lifecycle commands to it. Resource APIs are documented for Python, Java and Kotlin, and C++.
Three names serve different purposes:
|
Name |
Where it is used |
|
Implementation name |
|
|
Resource id |
A key in |
|
Alias |
A dependency or computation requirement can expose the resource under |
After registering the implementation in your language SDK, connect it in the spec:
- Configure the companion manager according to the language's getting-started guide.
- Add the resource to
spec.resourceswithresource_class_name = "NYT::NFlow::NCompanion::TCompanionResource". Setparameters.companion_resource_classto the registered implementation name, and put your static parameters in the sameparametersmap. - In the resource's
dependencies, require the manager on the worker under aliasCompanionManager. Setworker = %trueandcontroller = %false. If its resource id is alreadyCompanionManager, no explicit alias is needed. - Declare any other companion-hosted dependencies in that map, also with worker-only requirements. Their aliases are local to the resource's dependency context. Flow initializes dependencies before dependents.
- In the computation's
required_resource_ids, require both the manager and the hosted resource on the worker (worker = %true,controller = %false). The manager must be exposed asCompanionManager; the hosted resource's alias is the name used by user code. - Put dynamic resource parameters in
dynamic_spec.resources.<resource_id>.parameters. Flow delivers updates to the resource lifecycle; changing static configuration follows the pipeline configuration rules.
See the maintained Python, JVM and C++ specs. They distinguish the resource id greeting, computation alias greeting_view, and dependency-local alias dependency.
Initialization and recovery
The worker proxy's parameters.init_backoff controls retries during initial loading. An unregistered resource class, an unsupported resource command or a stale resource incarnation fails that loading attempt without the transient-error retry loop. For an unknown class, compare companion_resource_class with the registration in the actual companion executable.
parameters.keep_alive_interval controls periodic idempotent initialization. It must be positive. Repeated initialization of an unchanged live instance does not call its factory or load again. Periodic initialization can retry a failed reconfiguration and rebuild resources after a companion process restart. If a dependency instance changes, a dependent resource can be recreated with the updated binding.
Batches carry exact resource-instance and configuration references. A missing or stale reference prevents that batch from entering user code; the worker can initialize the graph and retry. This mechanism does not synchronize the mutable state of a resource already held by a batch. Follow the language-specific lifecycle and concurrency rules.
Worker-side metrics
The worker reports the state of its connection to a companion in any language:
yt.flow.worker.computation.companion_client.retry_countcounts repeated companion calls of a computation, tagged withcomputation_id. Theoperationtag names the call:DoProcess,GetCompanionInfo,PutJoborResourceExecute.yt.flow.worker.resource.companion_client.retry_countcounts repeated calls of the companion manager and of companion-hosted resource proxies. Theresourcetag identifies the resource.yt.flow.worker.resource.companion_resource.init_retry_countcounts retries of the initial loading of a companion-hosted resource; see Initialization and recovery.yt.flow.worker.resource.companion_manager.restartscounts restarts of the companion process.
The standard yt.rpc.client.* metrics describe the RPCs to the companion: request time, request and response sizes, failed and timed-out requests. They are tagged by method, not by computation.
Types of Computations for working with companions
NYT::NFlow::NCompanion::TSwiftMapCompanionComputation: An implementation of TSwiftMapComputation that delegates data processing to the companion process.NYT::NFlow::NCompanion::TSwiftOrderedSourceCompanionComputation: An implementation of TSwiftOrderedSourceComputation that delegates data processing to the companion process.NYT::NFlow::NCompanion::TTransformCompanionComputation: An implementation of TTransformComputation that delegates data processing to the companion process.NYT::NFlow::NCompanion::TTransformOrderedSourceCompanionComputation: An implementation of TTransformOrderedSourceComputation that delegates data processing to the companion process.
TSwiftMapCompanionComputation accepts only messages as input. Spec validation rejects any timer streams (timer_streams) or key-visitor streams (key_visitor_streams). A timer in the output fails the batch.
To enrich messages with data from an external table, declare an external state joiner in external_state_joiners, for example NYT::NFlow::TSimpleExternalStateJoiner. The joiner provides read-only access. Swift Map companions support only joiners that take keys from messages. Each joiner must have auto_preload = %true (the default). This applies in both batching modes. Choose a joiner and state format supported by the companion SDK.
By default, the joiner uses the computation's grouping key. Set join_on/key_schema_override to derive a different key from the message and join_on/key_provider_streams to select the input streams that supply lookup keys. For TSimpleExternalStateJoiner, the reference table's key schema must match join_on/key_schema_override when it is set or group_by_schema otherwise. For example, if the computation groups by word and joins on tag, the reference table is keyed by tag. For a message with word=alpha and tag=beta, the joiner looks up the row keyed by beta.
For joined state in table row format, C++ TJoinedStateKeyClient::GetState(message) derives the lookup key from the message. Message-based accessors in Python, Go, and Java/Kotlin use the grouping key. If the lookup key differs, pass it explicitly in these SDKs. For a message from a selected input stream, build a Payload that matches the key sent by the worker, using the columns, order, and types in the override schema.
- In Python, call
ctx.joined_external_state(name, dataclasses.replace(message, key=join_key)). Use the original message when emitting output. - In Go, get the holder with
rt.JoinedExternalState(name)and callholder.Get(joinKey). - In Java or Kotlin, pass a
Keyedthat returns the lookup key toctx.getState(StateDescriptors.externalReadOnly(name), keyed), for example() -> joinKeyin Java orKeyed { joinKey }in Kotlin.
A new lookup during replay can read a newer value from the reference table. The default Swift Map mode requires deterministic replay. The output must preserve its message count and order, keys, IDs, event timestamps, and parent lineage. This includes event timestamps read from an enriched field via watermark_strategy/event_timestamp_assigner/column.
Only non-key payload fields that cannot affect downstream message keys may vary. Downstream computations may then persist different values for those fields. Verify that the pipeline works correctly with those differences.
Setting parameters/allow_batching_with_relaxed_guarantees = %true enables relaxed batching with at-least-once processing. To materialize and commit the output of one successful processing attempt when the reference table can change, use TTransformCompanionComputation in its default exactly_once mode.
Before upgrading, check the static specs of TSwiftMapCompanionComputation computations for joiners with auto_preload = %false. The upgraded controller rejects those specs even after the pipelines have drained. Remove unused joiners from the static specs while the affected pipelines are stopped.
TTransformCompanionComputation rejects a spec where an external state manager has auto_preload = %false: the companion receives states with the batch and can’t load them on demand.
Two modes are available for a Source computation. TSwiftOrderedSourceCompanionComputation doesn’t materialize the output and requires deterministic processing without user state. TTransformOrderedSourceCompanionComputation materializes the output and commits it together with the internal state and the source offset in the epoch transaction. Choose it for non-deterministic processing or for working with internal state; the key of such a state is the source partition key. The spec limitations are the same as for TTransformOrderedSourceComputation.
For more details on implementing pipelines using companions, see Java and Kotlin, Python, and Go.