diff --git a/CHANGELOG.md b/CHANGELOG.md index 89a74de..4d79e02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`bench/embed`:** the same job on Ray Data (`pixi run -e ray bench-embed-ray`), and `bench-embed check`, which checks any output directory. - **Keyed partitions in flows:** `dista.flow`'s `Partition` and `Reduce` run a shuffle, such as a group-by, inside a flow, with results by partition; `partition_of` is a stable hash to split by, and `WithLike` names a `TaskWith`'s element type as `Elem`. - **Losses in a flow's shuffle:** a worker lost before a `Partition`'s barrier reads the inputs whose pieces it held again; one lost after it fails the flow naming the operator and the partition; `FlowStats.partition_bytes` gives each partition's bytes (from the new `Client.size_of`); a restarted head keeps every result of a re-sent `TaskMany` a rejoining worker had made, not only its first. +- **A `Partition`'s pieces stay on their workers** whatever their size, in the store and spilling past it, not in the head's memory: `remote_many(..., keep_on_worker=True)`, which a flow's `Partition` sets. ### Changed diff --git a/DESIGN.md b/DESIGN.md index 4a65589..4a96f8d 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -100,7 +100,7 @@ Since phase 2's PR 3, scheduling lives in one place: a head process. Every progr - **The head's event loop** `poll`s the listener and every connection. Each connection is a `Conn`: reads and writes never block, input accumulates until frames are whole, and output queues until the socket takes it. A slow peer never blocks anyone else, so the phase-1 rule limiting pipelined argument size is gone. - **Every connected socket is `O_NONBLOCK`**, and `Stream`'s `write_all` and `read_into` wait in `poll` when it would block, so to the code that wants to wait they still do. Until 2026-11-02 dista used per-call `MSG_DONTWAIT` instead, because `fcntl` is variadic: Apple's arm64 ABI passes variadic arguments on the stack, a plain `external_call` puts them in registers, and `F_SETFL` silently set nothing. But macOS blocks a send with `MSG_DONTWAIT` once the socket's buffer is full, so a driver that stopped reading stalled the whole head: with 2,000 tasks of 60 KB results, 20 ran while the driver slept and the rest waited. `external_call[..., num_fixed_args=2]` declares the variadic split, as memory-region's `open` does, and now sets the flag; `tests/test_frame.mojo` fills a socket and checks the send returns. - **Scheduling:** tasks queue in arrival order. Tasks waiting on inputs are held aside until every input exists. Queued tasks go to workers round-robin, up to `pipeline` in flight each (default 2); a worker with `DISTA_WORKER_SLOTS` above 1 takes its slots plus `pipeline - 1` (see "Worker slots"). Each result or error goes back to the driver that owns it. -- **Small results go through the head; large ones stay on their worker.** A result of 64 KiB or less comes back inline. The head keeps it, because a later task may take it as input, and forwards it to the owning driver. A larger result stays on the worker that computed it. The worker reports only its size; the head records where it lives and tells the owner, using located frames. The driver's `get` fetches it straight from that worker. +- **Small results go through the head; large ones stay on their worker.** A result of 64 KiB or less comes back inline. The head keeps it, because a later task may take it as input, and forwards it to the owning driver. A larger result stays on the worker that computed it. The worker reports only its size; the head records where it lives and tells the owner, using located frames. The driver's `get` fetches it straight from that worker. A `TaskMany` submitted with `keep_on_worker=True`, as a flow's `Partition` is, keeps all its results on its worker whatever their size (`KEEP_ON_WORKER`, the top bit of its result count in the frames). - **Every worker is also an object server.** Its loop `poll`s the head, its listener, the drivers and workers fetching from it, and the workers it fetches from. A task whose inputs live elsewhere arrives as task-inputs, with each input either inline or as an address. It waits, parked, until every input has arrived, and the worker keeps serving fetches meanwhile. No worker waits on another synchronously, so two workers that need each other's results can't deadlock. With one slot, the default, running a task blocks the loop, so a fetch from a busy worker waits until its current task ends; with more, tasks run on threads and the loop keeps serving (see "Worker slots"). - **On one host, large results go through shared memory.** A worker writes each large result into a file in the node store, through memory-region's `MappedRegion`. The store is `/dev/shm` on Linux, `$TMPDIR` on macOS, or `DISTA_STORE_DIR`. Files are named `dista--`, where the token is random per worker. The location the worker reports holds its address, its host name (for diagnostics), the file's path and the exact size. A reader that can see that file maps it read-only instead of fetching it. With a random token in the name, a visible file is the right one. Host names would have been the obvious test, but on GitHub's macOS runners processes on one machine reported different ones. A worker copies the bytes into the task's argument, once, from its mapping; the driver's `get` decodes straight from the mapping. A reader on another host fetches over a socket. Workers delete their files when they exit. `DISTA_SHM=0` turns the store off. In Kubernetes each pod has its own `/dev/shm`, so pods use sockets unless they share a volume for `DISTA_STORE_DIR`. Measured: a 100 MB result goes from one worker to a second worker and to the driver in about 0.2 s, with no socket bytes. - **A cluster token** ([#124](https://github.com/magmalake/dista.mojo/issues/124), `src/dista/auth.mojo`). dista has no other authentication: anything that reached a head or a worker's object server could join, submit or fetch. With `DISTA_TOKEN` (or `DISTA_TOKEN_FILE`, its first line) set, every connection a process opens to a head or a worker starts with an `auth` frame (kind 34) carrying it, and the head and every worker's object server hand out nothing from a connection they accepted until that frame has come with the token. A missing or wrong one, or more than 8 KiB sent before it (no large frame gets a buffer of its own first), closes the connection unanswered. The comparison takes the same time wherever the bytes differ, and the token is never printed. As in Ray's token mode (`RAY_AUTH_MODE=token`), it authenticates and doesn't encrypt: a cluster still belongs on a private network, and the token keeps anything else there out. Unset, nothing changes, and an `auth` frame that arrives anyway is dropped. orca gives each run start a token of its own when one run spans machines (orca.mojo#268). @@ -1132,11 +1132,11 @@ number of inputs that will have batches isn't known before then. `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 + it elsewhere. A piece of 64 KiB or less would go 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. + size (*done*, "PR 3, as built"). - **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 @@ -1258,7 +1258,7 @@ it. |---|---|---|---| | 1 | **Done.** **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 | **Done.** **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 | +| 3 | **Done.** **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 | @@ -1325,6 +1325,68 @@ it. it, and fails the flow. The window is the time between the worker going and the head's error reaching the driver. +**PR 3, as built.** What differs from the plan above, and why: + +- **The flag on the wire** is the top bit of the `TaskMany`'s result count + (`KEEP_ON_WORKER`, 1 << 63, in `dista/frame.mojo`), not a new bit in the + flags byte or a trailing field. The count is the one field every frame + that runs a `TaskMany` carries: task-many (driver to head and head to + worker), and task-after and task-inputs with `MANY`. Task-many has no + flags byte, and a trailing field would sit after the encoded argument, + which has no length. The count is at most 2^20, so the bit was always 0: + a program that doesn't set the flag sends the frames it sent before, byte + for byte (`tests/test_partition_keep.mojo` compares them with the layout + written out by hand), and a head or worker from before the flag would + refuse a flagged count as out of range rather than misread it. Only one + binary runs on every node, so nothing more is done for mixed versions. +- **Where it travels.** The driver's frame carries it; the head keeps it + with a waiting task (`_Task.keep`) and writes it into the count of the + task-many or task-inputs frame it sends the worker, so a task retried on + another worker after its worker is lost keeps it, and a task-many frame + goes on as it came. The driver keeps each submission's payload to send + again after a head restart (`Client._subs`), so a re-sent task carries it + too. The worker reads it from the count and stores every result of the + task (`Worker._finish`), in the node store and past `DISTA_STORE_BYTES` + in the spill directory, as for a large result. +- **An empty piece still goes to the head**: the node store can't map an + empty file (`SharedMapping` refuses one). A `Seq` is never empty when + encoded, so a `Partition`'s pieces never are. +- **The API**: `remote_many(..., keep_on_worker=False)`, a keyword-only + argument on all three forms of `Client.remote_many` and + `Runtime.remote_many`, so every existing call is unchanged. `Partition` + passes `True`; nothing else does. +- **Sizes and the barrier** work as before: a kept piece's size comes from + its located frame (`Client.size_of`, `Location.size`), so + `FlowStats.partition_bytes` still counts every piece, and the worker still + answers a `TaskMany`'s pieces last first, so the first piece settled + still means all are. +- **Measured** (`tests/test_partition_keep.mojo`, local mode, 2 workers), + the head's resident memory grown from its start once every piece is made + and none released: 496 pieces of 10 KB, 6.5 MB without the flag and + 0.9 MB with it; 2,000 pieces, 24.1 MB and 1.9 MB (macOS); on `sai` + (Linux), 8.6 and 0.6 MB, then 20.9 and 0.8 MB. What is left with the flag + is a location and a span per piece. The head's stats say it exactly: + without the flag it holds 2,000 small results, with it none and 2,000 + locations. The test checks the counts; the memory is printed, since a + threshold on it would be flaky. +- **A cost for PR 5 to measure**: a kept piece is a file written per piece, + and a reducer on another host fetches each of its pieces from the worker + that made it, where a small one used to come inline in its task-inputs + frame from the head: 416 small fetches per reducer on AWS. A reader on + the same host maps them. +- **A lost worker now loses its small pieces too**, which used to be safe + at the head, so a loss before the barrier reads again every input whose + pieces that worker held, not only the one it was running: one test that + expected exactly one rerun (`tests/test_flow_partition.mojo`, a partition + task's worker dying) now expects at least one, with every input read once + more per rerun. This is the plan's loss model for every piece over + 64 KiB already. +- **After a head restart** a kept piece is claimed back rather than re-sent + with its bytes, so until its worker says where it is it has no size, and + counts in `FlowStats.unsized_pieces` (`tests/head_restart.sh`'s partition + flow shows 4); before, small pieces always had one. +- `_run_many`'s three copies of a partition task's pieces are as they were. + **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 diff --git a/README.md b/README.md index 503a0ef..7087f03 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ What works today: - **Several tasks per worker:** `DISTA_WORKER_SLOTS=N` (0 for one per core) runs up to N tasks at once on a worker's threads, while it keeps serving its results; the default, 1, runs one at a time. N slots hold N tasks' inputs and results, and tasks must be thread-safe ([tests/test_slots.mojo](tests/test_slots.mojo)). - **Worker groups:** a task type with `group="gpu"` (`Task`, `Task2`, `Task3`, `TaskWith`, `TaskMany`, `TaskStream`, `StatefulTask`) runs only on workers started with `DISTA_GROUP=gpu`, and a task without one only on workers without one. In local mode, `Runtime(workers=4, groups="gpu=1")` forks a worker of group `gpu` beside the four; a task of a group with no worker fails there at once, and waits in a cluster. `dista status` shows each worker's group ([tests/test_groups.mojo](tests/test_groups.mojo)). An `Actor` with `group=` is placed, restored and moved only on workers of its group, and `dista drain` refuses the last worker of a group while tasks of it are queued. `dista status --json` and the head's `/metrics` count each group's workers, slots and tasks (`groups`, `dista_group_*{group=...}`), and `dista scale --once --group gpu` decides for one group alone ([tests/autoscale.sh](tests/autoscale.sh) `groups`). - **Sizing from the grant:** `DISTA_WORKER_SLOTS=auto` takes a worker's slots from the run's grant (`MORCA_GRANT_CPUS`, shared by a local run's workers) and runs only the tasks that fit the grant's `MORCA_GRANT_MEMORY_MB` (each at `DISTA_TASK_MEMORY_MB`, or what its footprint shows): the rest wait at the head for a worker with room, and the store spills at half of it. It starts at one task in flight and raises the count while throughput rises, backing off on memory pressure, spills or slower tasks, and learns what a task takes from the ones that ran alone, so no size need be given ([tests/test_sizing.mojo](tests/test_sizing.mojo)). -- **Large results stay on the worker that made them.** On the same host other processes map them from shared memory; across hosts they fetch them directly from that worker. Small ones come back through the head. +- **Large results stay on the worker that made them.** On the same host other processes map them from shared memory; across hosts they fetch them directly from that worker. Small ones come back through the head, except a `TaskMany`'s with `rt.remote_many(..., keep_on_worker=True)`, as a flow's `Partition` submits its own: those stay on their worker too, and spill, so a shuffle's many small pieces aren't held by the head ([tests/test_partition_keep.mojo](tests/test_partition_keep.mojo)). - **Spilling:** past `DISTA_STORE_BYTES` of results, or when the store is full, a worker writes the rest to `DISTA_SPILL_DIR` on disk, and readers map or fetch them as before ([tests/test_spill.mojo](tests/test_spill.mojo)). - **Data-aware scheduling:** a task goes to the node holding most of its inputs' bytes, unless that node has no worker free ([tests/locality.sh](tests/locality.sh)). - **Speed:** small tasks cost about 6 µs each. diff --git a/pixi.toml b/pixi.toml index e73cf57..a8fa319 100644 --- a/pixi.toml +++ b/pixi.toml @@ -36,6 +36,7 @@ test-cancel = { cmd = "sh scripts/test.sh test_cancel" } test-wait = { cmd = "sh scripts/test.sh test_wait" } test-stream = { cmd = "sh scripts/test.sh test_stream" } test-flow = { cmd = "sh scripts/test.sh test_flow" } +test-partition-keep = { cmd = "sh scripts/test.sh test_partition_keep" } test-stateful = { cmd = "sh scripts/test.sh test_stateful" } test-groups = { cmd = "sh scripts/test.sh test_groups" } test-head-drivers = { cmd = "sh scripts/test.sh test_head_drivers" } diff --git a/src/dista/client.mojo b/src/dista/client.mojo index f291734..d88e22c 100644 --- a/src/dista/client.mojo +++ b/src/dista/client.mojo @@ -60,6 +60,7 @@ from dista.frame import ( check_payload, decode_addr, fetch_payload, + many_word, read_frame, write_frame, append_frame, @@ -723,13 +724,20 @@ struct Client(Movable): def remote_many[ T: ManyLike - ](mut self, arg: T.A, n: Int) raises -> List[ObjectRef[T.Part]]: + ]( + mut self, arg: T.A, n: Int, *, keep_on_worker: Bool = False + ) raises -> List[ObjectRef[T.Part]]: """Submits task `T`, a `TaskMany`, on `arg`, for `n` results: each is - an object of its own, the `n` values of the `Seq` it returns.""" + an object of its own, the `n` values of the `Seq` it returns. + + With `keep_on_worker`, every result stays on the worker that made it, + however small, rather than going to the head and this driver + (`KEEP_ON_WORKER`): a shuffle's many small pieces then live in the + workers' stores, which spill, not in the head's memory.""" if n < 1: raise Error("remote_many needs at least one result") var body = List[UInt8]() - put_scalar[DType.uint64](body, UInt64(n)) + put_scalar[DType.uint64](body, many_word(n, keep_on_worker)) encode(arg, body) var refs = List[ObjectRef[T.Part]](capacity=n) for _ in range(n): @@ -741,37 +749,58 @@ struct Client(Movable): def remote_many[ T: ManyLike - ](mut self, arg: ObjectRef[T.A], n: Int) raises -> List[ObjectRef[T.Part]]: + ]( + mut self, + arg: ObjectRef[T.A], + n: Int, + *, + keep_on_worker: Bool = False, + ) raises -> List[ObjectRef[T.Part]]: """Submits task `T`, a `TaskMany`, to run on another task's result - once it exists, for `n` results.""" - return self._submit_many_after[T.Part](T.id(), [arg.id], False, n) + once it exists, for `n` results; `keep_on_worker` as for the first + form.""" + return self._submit_many_after[T.Part]( + T.id(), [arg.id], False, n, keep_on_worker + ) def remote_many[ X: AnyType, //, T: ManyLike - ](mut self, args: List[ObjectRef[X]], n: Int) raises -> List[ - ObjectRef[T.Part] - ]: + ]( + mut self, + args: List[ObjectRef[X]], + n: Int, + *, + keep_on_worker: Bool = False, + ) raises -> List[ObjectRef[T.Part]]: """Submits task `T`, a `TaskMany` taking a `Seq[X]`, to run on these results once they all exist, for `n` results: a shuffle's second - stage, partitioning what the first made.""" + stage, partitioning what the first made. `keep_on_worker` as for the + first form; a flow's `Partition` sets it.""" comptime assert ( reflect[T.A].base_name() == "Seq" ), "a task given a list of ObjectRefs must take a Seq" var deps = List[UInt64](capacity=len(args)) for r in args: deps.append(r.id) - return self._submit_many_after[T.Part](T.id(), deps, True, n) + return self._submit_many_after[T.Part]( + T.id(), deps, True, n, keep_on_worker + ) def _submit_many_after[ X: AnyType ]( - mut self, task_id: UInt64, deps: List[UInt64], gather: Bool, n: Int + mut self, + task_id: UInt64, + deps: List[UInt64], + gather: Bool, + n: Int, + keep_on_worker: Bool = False, ) raises -> List[ObjectRef[X]]: if n < 1: raise Error("remote_many needs at least one result") var flags = MANY | (GATHER if gather else UInt8(0)) var body: List[UInt8] = [flags] - put_scalar[DType.uint64](body, UInt64(n)) + put_scalar[DType.uint64](body, many_word(n, keep_on_worker)) put_scalar[DType.uint64](body, UInt64(len(deps))) for d in deps: put_scalar[DType.uint64](body, d) diff --git a/src/dista/executors.mojo b/src/dista/executors.mojo index 9e39ea8..64ff250 100644 --- a/src/dista/executors.mojo +++ b/src/dista/executors.mojo @@ -115,6 +115,9 @@ struct Job(Movable): var window: Int """A `TaskStream`'s window: how many items it may put that its driver hasn't taken; 0, any.""" + var keep: Bool + """A `TaskMany` whose results stay on the worker whatever their size + (`KEEP_ON_WORKER`).""" var started: UInt64 var ended: UInt64 var ok: Bool @@ -131,6 +134,7 @@ struct Job(Movable): many: Int = 0, epoch: Int = 0, window: Int = 0, + keep: Bool = False, ): self.object_id = object_id self.task_id = task_id @@ -140,6 +144,7 @@ struct Job(Movable): self.many = many self.epoch = epoch self.window = window + self.keep = keep self.started = 0 self.ended = 0 self.ok = False diff --git a/src/dista/flow.mojo b/src/dista/flow.mojo index bec222c..bc0466e 100644 --- a/src/dista/flow.mojo +++ b/src/dista/flow.mojo @@ -258,7 +258,11 @@ struct Partition[T: ManyLike, parts: Int, budget: Int = 4](OpLike): var refs = List[ObjectRef[NoneType]](capacity=len(inputs)) for id in inputs: refs.append(ObjectRef[NoneType](id)) - return c.remote_many[Self.T](refs, Self.parts)[0].id + # Its pieces stay on their workers however small, so a shuffle's + # many small pieces aren't held by the head (`KEEP_ON_WORKER`). + return c.remote_many[Self.T](refs, Self.parts, keep_on_worker=True)[ + 0 + ].id struct Reduce[T: WithLike, budget: Int = 16](OpLike): diff --git a/src/dista/frame.mojo b/src/dista/frame.mojo index 1d2ad5d..1d64296 100644 --- a/src/dista/frame.mojo +++ b/src/dista/frame.mojo @@ -16,7 +16,7 @@ Every frame is a 4-byte little-endian length, then that many bytes: | 3 error | worker to head, head to driver | a UTF-8 message | | 4 hello | driver, worker or observer to head | role byte (`ROLE_*`), the registry hash u64 (an observer's is ignored); a worker adds its object server's address, then its slots u64 when not 1, or when it has a group, then its group as a length byte and the name | | 5 welcome | head to driver | the driver's number, u64, then the head's epoch, u64 | -| 6 task-after | driver to head | flags byte (`GATHER`, `WITH_VALUE`, `MANY`, `STREAM`), with `MANY` the result count u64 or with `STREAM` the window u64, count u64, then that many object IDs; with `WITH_VALUE`, a length u64 and the encoded value | +| 6 task-after | driver to head | flags byte (`GATHER`, `WITH_VALUE`, `MANY`, `STREAM`), with `MANY` the result count u64 (its top bit `KEEP_ON_WORKER`) or with `STREAM` the window u64, count u64, then that many object IDs; with `WITH_VALUE`, a length u64 and the encoded value | | 7 stored | worker to head | the result's size, u64: it stayed on the worker | | 8 located | head to driver | the address of the worker holding the result | | 9 fetch | driver or worker to a worker | none, or the largest part the fetcher takes, u64: send that object back as a result frame, or if it's larger than that part, as part frames | @@ -38,7 +38,7 @@ Every frame is a 4-byte little-endian length, then that many bytes: | 25 covered | head to driver | the newest of this driver's calls to the actor a checkpoint now includes, u64; the object ID names the actor | | 26 status | observer to head, head to observer | none; the reply is the head's state as UTF-8 text | | 27 stop | observer to head, head to worker | none: shut down; a worker exits instead of rejoining | -| 28 task-many | driver to head, head to worker | the number of results u64, then the encoded argument; the results are this object ID and the ones after it | +| 28 task-many | driver to head, head to worker | the number of results u64 (its top bit `KEEP_ON_WORKER`), then the encoded argument; the results are this object ID and the ones after it | | 29 drain | worker to head | none: the worker was told to stop; it takes no more work, and leaves once the head says stop | | 30 adopt | head to worker | a draining worker's location of the object: fetch it and keep it | | 31 adopted | worker to head | 1 and the object's new location, or 0 and why not | @@ -116,6 +116,15 @@ some of those results live on workers, the head sends the task as task-inputs, and the worker fetches them before it runs the task. An address is 12 bytes: the IPv4 address, then the port as a u64. +Every frame that runs a `TaskMany` (task-many, and task-after and +task-inputs with `MANY`) carries its number of results as a u64, which is at +most 2^20. Its top bit, `KEEP_ON_WORKER`, says the results stay on the +worker that made them whatever their size: answered with stored frames, not +result frames, so the head never holds their bytes (a `Partition`'s pieces, +`remote_many(..., keep_on_worker=True)`). An empty result still goes as a +result frame, since the node store can't map an empty file. Without it the +count, and so the frame, is what it was before the flag. + A task-stream frame runs a `TaskStream`. Its worker answers each item as it is put, with a result or stored frame for the item's ID whose task ID is the stream's own, so the head knows which stream it belongs to. Item `k` is the @@ -214,6 +223,12 @@ of its results, a u64, follows the flags byte.""" comptime STREAM: UInt8 = 8 """Task-after and task-inputs flag: the task is a `TaskStream`, and its window, a u64, follows the flags byte.""" +comptime KEEP_ON_WORKER: UInt64 = 1 << 63 +"""The top bit of a `TaskMany`'s result count, in the task-many, task-after +and task-inputs frames: its results stay on the worker that made them, +whatever their size.""" +comptime MAX_MANY = 1 << 20 +"""The most results a `TaskMany` may have.""" comptime ADDR_SIZE = 12 comptime ROLE_DRIVER: UInt8 = 1 comptime ROLE_WORKER: UInt8 = 2 @@ -235,6 +250,25 @@ comptime MAX_OBJECT = 1 << 40 """A part frame announcing an object larger than this is garbage.""" +def many_word(n: Int, keep_on_worker: Bool) -> UInt64: + """A `TaskMany`'s result count as frames carry it: `n`, with + `KEEP_ON_WORKER` set if its results stay on their worker.""" + var w = UInt64(n) + if keep_on_worker: + w |= KEEP_ON_WORKER + return w + + +def parse_many(word: UInt64) raises -> Tuple[Int, Bool]: + """A `TaskMany`'s result count and whether its results stay on their + worker, from the u64 `many_word` wrote; a count outside 1 to `MAX_MANY` + raises.""" + var n = Int(word & ~KEEP_ON_WORKER) + if n < 1 or n > MAX_MANY: + raise Error("bad result count ", n) + return (n, (word & KEEP_ON_WORKER) != 0) + + def message(payload: Span[UInt8, _]) -> String: """An error frame's text. It comes from another process, so bytes that aren't UTF-8 become replacement characters instead of a broken String.""" diff --git a/src/dista/head.mojo b/src/dista/head.mojo index 1ef1e23..7b81105 100644 --- a/src/dista/head.mojo +++ b/src/dista/head.mojo @@ -186,6 +186,8 @@ from dista.frame import ( ROLE_OBSERVER, ROLE_WORKER, decode_addr, + many_word, + parse_many, Frame, ) from dista.socket import ( @@ -295,6 +297,9 @@ struct _Task(Copyable, Movable): var window: Int """A `TaskStream` submitted on other results: its window; -1 for any other task.""" + var keep: Bool + """A waiting `TaskMany` whose results stay on their worker whatever their + size (`KEEP_ON_WORKER`), sent on in its result count.""" def __init__( out self, @@ -307,6 +312,7 @@ struct _Task(Copyable, Movable): var node: String = String(), many: Int = 0, window: Int = -1, + keep: Bool = False, ): self.object_id = object_id self.task_id = task_id @@ -317,6 +323,7 @@ struct _Task(Copyable, Movable): self.node = node^ self.many = many self.window = window + self.keep = keep def is_stream(self) -> Bool: """Whether it runs a `TaskStream`: a task-stream, or task-inputs @@ -1659,12 +1666,15 @@ struct Head(Movable): var gather = (flags & GATHER) != 0 var pos = 1 var many = 0 + var keep = False if flags & MANY: if len(f.payload) < 17: raise Error("truncated task-after") - many = Int(get_scalar[DType.uint64](f.payload, pos)) - if many < 1 or many > 1 << 20: - raise Error("task-after with a bad result count ", many) + var word = get_scalar[DType.uint64](f.payload, pos) + try: + many, keep = parse_many(word) + except e: + raise Error("task-after with a ", e) var last = f.object_id + UInt64(many - 1) if owner_of(last) != owner_of(f.object_id): raise Error("task-many results run past their IDs") @@ -1735,6 +1745,7 @@ struct Head(Movable): gather=gather, many=many, window=window, + keep=keep, ) elif f.kind == KIND_TASK_MANY: self._task_many(f^) @@ -2017,9 +2028,13 @@ struct Head(Movable): if len(f.payload) < 8: raise Error("truncated task-many") var pos = 0 - var n = Int(get_scalar[DType.uint64](f.payload, pos)) - if n < 1 or n > 1 << 20: - raise Error("task-many with a bad result count ", n) + # Its top bit, `KEEP_ON_WORKER`, is the worker's: the payload goes on + # as it came. + var n: Int + try: + n = parse_many(get_scalar[DType.uint64](f.payload, pos))[0] + except e: + raise Error("task-many with a ", e) var first = f.object_id if owner_of(first + UInt64(n - 1)) != owner_of(first): raise Error("task-many results run past their driver's IDs") @@ -3428,7 +3443,7 @@ struct Head(Movable): # A `TaskMany` runs on its number of results, then the input. var args = List[UInt8]() if t.many > 0: - put_scalar[DType.uint64](args, UInt64(t.many)) + put_scalar[DType.uint64](args, many_word(t.many, t.keep)) if t.window >= 0: # A `TaskStream` runs on its window, then the input. put_scalar[DType.uint64](args, UInt64(t.window)) @@ -3467,7 +3482,7 @@ struct Head(Movable): flags |= STREAM var spec: List[UInt8] = [flags] if t.many > 0: - put_scalar[DType.uint64](spec, UInt64(t.many)) + put_scalar[DType.uint64](spec, many_word(t.many, t.keep)) if t.window >= 0: put_scalar[DType.uint64](spec, UInt64(t.window)) put_scalar[DType.uint64](spec, UInt64(len(t.deps))) diff --git a/src/dista/runtime.mojo b/src/dista/runtime.mojo index aaad5a9..1d9dce0 100644 --- a/src/dista/runtime.mojo +++ b/src/dista/runtime.mojo @@ -458,36 +458,53 @@ struct Runtime[*Ts: TaskLike](Movable): def remote_many[ T: ManyLike - ](mut self, arg: T.A, n: Int) raises -> List[ObjectRef[T.Part]]: + ]( + mut self, arg: T.A, n: Int, *, keep_on_worker: Bool = False + ) raises -> List[ObjectRef[T.Part]]: """Submits task `T`, a `TaskMany`, on `arg`, for `n` results: each is an object of its own, stored, fetched and freed on its own. A shuffle's map task takes this shape: one partition per reducer. + A result of 64 KiB or less goes to the head and this driver, as any + task's does; with `keep_on_worker` every result stays on the worker + that made it, in its store, which spills: for many small pieces. """ Self._check_registered[T]() - return self._c.remote_many[T](arg, n) + return self._c.remote_many[T](arg, n, keep_on_worker=keep_on_worker) def remote_many[ T: ManyLike - ](mut self, arg: ObjectRef[T.A], n: Int) raises -> List[ObjectRef[T.Part]]: + ]( + mut self, + arg: ObjectRef[T.A], + n: Int, + *, + keep_on_worker: Bool = False, + ) raises -> List[ObjectRef[T.Part]]: """Submits task `T`, a `TaskMany`, to run on another task's result - once it exists, for `n` results.""" + once it exists, for `n` results; `keep_on_worker` as for the first + form.""" Self._check_registered[T]() - return self._c.remote_many[T](arg, n) + return self._c.remote_many[T](arg, n, keep_on_worker=keep_on_worker) def remote_many[ X: AnyType, //, T: ManyLike - ](mut self, args: List[ObjectRef[X]], n: Int) raises -> List[ - ObjectRef[T.Part] - ]: + ]( + mut self, + args: List[ObjectRef[X]], + n: Int, + *, + keep_on_worker: Bool = False, + ) raises -> List[ObjectRef[T.Part]]: """Submits task `T`, a `TaskMany` taking a `Seq[X]`, to run on these - results once they exist, for `n` results. + results once they exist, for `n` results; `keep_on_worker` as for the + first form. A shuffle's later stage takes this shape: it partitions again what earlier tasks made, without the driver fetching it. """ Self._check_registered[T]() - return self._c.remote_many[T](args, n) + return self._c.remote_many[T](args, n, keep_on_worker=keep_on_worker) def stream[ T: StreamLike diff --git a/src/dista/worker.mojo b/src/dista/worker.mojo index c93503d..2ce3172 100644 --- a/src/dista/worker.mojo +++ b/src/dista/worker.mojo @@ -115,6 +115,9 @@ from dista.frame import ( encode_addr, fetch_part, fetch_payload, + KEEP_ON_WORKER, + many_word, + parse_many, part_payload_size, ) from dista.checkpoint import ( @@ -256,6 +259,8 @@ struct TaskInputs(Movable): """A `TaskWith`'s value, which goes before the inputs; or empty.""" var window: Int """A `TaskStream`'s window; -1 for any other task.""" + var keep: Bool + """A `TaskMany` whose results stay here whatever their size.""" def parse_task_inputs(payload: Span[UInt8, _]) raises -> TaskInputs: @@ -266,10 +271,12 @@ def parse_task_inputs(payload: Span[UInt8, _]) raises -> TaskInputs: var gather = (flags & GATHER) != 0 var pos = 1 var many = 0 + var keep = False if flags & MANY: - many = Int(get_scalar[DType.uint64](payload, pos)) - if many < 1 or many > 1 << 20: - raise Error("bad task-inputs result count ", many) + try: + many, keep = parse_many(get_scalar[DType.uint64](payload, pos)) + except e: + raise Error("bad task-inputs: ", e) var window = -1 if flags & STREAM: if flags & MANY or len(payload) - pos < 16: @@ -313,7 +320,7 @@ def parse_task_inputs(payload: Span[UInt8, _]) raises -> TaskInputs: value = List[UInt8](payload[pos:]) elif pos != len(payload): raise Error("task-inputs with ", len(payload) - pos, " bytes left over") - return TaskInputs(many, gather, inputs^, value^, window) + return TaskInputs(many, gather, inputs^, value^, window, keep) struct _Input(Movable): @@ -390,6 +397,8 @@ struct _Parked(Movable): """A `TaskMany`'s number of results; 0 for any other task.""" var window: Int """A `TaskStream`'s window; -1 for any other task.""" + var keep: Bool + """A `TaskMany` whose results stay here whatever their size.""" def __init__( out self, @@ -400,11 +409,13 @@ struct _Parked(Movable): var value: List[UInt8], many: Int = 0, window: Int = -1, + keep: Bool = False, ): self.object_id = object_id self.task_id = task_id self.many = many self.window = window + self.keep = keep self.gather = gather self.inputs = inputs^ self.value = value^ @@ -1009,6 +1020,7 @@ struct Worker[ spec.value.copy(), many, window, + spec.keep, ) ) elif f.kind == KIND_STOP: @@ -1418,7 +1430,7 @@ struct Worker[ args.reserve(size) # A `TaskMany` runs on its number of results, then the input. if p.many > 0: - put_scalar[DType.uint64](args, UInt64(p.many)) + put_scalar[DType.uint64](args, many_word(p.many, p.keep)) if p.window >= 0: # A `TaskStream` runs on its window, then the input. put_scalar[DType.uint64](args, UInt64(p.window)) @@ -1993,6 +2005,7 @@ struct Worker[ ) continue var many = 0 + var keep = False var args = t.args^ t.args = List[UInt8]() if kind == KIND_TASK_MANY: @@ -2000,7 +2013,10 @@ struct Worker[ self._report_error(t.object_id, "a truncated TaskMany") continue var pos = 0 - many = Int(get_scalar[DType.uint64](args, pos)) + # Checked by the head; its top bit says where results go. + var word = get_scalar[DType.uint64](args, pos) + many = Int(word & ~KEEP_ON_WORKER) + keep = (word & KEEP_ON_WORKER) != 0 var rest = List[UInt8](args[8:]) args = rest^ elif kind == KIND_TASK_STREAM: @@ -2027,6 +2043,7 @@ struct Worker[ many, self._epoch, window, + keep, ), halted=self._stops.pop(t.object_id, False), ) @@ -2079,7 +2096,13 @@ struct Worker[ self._span(obj, j.arrived, j.started) self._report_error(obj, why) else: - self._finish(obj, j.arrived, j.started, parts[k].copy()) + self._finish( + obj, + j.arrived, + j.started, + parts[k].copy(), + keep=j.keep, + ) elif j.ok: var out = List[UInt8]() swap(out, j.out) @@ -2127,11 +2150,15 @@ struct Worker[ var first = t.object_id var started = wall_ns() var n = 0 + var keep = False var parts = List[List[UInt8]]() var why = String() try: var pos = 0 - n = Int(get_scalar[DType.uint64](t.args, pos)) + # Checked by the head; its top bit says where results go. + var word = get_scalar[DType.uint64](t.args, pos) + n = Int(word & ~KEEP_ON_WORKER) + keep = (word & KEEP_ON_WORKER) != 0 var out = List[UInt8]() Self.dispatch(t.task_id, List[UInt8](t.args[8:]), out, self._ctx) parts = split_parts(out) @@ -2147,7 +2174,9 @@ struct Worker[ self._span(obj, t.arrived, started) self._report_error(obj, why) else: - self._finish(obj, t.arrived, started, parts[k].copy()) + self._finish( + obj, t.arrived, started, parts[k].copy(), keep=keep + ) def _run_stream(mut self, var t: _Ready): """Runs a `TaskStream` on the loop's thread: each `put` stores and @@ -2243,10 +2272,13 @@ struct Worker[ started: UInt64, var out: List[UInt8], stream: UInt64 = 0, + keep: Bool = False, ): """Sends a small result to the head, or stores a large one here. A - stream's item (`stream` its ID) has no span of its own.""" - if len(out) <= INLINE_LIMIT: + stream's item (`stream` its ID) has no span of its own. With `keep` + (`KEEP_ON_WORKER`) a small result is stored here too, unless it's + empty: the store can't map an empty file.""" + if len(out) <= INLINE_LIMIT and (not keep or len(out) == 0): if stream == 0: self._span(obj, arrived, started) self._to_head(KIND_RESULT, obj, out, stream) diff --git a/tests/test_flow_partition.mojo b/tests/test_flow_partition.mojo index fc4cbbb..8621d68 100644 --- a/tests/test_flow_partition.mojo +++ b/tests/test_flow_partition.mojo @@ -507,7 +507,9 @@ def _fresh_dir() raises: def test_a_partition_task_whose_worker_dies_reads_its_input_again() raises: """With `DISTA_TASK_RETRIES=0` the head doesn't run the killed task again, and fails its pieces with a loss: the flow reads input 3 again, - makes its pieces again, and the result is exact.""" + makes its pieces again, and the result is exact. The pieces of other + inputs that worker made are lost with it (they stay on their worker, + `KEEP_ON_WORKER`), so the barrier may read those inputs again too.""" _fresh_dir() _ = setenv("DISTA_TASK_RETRIES", "0") var rt = Runtime[RowsOf, SplitDyingOnce, ReduceRows](workers=6) @@ -525,9 +527,10 @@ def test_a_partition_task_whose_worker_dies_reads_its_input_again() raises: got[done.input] = rt.take(done.refs[0]) var st = run.stats() print(" ", st) - assert_equal(st.ops[1].reruns, 1, String(st)) - assert_equal(st.ops[0].submitted, INPUTS + 1, String(st)) - assert_equal(st.ops[1].submitted, INPUTS + 1, String(st)) + var reruns = st.ops[1].reruns + assert_true(reruns >= 1, String(st)) + assert_equal(st.ops[0].submitted, INPUTS + reruns, String(st)) + assert_equal(st.ops[1].submitted, INPUTS + reruns, String(st)) _assert_exact(got, _want(_inputs(INPUTS)), False) _assert_empty(rt) diff --git a/tests/test_partition_keep.mojo b/tests/test_partition_keep.mojo new file mode 100644 index 0000000..074423d --- /dev/null +++ b/tests/test_partition_keep.mojo @@ -0,0 +1,674 @@ +"""A `TaskMany`'s results kept on their worker whatever their size: the +`KEEP_ON_WORKER` bit of the result count, which a flow's `Partition` sets. + +The frames first, with no processes: a program that doesn't set the flag +sends the bytes it sent before, and the head passes the flag on to the +worker in each frame that runs a `TaskMany`, again when it retries one on +another worker. Then in local mode: 2,000 pieces of 10 KB made with the flag +leave the head holding none of them, where without it the head holds all +2,000 (the head's resident memory is printed for both, at 496 and 2,000 +pieces, as evidence: it isn't asserted, since Mojo's stays at its peak and +thresholds on it are flaky); a flow's `Partition` of 125 inputs into 16 +pieces each keeps its pieces on the workers and its result is exact; and +with the store's room a quarter of the pieces, the rest spill, the result +is exact, and the store and the spill directory are empty once the run +ends.""" + +from std.ffi import c_int, external_call +from std.os import listdir, makedirs, remove, setenv, unsetenv +from std.os.path import exists +from std.sys import CompilationTarget +from std.testing import TestSuite, assert_equal, assert_false, assert_true +from std.time import sleep + +from dista import Emit, ObjectRef, Runtime, Seq, TaskLike, TaskMany +from dista import TaskStream +from dista import TaskWith +from dista.client import Client, HeadStats +from dista.codec import get_scalar, put_scalar +from dista.conn import Conn +from dista.flow import Flow, Partition, Read, Reduce, partition_of +from dista.frame import ( + GATHER, + KEEP_ON_WORKER, + KIND_HELLO, + KIND_RESULT, + KIND_STORED, + KIND_TASK, + KIND_TASK_AFTER, + KIND_TASK_INPUTS, + KIND_TASK_MANY, + KIND_WELCOME, + MANY, + MAX_MANY, + ROLE_DRIVER, + ROLE_WORKER, + Frame, + encode_addr, + many_word, + parse_many, + read_frame, + write_frame, +) +from dista.head import DRIVER_SHIFT, Head +from dista.socket import Listener, Stream, stream_pair +from dista.store import Location +from dista.worker import parse_task_inputs + +comptime HASH: UInt64 = 0x5EED +comptime PARTS = 16 +comptime PIECE = 10_000 +"""Bytes of each piece's string in the hand-written runs.""" +comptime INPUTS = 125 +"""Inputs of the flows: 125 × 16 = 2,000 pieces.""" +comptime KEYS = 6_800 +"""Keys of every input: 425 a piece, about 10 KB of rows.""" +comptime STORE = "build/test-partition-keep-store" +comptime SPILL = "build/test-partition-keep-spill" + + +# ---- The tasks ---- + + +def make_pieces(m: Int) raises -> Seq[String]: + """Task `m`'s 16 pieces of 10 KB, each its own letter.""" + var out = Seq[String]() + for j in range(PARTS): + out.append(String(chr(65 + (m + j) % 26)) * PIECE) + return out^ + + +@fieldwise_init +struct Row(Copyable, Movable): + """A key's count and integer sum.""" + + var key: Int + var count: Int + var total: Int + + +def value(m: Int, k: Int) -> Int: + return (m * 31 + k * 7) % 100 + + +def _rows(m: Int, batches: Int, mut out: Emit[Seq[Row]]) raises: + """Input `m`'s row for every key, in `batches` batches.""" + var per = KEYS // batches + for b in range(batches): + var batch = Seq[Row]() + for k in range(b * per, (b + 1) * per): + batch.append(Row(k, 1, value(m, k))) + out.put(batch) + + +def small_batches(m: Int, mut out: Emit[Seq[Row]]) raises: + """4 batches of 1,700 rows, small enough to go through the head.""" + _rows(m, 4, out) + + +def large_batches(m: Int, mut out: Emit[Seq[Row]]) raises: + """2 batches of 3,400 rows, over 64 KiB: they stay on their workers, so + the partition task runs from a task-inputs frame.""" + _rows(m, 2, out) + + +def split_rows(batches: Seq[Seq[Row]]) raises -> Seq[Seq[Row]]: + """An input's rows into `PARTS` pieces by `partition_of` of the key.""" + var parts = List[Seq[Row]]() + for _ in range(PARTS): + parts.append(Seq[Row]()) + for b in range(len(batches)): + ref batch = batches.items[b] + for i in range(len(batch)): + ref r = batch.items[i] + parts[partition_of(r.key, PARTS)].append(r.copy()) + return Seq[Seq[Row]](parts^) + + +def reduce_rows(j: Int, pieces: Seq[Seq[Row]]) raises -> Seq[Row]: + """Partition `j`'s pieces, merged per key.""" + var sums = Dict[Int, Row]() + for p in range(len(pieces)): + ref piece = pieces.items[p] + for i in range(len(piece)): + ref r = piece.items[i] + if r.key in sums: + ref s = sums[r.key] + s.count += r.count + s.total += r.total + else: + sums[r.key] = r.copy() + var out = Seq[Row]() + for entry in sums.items(): + out.append(entry.value.copy()) + return out^ + + +def piece_of(k: Int, pieces: Seq[String]) raises -> Int: + """Piece `k`'s length, read by a task.""" + return pieces.items[k].byte_length() + + +comptime MakePieces = TaskMany[Int, String, make_pieces] +comptime PieceOf = TaskWith[Int, String, Int, piece_of] +comptime SmallBatches = TaskStream[Int, Seq[Row], small_batches] +comptime LargeBatches = TaskStream[Int, Seq[Row], large_batches] +comptime SplitRows = TaskMany[Seq[Seq[Row]], Seq[Row], split_rows] +comptime ReduceRows = TaskWith[Int, Seq[Row], Seq[Row], reduce_rows] + + +comptime Small = Flow[ + Read[SmallBatches], Partition[SplitRows, PARTS], Reduce[ReduceRows, 1] +] +"""One reducer at a time, so the pieces wait at the barrier.""" +comptime Large = Flow[ + Read[LargeBatches], Partition[SplitRows, PARTS], Reduce[ReduceRows, 1] +] + + +# ---- Helpers ---- + + +def _rss_of(pid: Int) -> Int: + """Process `pid`'s resident bytes now, which for Mojo stay near their + peak; 0 if they can't be read. A forked head starts with the driver's + pages counted (on Linux), so the tests print its growth.""" + comptime if CompilationTarget.is_macos(): + # PROC_PIDTASKINFO (4): struct proc_taskinfo, whose second field is + # pti_resident_size. + var info = List[UInt8](length=96, fill=0) + var n = external_call["proc_pidinfo", c_int]( + c_int(pid), c_int(4), UInt64(0), info.unsafe_ptr(), c_int(96) + ) + if n < 16: + return 0 + var rss = 0 + for k in range(8): + rss |= Int(info[8 + k]) << (8 * k) + return rss + else: + try: + var text: String + with open(String("/proc/", pid, "/status"), "r") as f: + text = f.read() + for line in text.splitlines(): + if line.startswith("VmRSS:"): + var fields = line.split() + return Int(fields[1]) * 1024 + except: + pass + return 0 + + +def _mb(n: Int) -> String: + return String(Float64(n // 10_000) / 100.0, " MB") + + +def _assert_empty[*Ts: TaskLike](mut rt: Runtime[*Ts]) raises: + var st = rt.stats() + assert_equal(st.objects, 0, String(st)) + assert_equal(st.results + st.located + st.errors, 0, String(st)) + + +def _fresh(dir: String) raises: + if not exists(dir): + makedirs(dir) + for name in listdir(dir): + remove(String(dir, "/", name)) + + +def _files(dir: String) raises -> Int: + """Results in `dir`, written whole.""" + var n = 0 + for name in listdir(dir): + if name.startswith("dista-") and not name.endswith(".tmp"): + n += 1 + return n + + +def _inputs() -> List[Int]: + var out = List[Int](capacity=INPUTS) + for m in range(INPUTS): + out.append(m) + return out^ + + +def _assert_exact(got: List[Seq[Row]]) raises: + """Every key once, in its partition, with every input's count and sum.""" + assert_equal(len(got), PARTS) + var seen = 0 + for j in range(PARTS): + ref part = got[j] + for i in range(len(part)): + ref r = part.items[i] + assert_equal(partition_of(r.key, PARTS), j) + assert_equal(r.count, INPUTS) + var want = 0 + for m in range(INPUTS): + want += value(m, r.key) + assert_equal(r.total, want) + seen += 1 + assert_equal(seen, KEYS) + + +# ---- The frames ---- + + +def test_the_count_carries_the_flag_in_its_top_bit() raises: + assert_equal(many_word(16, False), UInt64(16)) + assert_equal(many_word(16, True), UInt64(16) | KEEP_ON_WORKER) + assert_equal(KEEP_ON_WORKER, UInt64(1) << 63) + var a = parse_many(many_word(16, True)) + assert_equal(a[0], 16) + assert_true(a[1]) + var b = parse_many(16) + assert_equal(b[0], 16) + assert_false(b[1]) + assert_equal(parse_many(many_word(MAX_MANY, True))[0], MAX_MANY) + for bad in [UInt64(0), KEEP_ON_WORKER, UInt64(MAX_MANY + 1)]: + var refused = False + try: + _ = parse_many(bad) + except e: + refused = String(e).startswith("bad result count") + assert_true(refused, String("took ", bad)) + + +def _driver(var mine: Stream, peer: Stream) raises -> Client: + """A client on `mine`, whose other end, `peer`, plays the head: a + welcome is waiting for it, and its hello is read off.""" + var welcome = List[UInt8]() + put_scalar[DType.uint64](welcome, 3) + put_scalar[DType.uint64](welcome, 99) + write_frame(peer, KIND_WELCOME, 0, 0, welcome) + var c = Client(mine^, "", HASH) + var hello = read_frame(peer) + assert_equal(hello.value().kind, KIND_HELLO) + return c^ + + +def _sent(peer: Stream) raises -> Frame: + var f = read_frame(peer) + if not f: + raise Error("the client hung up") + return f.take() + + +def test_a_program_without_the_flag_sends_the_bytes_it_sent_before() raises: + """Each `remote_many` form's frame, byte for byte as main wrote it before + the flag; with the flag, only the count's top bit differs, and the copy + the driver keeps to send again after a head restart has it too.""" + var pair = stream_pair() + var peer = pair.pop() + var c = _driver(pair.pop(), peer) + for keep in [False, True]: + # On a value: task-many, the count and then the encoded argument. + var refs = c.remote_many[MakePieces](7, 4, keep_on_worker=keep) + var f = _sent(peer) + assert_equal(f.kind, KIND_TASK_MANY) + assert_equal(f.object_id, refs[0].id) + assert_equal(f.task_id, MakePieces.id()) + var want = List[UInt8]() + put_scalar[DType.uint64](want, UInt64(4)) + if keep: + want[7] |= 0x80 + put_scalar[DType.int64](want, 7) + assert_true(f.payload == want, "task-many bytes changed") + assert_true(c._subs[refs[0].id].payload == want, "resend differs") + # On results, gathered: task-after, flags, count, inputs, IDs. + var deps: List[ObjectRef[Int]] = [ + ObjectRef[Int](11), + ObjectRef[Int](12), + ] + var more = c.remote_many[SplitRows](deps, 16, keep_on_worker=keep) + f = _sent(peer) + assert_equal(f.kind, KIND_TASK_AFTER) + assert_equal(f.object_id, more[0].id) + want = [MANY | GATHER] + put_scalar[DType.uint64](want, UInt64(16)) + if keep: + want[8] |= 0x80 + put_scalar[DType.uint64](want, UInt64(2)) + put_scalar[DType.uint64](want, UInt64(11)) + put_scalar[DType.uint64](want, UInt64(12)) + assert_true(f.payload == want, "task-after bytes changed") + assert_true(c._subs[more[0].id].payload == want, "resend differs") + # On one result: task-after without gather. + var one = c.remote_many[MakePieces]( + ObjectRef[Int](13), 2, keep_on_worker=keep + ) + f = _sent(peer) + want = [MANY] + put_scalar[DType.uint64](want, UInt64(2)) + if keep: + want[8] |= 0x80 + put_scalar[DType.uint64](want, UInt64(1)) + put_scalar[DType.uint64](want, UInt64(13)) + assert_true(f.payload == want, "task-after bytes changed") + _ = one[0].id + _ = peer.fd + _ = c._counter + + +def _connect(mut head: Head, mut peers: List[Stream]) raises -> Int: + var pair = stream_pair() + peers.append(pair.pop()) + return head._add_conn(Conn(pair.pop())) + + +def _hello(mut head: Head, i: Int, role: UInt8) raises: + var hello: List[UInt8] = [role] + put_scalar[DType.uint64](hello, HASH) + if role == ROLE_WORKER: + hello.extend(encode_addr([127, 0, 0, 1], 7000 + i)) + head._handle(i, Frame(KIND_HELLO, 0, 0, hello^)) + + +def _number(head: Head, driver: Int) -> UInt64: + for entry in head._driver_conn.items(): + if entry.value == driver: + return entry.key + return 0 + + +def _task_frame(mut head: Head, w: Int, peer: Stream) raises -> Frame: + """The next `TaskMany` the head sent worker `w`, past its other frames: + task-many or task-inputs.""" + head._conns[w].flush() + while True: + var f = read_frame(peer) + if not f: + raise Error("the head hung up") + var frame = f.take() + if frame.kind == KIND_TASK_MANY or frame.kind == KIND_TASK_INPUTS: + return frame^ + + +def _after_many(n: Int, keep: Bool, deps: List[UInt64]) -> List[UInt8]: + """A gathering task-after for a `TaskMany` of `n` results.""" + var body: List[UInt8] = [MANY | GATHER] + put_scalar[DType.uint64](body, many_word(n, keep)) + put_scalar[DType.uint64](body, UInt64(len(deps))) + for d in deps: + put_scalar[DType.uint64](body, d) + return body^ + + +def test_the_head_passes_the_flag_on_and_keeps_it_for_a_retry() raises: + """A task-many frame goes to the worker as it came; a task-after on a + result the head holds goes as task-many with the flag in its count, and + without the flag as before; both, retried on another worker once theirs + is lost, keep it.""" + for keep in [False, True]: + var head = Head(Listener(0), HASH, 2, False) + var peers = List[Stream]() + var driver = _connect(head, peers) + _hello(head, driver, ROLE_DRIVER) + var w1 = _connect(head, peers) + _hello(head, w1, ROLE_WORKER) + var d = _number(head, driver) << DRIVER_SHIFT + var many = List[UInt8]() + put_scalar[DType.uint64](many, many_word(4, keep)) + many.append(9) + head._handle(driver, Frame(KIND_TASK_MANY, d | 1, 5, many.copy())) + head._handle(driver, Frame(KIND_RESULT, d | 10, 0, [UInt8(42)])) + head._handle( + driver, + Frame(KIND_TASK_AFTER, d | 20, 6, _after_many(3, keep, [d | 10])), + ) + head._release_waiting() + head._dispatch() + var want = List[UInt8]() + put_scalar[DType.uint64](want, UInt64(3)) + if keep: + want[7] |= 0x80 + put_scalar[DType.int64](want, 1) + want.append(42) + for _ in range(2): + var f = _task_frame(head, w1, peers[1]) + assert_equal(f.kind, KIND_TASK_MANY) + if f.object_id == d | 1: + assert_true(f.payload == many, "task-many changed") + else: + assert_equal(f.object_id, d | 20) + assert_true(f.payload == want, "task-many from task-after") + # The worker goes: both run again on the next, flag and all. + var w2 = _connect(head, peers) + _hello(head, w2, ROLE_WORKER) + head._drop(w1) + head._dispatch() + for _ in range(2): + var f = _task_frame(head, w2, peers[2]) + assert_equal(f.kind, KIND_TASK_MANY) + if f.object_id == d | 1: + assert_true(f.payload == many, "retried task-many changed") + else: + assert_true(f.payload == want, "retried task-after changed") + _ = len(head._conns) + _ = len(peers) + + +def test_task_inputs_carry_the_flag() raises: + """A task-after on a result that lives on a worker goes as task-inputs, + whose count has the flag, and again after a retry on another worker.""" + for keep in [False, True]: + var head = Head(Listener(0), HASH, 1, False) + var peers = List[Stream]() + var driver = _connect(head, peers) + _hello(head, driver, ROLE_DRIVER) + var conns: List[Int] = [driver] + for _ in range(2): + var w = _connect(head, peers) + _hello(head, w, ROLE_WORKER) + conns.append(w) + var d = _number(head, driver) << DRIVER_SHIFT + # A result stored on one worker, `h`, the input of a `TaskMany`. + head._handle(driver, Frame(KIND_TASK, d | 1, 5, [UInt8(1)])) + head._dispatch() + var h = 1 if len(head._inflight[conns[1]]) == 1 else 2 + var o = 3 - h + var loc = Location([127, 0, 0, 1], 7000 + conns[h], "n", "", 100_000) + head._handle(conns[h], Frame(KIND_STORED, d | 1, 0, loc.encode())) + # Busy `h` with other tasks, so the `TaskMany` runs on the other + # worker, `o`, which can then be lost without its input. + var next = UInt64(2) + while len(head._inflight[conns[h]]) == 0: + head._handle(driver, Frame(KIND_TASK, d | next, 5, [UInt8(1)])) + next += 1 + head._dispatch() + for obj in head._inflight[conns[o]].copy(): + head._handle(conns[o], Frame(KIND_RESULT, obj, 0, List[UInt8]())) + head._handle( + driver, + Frame(KIND_TASK_AFTER, d | 20, 6, _after_many(5, keep, [d | 1])), + ) + head._release_waiting() + head._dispatch() + var f = _task_frame(head, conns[o], peers[o]) + assert_equal(f.kind, KIND_TASK_INPUTS) + assert_equal(f.object_id, d | 20) + var spec = parse_task_inputs(f.payload) + assert_equal(spec.many, 5) + assert_equal(spec.keep, keep) + var pos = 1 + var word = get_scalar[DType.uint64](f.payload, pos) + # The count as before the flag, the u64 after the flags byte, and + # with it only the top bit more. + assert_equal(word, many_word(5, keep)) + # `o` goes; once `h` is free, the task runs there, flag and all. + head._drop(conns[o]) + for obj in head._inflight[conns[h]].copy(): + head._handle(conns[h], Frame(KIND_RESULT, obj, 0, List[UInt8]())) + head._dispatch() + var g = _task_frame(head, conns[h], peers[h]) + assert_equal(g.kind, KIND_TASK_INPUTS) + assert_equal(g.object_id, d | 20) + assert_true(g.payload == f.payload, "the retry's frame differs") + _ = len(head._conns) + _ = len(peers) + + +# ---- In local mode ---- + + +def _hold_pieces(tasks: Int, keep: Bool) raises -> Tuple[HeadStats, Int]: + """`tasks` × 16 pieces of 10 KB, all made and none released: the head's + stats and resident memory then. A few are read back, by the driver and + by a task, and then all released.""" + var rt = Runtime[MakePieces, PieceOf](workers=2) + _ = rt.stats() + var base = _rss_of(rt._pids[0]) + var refs = List[ObjectRef[String]]() + for m in range(tasks): + refs.extend(rt.remote_many[MakePieces](m, PARTS, keep_on_worker=keep)) + _ = rt.wait(refs, count=len(refs)) + var st = rt.stats() + var rss = _rss_of(rt._pids[0]) - base + for k in [0, 17, len(refs) - 1]: + var m = k // PARTS + var j = k % PARTS + var s = rt.get(refs[k]) + assert_equal(s.byte_length(), PIECE) + assert_equal(s.as_bytes()[0], UInt8(65 + (m + j) % 26)) + var mine = List[ObjectRef[String]]() + for i in range(PARTS): + mine.append(refs[m * PARTS + i]) + assert_equal(rt.take(rt.remote[PieceOf](j, mine)), PIECE) + if keep: + assert_true(rt.location(refs[k]) != "", "a kept piece came inline") + else: + assert_equal(rt.location(refs[k]), "") + rt.release(refs) + _assert_empty(rt) + return (st^, rss) + + +def test_kept_pieces_stay_off_the_head() raises: + """2,000 pieces of 10 KB: without the flag the head holds every one, + with it none, and each is read the same.""" + var rows = List[String]() + for tasks in [INPUTS // 4, INPUTS]: + for keep in [False, True]: + var got = _hold_pieces(tasks, keep) + ref st = got[0] + var n = tasks * PARTS + if keep: + assert_equal(st.results, 0, String(st)) + assert_equal(st.located, n, String(st)) + else: + assert_equal(st.results, n, String(st)) + assert_equal(st.located, 0, String(st)) + rows.append( + String( + " ", + n, + " pieces, keep_on_worker=", + keep, + ": head RSS grew ", + _mb(got[1]), + "; ", + st, + ) + ) + for r in rows: + print(r) + + +def test_a_partitions_pieces_stay_on_their_workers() raises: + """125 inputs, 16 pieces each of about 10 KB: once the first partition's + result is out, the head holds none of the other pieces' bytes, only + their locations; the result is exact.""" + var rt = Runtime[SmallBatches, SplitRows, ReduceRows](workers=4) + _ = rt.stats() + var base = _rss_of(rt._pids[0]) + var run = Small.start(rt, _inputs()) + var got = List[Seq[Row]](length=PARTS, fill=Seq[Row]()) + var first = True + var peak = 0 + while True: + var r = run.next(rt) + if not r: + break + var done = r.take() + if first: + first = False + var st = rt.stats() + peak = _rss_of(rt._pids[0]) + print(" at the first partition's result:", st) + # Partition 0's result, maybe 1's reducer's: no piece. + assert_true(st.results <= 2, String(st)) + # Every other partition's pieces, but one's being reduced. + assert_true(st.located >= (PARTS - 2) * INPUTS, String(st)) + got[done.input] = rt.take(done.refs[0]) + var st = run.stats() + print(" ", st) + print( + " head RSS at the start", _mb(base), "and the first result", _mb(peak) + ) + assert_equal(st.unsized_pieces, 0) + var bytes = 0 + for j in range(PARTS): + bytes += st.partition_bytes[j] + # 6,800 rows of three Ints from each input, and a count per piece. + assert_equal(bytes, INPUTS * (KEYS * 24 + PARTS * 8)) + _assert_exact(got) + _assert_empty(rt) + + +def test_pieces_past_the_store_spill_and_are_removed() raises: + """With room in the store for a quarter of the pieces, the rest spill; + the result is exact, and the store and the spill directory are empty + once the run ends. The batches are large, so the partition tasks run + from task-inputs frames.""" + _fresh(STORE) + _fresh(SPILL) + comptime WORKERS = 4 + var pieces = INPUTS * (KEYS * 24 + PARTS * 8) + # The batches go into the store first, and are freed as their input's + # partition task settles; a quarter of the pieces' bytes, across the + # workers. + _ = setenv("DISTA_STORE_DIR", STORE) + _ = setenv("DISTA_SPILL_DIR", SPILL) + _ = setenv("DISTA_STORE_BYTES", String(pieces // 4 // WORKERS)) + var rt = Runtime[LargeBatches, SplitRows, ReduceRows](workers=WORKERS) + _ = unsetenv("DISTA_STORE_DIR") + _ = unsetenv("DISTA_SPILL_DIR") + _ = unsetenv("DISTA_STORE_BYTES") + var run = Large.start(rt, _inputs()) + var got = List[Seq[Row]](length=PARTS, fill=Seq[Row]()) + var first = True + var spilled = 0 + var stored = 0 + while True: + var r = run.next(rt) + if not r: + break + var done = r.take() + if first: + first = False + spilled = _files(SPILL) + stored = _files(STORE) + got[done.input] = rt.take(done.refs[0]) + print( + " at the first partition's result:", + stored, + "results in the store,", + spilled, + "spilled", + ) + # About three quarters of 2,000, less partition 0's and the batches'. + assert_true(spilled >= INPUTS * PARTS // 2, String(spilled, " spilled")) + assert_true(stored > 0, "nothing in the store") + _assert_exact(got) + _assert_empty(rt) + # The head has freed everything; its frees reach the workers soon after. + for _ in range(100): + if _files(SPILL) + _files(STORE) == 0: + break + sleep(0.05) + assert_equal(_files(SPILL), 0, "spill files left") + assert_equal(_files(STORE), 0, "store files left") + + +def main() raises: + TestSuite.discover_tests[__functions_in_module()]().run()