---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.2
alternate:
  - https://ytsaurus.tech/docs/en/flow/cpp/examples/shuffle.md
  - https://ytsaurus.tech/docs/ru/flow/cpp/examples/shuffle.md
  - href: https://ytsaurus.tech/docs/en/flow/cpp/examples/shuffle.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/en/llms.txt?revision=0987aa47985046d89a7b7ec44c4bbc08e6a3b783
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/en/llms.txt?revision=0987aa47985046d89a7b7ec44c4bbc08e6a3b783

<!-- source: en/_includes/flow/cpp/examples/shuffle.md -->
# Shuffle in YTsaurus Flow (C++)

You use the [pipeline](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/cpp/shuffle) 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](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/cpp/shuffle/test/test_shuffle.py) 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](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#spec-and-dynamic-spec) related to this computation:

```yson
{
    "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_streams` contains the `queue` source with the type `NYT::NFlow::TQueueSource`. This `source` reads data from a sorted dynamic table using a `consumer`. In `parameters`, you specify which queue to read from and which consumer to use. You can learn more about the parameters in the `NYT::NFlow::TQueueSourceParameters` class.
- Use `NYT::NFlow::TQueueSourceController` to manage the `Computation`, because you need to define the number and settings of the [partitions](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#partition) based on the input sorted dynamic table.
- `streams` contains a single `event` flow — the parsed flow output from `reader`, which is available to other `Computation` components. It has an associated schema. This same flow is also registered in `computations/reader/output_stream_ids`.
- The `TQueueReader` class implements `IProcessFunction`; the `TProcessFunctionSourceComputation` named in `computation_class_name` hosts it. A built-in passthrough isn’t suitable here because parsing `JSON` requires a custom `ProcessMessage` implementation.

```cpp
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.
- `TQueueSource` and 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`:

```yson
{
    "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::TSwiftPassthroughComputation` is sufficient. If transformation is required, implement the custom logic as `IProcessFunction` and host it with `NYT::NFlow::TProcessFunctionSwiftMapComputation`.
- `NYT::NFlow::TSwiftPassthroughComputation` doesn’t materialize data in YTsaurus.
- `group_by_schema` contains the corresponding `key_b` key. The `hash` column is added, because partitioning in `Flow` works only under the assumption that the first column contains uniformly distributed `uint64` values.
- `input_stream_ids` and `output_stream_ids` contain `event_a` and `event_b`, respectively.
- `spec/streams` also contains `event_a` and `event_b` with 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.

```yson
{
    "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 by `TProcessFunctionComputation`, implements the logic.
- To work with the [state](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#state), the example uses `TSimpleExternalStateManager`, which provides direct access to the table. `TReducer` stores a `TMutableStateKeyClient<TSimpleExternalState>` and binds it to `"/state"` in `Init(const IRuntimeInitContextPtr&)`.

```cpp
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();
}
```
<!-- endsource: en/_includes/flow/cpp/examples/shuffle.md -->

<!-- source: en/_includes/flow/cpp/examples/shuffle_also.md -->
## See also

- [Quick start (C++)](https://ytsaurus.tech/docs/en/flow/cpp/getting-started.md)
- [Computation (C++)](https://ytsaurus.tech/docs/en/flow/cpp/computation.md)

- You must include the `value` column (and its hash) in `group_by_schema` to group by `value`.
- List all streams — `event_a`, `event_b`, `event_c`, and `event_d` — in `input_stream_ids` to 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 the `exactly-once` guarantees, even in the case of a `Swift` chain.
- `TReducer` implements `IProcessFunction` and is hosted by `TProcessFunctionComputation`. The adapter persists `input_messages` and `output_messages` in YTsaurus, but this example produces no output messages. In effect, the pipeline saves the `reader` metadata, the (`message_id`, `key`) metadata for each `reducer` input message, and the `value => count` table. The intermediate passthrough computations don’t interact with YTsaurus.

### DynamicSpec

- Fill the `dynamic_spec/computations/<computation_id>/parameters/desired_partition_count` field for each `computation` except `reader`. The `test_shuffle.py` test 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`, and `monitoring_port`.
- Set `controller/scheduler_period` to 200 for this specific test — in reality, the default value should be sufficient.
- `logging` contains the logging settings.

```yson
{
    "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";
            };
        };
    }
}
```
<!-- endsource: en/_includes/flow/cpp/examples/shuffle_also.md -->
