Shuffle in YTsaurus Flow (C++)
You use the pipeline to read a JSON stream from a sorted dynamic table, group it multiple times by different keys, and then count the number of unique keys in all resulting streams. A test is also described for the pipeline.
This pipeline doesn’t aim to solve any business problem.
General pipeline overview
Reader. Reading input data
The first computation is Reader. It reads and performs initial transformation of data from the queue. Here are the parts of the spec related to this computation:
{
"spec" = {
"computations" = {
"reader" = {
"computation_class_name" = "NYT::NFlow::TProcessFunctionSourceComputation";
"processing_function" = "NYT::NFlow::NExample::TQueueReader";
"output_stream_ids" = ["event"];
"source_streams" = {
"queue" = {
"source_class_name" = "NYT::NFlow::TQueueSource";
"parameters" = {
"queue_path" = "<cluster=cluster_name>//path/to/queue";
"consumer_path" = "<cluster=cluster_name>//path/to/consumer";
"finite" = false;
};
};
};
};
};
"streams" = {
"event" = {
"schema" = [
{"name" = "key_a"; "type" = "uint64";};
{"name" = "key_b"; "type" = "uint64";};
{"name" = "key_c"; "type" = "uint64";};
{"name" = "key_d"; "type" = "uint64";};
{"name" = "value"; "type" = "string";};
];
}
};
};
}
Let’s break it down.
computations/reader/source_streamscontains thequeuesource with the typeNYT::NFlow::TQueueSource. Thissourcereads data from a sorted dynamic table using aconsumer. Inparameters, you specify which queue to read from and which consumer to use. You can learn more about the parameters in theNYT::NFlow::TQueueSourceParametersclass.- Use
NYT::NFlow::TQueueSourceControllerto manage theComputation, because you need to define the number and settings of the partitions based on the input sorted dynamic table. streamscontains a singleeventflow — the parsed flow output fromreader, which is available to otherComputationcomponents. It has an associated schema. This same flow is also registered incomputations/reader/output_stream_ids.- The
TQueueReaderclass implementsIProcessFunction; theTProcessFunctionSourceComputationnamed incomputation_class_namehosts it. A built-in passthrough isn’t suitable here because parsingJSONrequires a customProcessMessageimplementation.
void TQueueReader::ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& output,
const IRuntimeContextPtr& context)
{
auto data = GetColumnValue<std::string>(message, "data");
::NJson::TJsonValue json;
::NJson::ReadJsonTree(data, &json, /*throwOnError*/ true);
auto builder = context->MakeOutputMessageBuilder("event");
builder.Payload().Set<std::string>(json["value"].GetStringSafe(), "value");
builder.Payload().Set<ui64>(json["key_a"].GetUIntegerSafe(), "key_a");
builder.Payload().Set<ui64>(json["key_b"].GetUIntegerSafe(), "key_b");
builder.Payload().Set<ui64>(json["key_c"].GetUIntegerSafe(), "key_c");
builder.Payload().Set<ui64>(json["key_d"].GetUIntegerSafe(), "key_d");
output->AddMessage(builder.Finish());
}
- The source adapter runs in Swift mode: it doesn’t materialize output streams in YTsaurus and saves only the metadata required for deterministic operation.
TQueueSourceand the adapter manage queue access, including access to a remote cluster. The process function receives an already-read message and doesn’t access a YTsaurus client directly.
Shuffle
The pipeline includes several shuffles: shuffle_a, shuffle_b, shuffle_c, and shuffle_d. Each of them groups the input stream by the corresponding key — key_a, key_b, key_c, or key_d. They don’t transform the data; they just demonstrate the ability to group different objects.
Let’s examine the spec for shuffle_b:
{
"spec" = {
"computations" = {
"shuffle_b" = {
"computation_class_name" = "NYT::NFlow::TSwiftPassthroughComputation";
"group_by_schema" = [
{"name" = "hash"; "expression" = "farm_hash(key_b)"; "type" = "uint64";};
{"name" = "key_b"; "type" = "uint64";};
];
"input_stream_ids" = ["event_a"];
"output_stream_ids" = ["event_b"];
};
};
streams = {
"event_a" = {
"schema" = [
{"name" = "key_a"; "type" = "uint64";};
{"name" = "key_b"; "type" = "uint64";};
{"name" = "key_c"; "type" = "uint64";};
{"name" = "key_d"; "type" = "uint64";};
{"name" = "value"; "type" = "string";};
];
};
"event_b" = {
"schema" = [
{"name" = "key_a"; "type" = "uint64";};
{"name" = "key_b"; "type" = "uint64";};
{"name" = "key_c"; "type" = "uint64";};
{"name" = "key_d"; "type" = "uint64";};
{"name" = "value"; "type" = "string";};
];
};
};
};
}
- Since this example doesn’t include any data transformation,
NYT::NFlow::TSwiftPassthroughComputationis sufficient. If transformation is required, implement the custom logic asIProcessFunctionand host it withNYT::NFlow::TProcessFunctionSwiftMapComputation. NYT::NFlow::TSwiftPassthroughComputationdoesn’t materialize data in YTsaurus.group_by_schemacontains the correspondingkey_bkey. Thehashcolumn is added, because partitioning inFlowworks only under the assumption that the first column contains uniformly distributeduint64values.input_stream_idsandoutput_stream_idscontainevent_aandevent_b, respectively.spec/streamsalso containsevent_aandevent_bwith the full schema description.
Reduce
This is the final Computation. It reads the event_a, event_b, event_c, and event_d streams and counts how many times each value appears. In effect, the original stream is processed four times.
{
"spec" = {
"computations" = {
"reducer" = {
"computation_class_name" = "NYT::NFlow::TProcessFunctionComputation";
"processing_function" = "NYT::NFlow::NExample::TReducer";
"group_by_schema" = [
{"name" = "hash"; "expression" = "farm_hash(value)"; "type" = "uint64";};
{"name" = "value"; "type" = "string";};
];
"input_stream_ids" = ["event_a"; "event_b"; "event_c"; "event_d";];
"output_stream_ids" = [];
"external_state_managers" = {
"/state" = {
"external_state_manager_class_name" = "NYT::NFlow::TSimpleExternalStateManager";
"parameters" = {
"path" = "//path/to/state";
};
};
};
};
};
};
};
- The process function
TReducer, hosted byTProcessFunctionComputation, implements the logic. - To work with the state, the example uses
TSimpleExternalStateManager, which provides direct access to the table.TReducerstores aTMutableStateKeyClient<TSimpleExternalState>and binds it to"/state"inInit(const IRuntimeInitContextPtr&).
void TReducer::Init(const IRuntimeInitContextPtr& initContext)
{
initContext->InitExternalStateClient(StateClient_, "/state");
}
void TReducer::ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& /*output*/,
const IRuntimeContextPtr& /*context*/)
{
auto state = StateClient_.GetState(message->Key);
i64 count = state->GetColumnValue<std::optional<i64>>("count").value_or(0);
count += 1;
TPayloadBuilder builder(state->Schema);
builder.Set(count, "count");
state->Payload = builder.Finish();
}
See also
-
You must include the
valuecolumn (and its hash) ingroup_by_schemato group byvalue. -
List all streams —
event_a,event_b,event_c, andevent_d— ininput_stream_idsto read all resulting streams. From a business logic perspective, this isn’t the most meaningful action. However, the original goal of this pipeline was to test theexactly-onceguarantees, even in the case of aSwiftchain. -
TReducerimplementsIProcessFunctionand is hosted byTProcessFunctionComputation. The adapter persistsinput_messagesandoutput_messagesin YTsaurus, but this example produces no output messages. In effect, the pipeline saves thereadermetadata, the (message_id,key) metadata for eachreducerinput message, and thevalue => counttable. The intermediate passthrough computations don’t interact with YTsaurus.
DynamicSpec
- Fill the
dynamic_spec/computations/<computation_id>/parameters/desired_partition_countfield for eachcomputationexceptreader. Thetest_shuffle.pytest changes the number of partitions. - Specify the required number of threads for running all jobs in
dynamic_spec/job_tracker/job_threads.
Config for running
- Key settings for running:
cluster_url,proxy_role,path,rpc_port, andmonitoring_port. - Set
controller/scheduler_periodto 200 for this specific test — in reality, the default value should be sufficient. loggingcontains the logging settings.
{
"cluster_url" = "cluster_name";
"path" = "//path/to/pipeline";
"rpc_port" = 81;
"monitoring_port" = 80;
"controller" = {
"scheduler_period" = 200;
};
"logging" = {
"suppressed_messages" = [
];
"rules" = [
{
"exclude_categories" = [
"Bus";
"Dns";
"Concurrency";
"QueryClient";
"Profiling";
"RpcClient";
"Monitoring";
"Net";
"Solomon";
"Jaeger";
"RpcProxyClient";
"RpcServer";
"Dns";
"BufferMetrics";
];
"min_level" = "debug";
"writers" = [
"Stderr";
];
};
];
"writers" = {
"Stderr" = {
"type" = "file";
"file_name" = "/path/to/file.log";
};
};
}
}