From dd4de0e65a25ea4da460b305cd91973397a4b0c6 Mon Sep 17 00:00:00 2001 From: Marius S <39998+winding-lines@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:12:33 -0800 Subject: [PATCH] DESIGN: a plan for keyed partitions in flows (Partition and Reduce) A docs-only plan for a group-by inside dista.flow: a Partition operator (a TaskMany per input, on its batches, making one piece per partition) and a Reduce (a TaskWith per partition, on that piece from every input), joined by a barrier. It settles the types and checks, the executor's two chains, memory and spilling, losses before and after the barrier, the hash, groups and sizing, and lists five PRs ending with bench/shuffle as a flow on sai beside the hand-written version and Ray. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017TycsyUqdnuDeZrYc3z6wV --- DESIGN.md | 305 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 304 insertions(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index c78edf7..3118299 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -921,7 +921,8 @@ Why not actors, which exist: - **Operators that aren't one-to-one after the read**: a flat map, a filter that drops batches, rebatching to a size, a union, a join. - **Shuffles inside a flow** (sort, group by, repartition): `TaskMany` - stays the way to write one. + stays the way to write one. A group-by is planned since: see "Keyed + partitions in flows" below. - **Budgets in bytes.** - **A flow across steps**, or one that checkpoints: it runs inside a morca step, and the step is what repeats. @@ -981,3 +982,305 @@ Why not actors, which exist: | Order of results | inputs as they finish, each input's results in the read's order | every result in input order (slower: one slow input holds the rest), or any order | | Budgets | in batches: 16 per operator, 4 streams of window 16 per read | in bytes | | Operators in the first version | `Read` first, then `Map` and `MapWith`, all one-to-one | a flat map and a filter from the start | + +## Keyed partitions in flows (plan, 2026-11-29) + +A flow's operators are one batch in, one batch out, so a group-by is still +written by hand: map tasks split their rows by key into one partition per +reducer (a `TaskMany`), and reducer `j` takes partition `j` from every map +task (a `TaskWith`), as `deploy/shuffle.mojo` and `tests/test_shuffle.mojo` +do. morca's [docs/layers.md](https://github.com/morca-dev/morca/blob/main/docs/layers.md) +lists that under flows: "the taxi and shuffle jobs are written by hand". +This plan adds two operators, `Partition` and `Reduce`, which together are +that shuffle inside a flow. They are the base for joins and sort later; the +first version is a hash group-by. + +```mojo +from dista import Emit, Runtime, Seq, TaskMany, TaskStream, TaskWith +from dista.flow import Flow, Partition, Read, Reduce + +comptime PARTS = 16 + +def scan_groups(t: MapFile, mut out: Emit[Groups]) raises: + """One data file's trips, added up per key, a batch at a time.""" + var tasks: List[FileScanTask] = [t.file.task()] + for b in _scan(TableMetadata.parse(t.metadata)).to_batches_for_tasks(tasks^): + out.put(groups_of(b)) + +def split_zones(batches: Seq[Groups]) raises -> Seq[Groups]: + """One input's groups, merged per key, split into PARTS by key % PARTS.""" + ... + +def reduce_zones(j: Int, parts: Seq[Groups]) raises -> Answer: + """Partition j of every input, merged: totals and top 10, as today.""" + ... + +comptime ScanGroups = TaskStream[MapFile, Groups, scan_groups] +comptime SplitZones = TaskMany[Seq[Groups], Groups, split_zones] +comptime ReduceZones = TaskWith[Int, Groups, Answer, reduce_zones] +comptime ZoneHours = Flow[ + Read[ScanGroups], Partition[SplitZones, PARTS], Reduce[ReduceZones] +] + +var rt = Runtime[ScanGroups, SplitZones, ReduceZones](workers=4) +var inputs = List[MapFile]() # one per planned data file, as today +for f in files: + inputs.append(MapFile(PlannedFile.of(f), reading, PARTS)) +var got = Answer.zero() +for a in ZoneHours.run(rt, inputs^): # one Answer per partition, by partition + got.add(a) +``` + +`groups_of` is a per-batch group-by into the bench's `Groups`; the rest is +`deploy/shuffle.mojo`'s code with the reducer count a compile-time constant. + +### The operators + +- **`Partition[T: ManyLike, parts: Int, budget: Int = 4]`**: one task per + input, on all of that input's batches. `T` is a `TaskMany` whose argument + is a `Seq` of the previous operator's output and whose function returns + exactly `parts` pieces: `rt.remote_many[T](refs, parts)`, the form that + already exists for a `TaskMany` taking a `Seq` (`Client.remote_many`). Its + `In` is `T.A`, a `Seq[X]`, and its `Out` is `T.Part`, the piece. +- **`Reduce[T: WithLike, budget: Int = 16]`**: one task per partition, + `rt.remote[T](j, refs)` with `j` the partition's index and `refs` that + partition's piece from every input, in input order. `T` is a `TaskWith` + whose value is an `Int`. Its `In` is the piece type, its `Out` `T.R`. +- **`Map` and `MapWith` may follow a `Reduce`**, one task per partition's + result, such as a sink writing one file per partition. Before the + `Partition`, the chain is today's: a `Read`, then `Map`s and `MapWith`s. +- **Why per input, not per batch.** The function sees a whole input's + batches, so it merges them before splitting: that is the combiner, in + user code, and an input makes `parts` pieces however many batches it + had. The cost of a shuffle in dista is its piece count: on 12 nodes, + 192 reducers over 416 map tasks (80,000 pieces) took twice as long as 96 + (`bench/cloud/results/NUMBERS.md`, 8c). Per batch, the same job would + make batches × parts pieces. The price is that an input's batches are + gathered on one worker, so an input must fit in one task's memory, and + a pre-aggregating `Map` or stream (as `scan_groups` above) keeps that + small. Inputs were already meant to be small: they are the unit of rerun. +- **The compile-time checks** (`Flow._check`): at most one `Partition`; a + `Reduce` comes right after it and nowhere else; a `Partition`'s `In` is + `Seq` of the previous operator's `Out`, checked by name, as + `reflect[In].name() == String("dista.seq.Seq[", reflect[Prev.Out].name(), "]")` + (*verified* on 1.3.0.dev2026112605, with the failing case failing to + compile); a `Reduce`'s task takes an `Int`. `start` adds what it can only + check at run time, as for `Map`: a `Partition`'s task is a `TaskMany` + and a `Reduce`'s a `TaskWith` (today's check refuses `is_many()` for every + operator after the read, `Flow.start`). +- **In the core**, two small changes: `ManyLike.Part` becomes + `Movable & Deinitable`, since `OpLike.Out` needs it and a `Partition` + over today's `ManyLike` doesn't compile (*verified*), as `TaskLike`'s `A` + and `R` were changed for flows' PR 1; and a `WithLike` trait exposing + `TaskWith`'s element type `X`, which nothing names today (the client + recognises a `TaskWith` by `reflect[T].base_name()`). + +### The executor + +A flow with a `Partition` is two chains joined by a barrier: the first runs +per input, as today, up to the `Partition`; the second runs per partition, +from the `Reduce` on. Nothing of the second starts until every input's +pieces exist, since reducer `j` needs piece `j` of every input, and the +number of inputs that will have batches isn't known before then. + +- **Before the barrier.** The operator before the `Partition` keeps its + results per input, outside its budget, as the last operator's are today + (`FlowRun._record`), since none is taken until its input ends. When an + input's stream has ended and all its batches are through (`_finish_one`), + the executor submits the `Partition` task on them in the read's order and + releases them (the head keeps them until that task settles). An input + with no batches makes no pieces. The `Partition`'s budget counts its tasks + in flight and the finished inputs waiting for one; the read opens a new + stream only while the `Partition` has room, so the batches held are at + most `streams` inputs' worth plus `budget` inputs waiting. +- **A partition task's pieces** are its result IDs: the first, plus `k` for + piece `k` (`Client.remote_many`; the head checks the range, + `Head._task_many`). The executor waits on the first only: the worker + answers the pieces last first, so the head sees the task in flight until + all are (`Worker._run_many`). Finished pieces count against no budget. +- **The barrier.** Once every input has its pieces, the executor looks at + every piece's error, which the driver already has without fetching + (`Client.error_of`), as `next` does today before handing an input out. +- **After it**, the second chain runs as the first does, with partition + indices as its inputs and the `Reduce` as its source: up to its budget of + reducers at once, each submitted on its pieces in input order and those + refs released at once (the driver holds the release back until the + reducer settles, `Client.release`). The head holds a reducer until its + pieces exist, so it holds no worker slot while it waits. +- **Waiting** is still `rt.wait` on IDs: before the barrier the in-flight + tasks, streams and partition tasks' first pieces; after it the reducers + and the tasks after them. Finished pieces are never in the list, which + matters because `Client.wait` scans its list on every frame it reads. +- **What `next` hands out.** Nothing before the barrier. Then one + `FlowResult` per partition as it finishes, with `input` set to the + partition's index and `refs` its results (one each, from the `Reduce` or + the `Map` after it). `Flow.run` returns them by partition index. "By + input, in the read's order" becomes "by partition": inputs no longer + exist in the output. +- **Backpressure across the barrier** is the budgets before it and after + it, as today. What no budget bounds is the pieces: their count is inputs × + parts and their bytes whatever the partition functions made, held until + the reducers take them. That is what a barrier means; spilling, not + budgets, bounds it (below). +- **Determinism.** Each reducer gets its pieces in input order, not finish + order, so its floating-point sums are the same on every run and after + every rerun. + +### Memory + +- **Where pieces live.** A piece over 64 KiB (`INLINE_LIMIT`, + `Worker._finish`) stays on the worker that made it: in the node store up + to `DISTA_STORE_BYTES`, then in `DISTA_SPILL_DIR` on disk, then in memory + if both fail ("Spilling" above). Readers map it on the same host and fetch + it elsewhere. A piece of 64 KiB or less goes to the head, which keeps it + in memory until it is released and never spills it ("Roles and the + head"). Many small pieces would put the shuffle in the head's memory, so + PR 3 marks a `Partition`'s pieces to stay on their worker whatever their + size. +- **When they go.** Each piece is released by the driver when its reducer + is submitted, and freed by the head and its worker once that reducer + settles. A flow that fails releases every piece, as it releases + everything today (`FlowRun._abandon`). +- **A partition task's peak** is about three times its pieces: the result, + `split_parts`'s copy of each part, and the copy each part's `_finish` is + given (`Worker._run_many`). Worth a fix in the core if PR 5 shows it. +- **Counts for the bench.** On the local table (24 files, 589,165 groups, + `PARTS` 16): 384 pieces. Their bytes are 40 per group per input that saw + the group: between 24 MB (each group in one file) and 565 MB (every group + in every file). A piece passes 64 KiB at about 1,640 groups, which most + of a file's sixteenths are likely to have; PR 5 counts them. On + AWS (416 files, 1,044,000 groups) 96 reducers make 39,936 pieces. The head + keeps one span per settled task (`Head._close_span`, at most `MAX_SPANS`, + 1,000,000, per driver), and a `TaskMany` is one task: here 24 streams, 24 + partition tasks and 16 reducers, so spans are not the limit they were for + the embedding gate. The driver holds every piece's ID until its reducer is + submitted; the head warns past `DISTA_WARN_HELD` (100,000) objects, which + a job reaches at 6,250 inputs of 16 pieces. + +### Failures + +- **A raised error fails the flow**, at any stage, as today: everything + in flight is cancelled and everything held released, pieces included. + A partition function that returns the wrong number of pieces fails every + piece with `returned N results, not M` (`Worker._run_many`), which is a + raised error. +- **A loss before the barrier reruns the input**, with today's machinery + (`FlowRun._rerun`): a partition task whose worker died (a `TaskMany` that + had answered some parts isn't retried by the head, "Failure handling"), + or a piece lost with its worker before the reducers start, found at the + barrier. The rerun releases all `parts` pieces of the attempt. This is + most of a shuffle's exposure: the map side is the long part. +- **A loss after the barrier fails the flow in the first version**, with + `partition j lost a piece after its reducer started: dista doesn't + rebuild lost results; run the flow again`. That is today's behaviour for + a job written by hand, and the morca step repeats. +- **The later version** reruns there too: it finds the inputs whose pieces + were on the lost worker (every piece a partition task made is on its + worker), reads them again, and resubmits the reducers that failed with + their pieces. It costs three things: the driver keeps each piece's ref + until its reducer has succeeded rather than until it is submitted (no + more memory: the head keeps them until then anyway), a reducer can't be + retried until its inputs are read again (every piece of a rerun input + but the ones needed is released at once), and the executor tracks + attempts per partition as well as per input. A reducer's own result lost + before it is handed out is the same case. + +### Keys and correctness + +- **The hash is the user's, with a stable one provided.** The partition + function decides where a key goes; `dista.flow.partition_of(key, parts)` + gives a fixed one: splitmix64 of an `Int`, or FNV-1a 64 (`fnv1a64`, + already in `dista.task`) of a string's bytes, modulo `parts`. Neither is + seeded, so a key lands in the same partition in every process, on every + machine and across reruns. Mojo's `hash()` isn't documented as stable + across processes or versions, so the plan doesn't rely on it. The bench + keeps `key % PARTS`, which is stable too. +- **Key types**: whatever the user's function reads. `partition_of` takes + an `Int` or a `StringSlice`; anything else is encoded to one first. +- **Skew.** One huge key goes to one reducer. For an aggregate the combiner + makes that one row per input, not one per row; for a reduce that keeps + rows it is that reducer's memory. v1 doesn't split keys. `run.stats()` + gains the bytes of each partition's pieces, which the driver knows from + the located frames, so skew is visible. +- **Empty partitions.** A partition with no keys still has an (empty) + piece from every input, and its reducer runs on them: every index from 0 + to `parts - 1` is handed out exactly once. With no batches at all, every + reducer runs on an empty list; PR 1 checks the head takes a reducer with + no inputs. +- **The check.** Exact equality with one process, as + `tests/test_shuffle.mojo` does: integer sums exactly, every key once. + The bench keeps its rules (counts and the top 10 exactly, sums to 1e-9). + +### Groups and sizing + +- **Each operator runs in its task's group**, given on its type as for any + task: `TaskMany[..., group="..."]`, `TaskWith[..., group="..."]`. No group + by default. The read's stream cap ("Streams that hold every slot") + already counts every operator after the read in its group. +- **`parts` is a compile-time parameter**, shared with the partition + function, which gets only its argument and must return exactly `parts` + pieces. The bench's `SHUFFLE_REDUCERS` becomes `PARTS`. A runtime count + (`start(..., parts=n)`) needs the function to be told `n`, a new task + shape; it can come later without breaking this one. +- **Choosing it**: about one wave of reducers, the reduce group's slots, + up to twice that. On AWS 48 to 96 reducers were best on 6 and 12 nodes of + 16 slots, and 192 twice as slow (NUMBERS.md, 8c). + +### Not in this plan + +- Joins (two partitioned inputs meeting in one reducer), sort and range + partitioning (which need sampled boundaries), several partitions in one + flow, a partition over an unbounded input (streaming aggregation), and + `parts` chosen from the data or the cluster. The two-chain executor + leaves room for them: a join is two first chains meeting at one barrier, + a sort a `Partition` whose function takes boundaries the driver computed + from a sample, and a second partition another barrier. +- Splitting a hot key across reducers, and budgets in bytes. + +### How Ray Data does it, for comparison + +Ray Data's `groupby(key).map_groups(fn)`, its aggregations and +`repartition(n, shuffle=True)` are all-to-all operators. As far as I know +its streaming executor runs them as a barrier too: the upstream blocks all +exist before the reduce side runs, they live in Ray's object store, which +spills to disk, and lineage reconstruction rebuilds blocks lost with a node. +Groupby used a sort-based shuffle (sampled boundaries, then range +partitions); recent versions add a hash shuffle in which aggregator actors +take partitions as map blocks finish. Which version made that the default +and how it bounds memory I haven't checked. The bench's Ray side +(`bench/ray/shuffle_ray.py`) uses Ray Core tasks with `num_returns=R`, not +Ray Data, and stays the comparison; a Ray Data `groupby` run can go beside +it. + +### PRs + +| # | PR | Gate | Size | +|---|---|---|---| +| 1 | **Partition and Reduce**: the two operators, `WithLike`, `ManyLike.Part`'s bound, the checks, the two-chain executor, results by partition, raised errors failing the flow, `partition_of`. | `tests/test_flow_partition.mojo` in local mode: test_shuffle's group-by as a flow, 8 inputs of 20 batches, `parts` 4, equal to one process's `Dict`; inputs with no batches, and a partition no key reaches, each handed out once; a raising split fails the flow and leaves the stores empty; two runs give bit-identical float sums; `tests/compile_fail` cases for a `Reduce` without a `Partition`, a piece type that doesn't match, and a `Reduce` whose task doesn't take an `Int`. | ~800 | +| 2 | **Losses**: the barrier's piece check, rerun before it, the clear failure after it, per-partition bytes in `stats`. | `tests/flow_loss.sh`, partition case: the worker holding the most pieces killed before the barrier gives exact results with at least one rerun; killed while reducers run, the flow fails with the message and the stores are empty. `tests/head_restart.sh` with a partition flow restarted before its barrier finishes exact. | ~500 | +| 3 | **Pieces stay on their worker**: a flag on the task-many frames so a `Partition`'s pieces are stored whatever their size. | 2,000 pieces of 10 KB: the head's memory doesn't grow with them. With `DISTA_STORE_BYTES` room for a quarter of the pieces, the rest spill, the result is exact and the spill files are gone when the run ends. A program that doesn't set the flag sends the bytes it sent before. | ~400 | +| 4 | **bench/shuffle as a flow**: `deploy/shuffle_flow.mojo`, printing the same `ANSWER` and `TOP` lines; `bench/shuffle/README.md` updated. | `TAXI_MODE=both` passes on the local table: the flow's answer equals one process's and the hand-written version's. CI builds it. | ~300 | +| 5 | **The runs on `sai`** and their write-up in `bench/shuffle/results/`, as `bench/embed` did: the flow, the hand-written dista version and Ray (`shuffle_ray.py`) on the same table, workers and CPU sets, `PARTS` 16 and 64, 3 passes each, time and peak memory (the sum of PSS over the job's processes). Then the flow again with `DISTA_STORE_BYTES` at a quarter of the pieces' bytes. | The bars below. | write-up | + +**Bars for PR 5** (to confirm): every answer exact against one process; +the flow's median pass within 15% of the hand-written version's and no +slower than Ray's; the flow's peak memory within 10% of the hand-written +version's; with the small store, the flow finishes exact, spills, and its +workers' peak stays within the store limit plus what the hand-written +version's workers use outside the store. If the flow misses the time bar +because of the gather (an input's batches fetched to one worker), a +variant whose stream puts one item per file, as the hand-written map task +does, separates that cost from the executor's. + +The local taxi table (1.3 GB) has to be copied to `sai` for PR 5, and Ray's +environment there is the one the embedding gate used. + +### Open questions for the user + +| Question | Default, so work can proceed | +|---|---| +| A piece lost after the reducers started, in v1 | fail the flow, and the morca step repeats; rerunning there is the later version | +| What a `Partition` task takes | a whole input's batches (one task and `parts` pieces per input, with the merge as the combiner); per batch is the alternative, with batches × `parts` pieces | +| How `parts` is set | at compile time, shared with the partition function; a runtime `parts=` needs a new task shape | +| Pieces of 64 KiB or less | kept on their worker (PR 3, a frame flag); the alternative is to accept them at the head and document it | +| PR 5's bars | within 15% of the hand-written time, no slower than Ray, memory within 10%, bounded by the store when it is small |