Skip to main content

mito2/sst/parquet/
parallel_writer.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Arrow to Parquet writer that encodes the columns of a row group in parallel.
16
17use std::mem;
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20
21use bytes::Bytes;
22use common_base::cancellation::Cancelled;
23use common_runtime::JoinHandle;
24use datatypes::arrow::datatypes::SchemaRef;
25use datatypes::arrow::record_batch::RecordBatch;
26use parquet::arrow::ArrowWriter;
27use parquet::arrow::arrow_writer::{
28    ArrowColumnChunk, ArrowColumnWriter, ArrowRowGroupWriterFactory, compute_leaves,
29};
30use parquet::arrow::async_writer::AsyncFileWriter;
31use parquet::errors::{ParquetError, Result};
32use parquet::file::metadata::{KeyValue, ParquetMetaData};
33use parquet::file::properties::WriterProperties;
34use parquet::file::writer::SerializedFileWriter;
35use tokio_util::sync::CancellationToken;
36
37/// Runtime whose blocking pool encodes the columns of a writer.
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub enum EncodeRuntime {
40    /// The global runtime.
41    #[default]
42    Global,
43    /// The compaction runtime.
44    Compact,
45}
46
47impl EncodeRuntime {
48    fn spawn<F, R>(self, f: F) -> JoinHandle<R>
49    where
50        F: FnOnce() -> R + Send + 'static,
51        R: Send + 'static,
52    {
53        match self {
54            EncodeRuntime::Global => common_runtime::spawn_blocking_global(f),
55            EncodeRuntime::Compact => common_runtime::spawn_blocking_compact(f),
56        }
57    }
58}
59
60/// Column writers of one top-level field: its index and its leaf writers.
61type FieldWriters = (usize, Vec<(usize, ArrowColumnWriter)>);
62
63/// Output of one encode task: column chunks by leaf index, and the time spent
64/// on each field.
65type EncodedFields = (Vec<(usize, ArrowColumnChunk)>, Vec<(usize, Duration)>);
66
67/// Writes Parquet like [`parquet::arrow::AsyncArrowWriter`], but encodes the
68/// columns of each row group on up to `parallelism` blocking tasks.
69///
70/// A row group encodes in the background while the next one is buffered, so at
71/// most two row groups of input are held in memory. Every column writer sees the
72/// same input as with [`ArrowWriter`], so the output is byte-for-byte identical.
73/// The bytes of a row group reach the async writer when the next row group
74/// starts or on [`Self::flush`], one row group later than with `AsyncArrowWriter`.
75pub struct ParallelArrowWriter<W> {
76    /// Assembles row groups and the footer into an in-memory buffer.
77    file_writer: SerializedFileWriter<Vec<u8>>,
78    /// Creates the column writers of each row group.
79    factory: Arc<ArrowRowGroupWriterFactory>,
80    arrow_schema: SchemaRef,
81    /// Top-level field of each leaf column.
82    leaf_fields: Vec<usize>,
83    /// Encode time of each field in the last row group, used to balance tasks.
84    field_costs: Vec<Duration>,
85    async_writer: W,
86    max_row_group_rows: usize,
87    parallelism: usize,
88    runtime: EncodeRuntime,
89    /// Slices of input buffered for the next row group.
90    buffered: Vec<RecordBatch>,
91    buffered_rows: usize,
92    /// Tasks encoding the previous row group.
93    encoding: Vec<JoinHandle<Result<EncodedFields>>>,
94    num_row_groups: usize,
95    cancellation: Option<CancellationToken>,
96}
97
98impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
99    /// Returns whether the writer can reproduce [`ArrowWriter`]'s row groups for
100    /// `props`, which holds only when row groups are limited by row count alone.
101    pub fn supports(props: &WriterProperties) -> bool {
102        props.max_row_group_row_count().is_some() && props.max_row_group_bytes().is_none()
103    }
104
105    /// Creates a writer. `props` must be [supported](Self::supports).
106    pub fn try_new(
107        async_writer: W,
108        arrow_schema: SchemaRef,
109        props: WriterProperties,
110        parallelism: usize,
111        runtime: EncodeRuntime,
112    ) -> Result<Self> {
113        let max_row_group_rows = match props.max_row_group_row_count() {
114            Some(rows) if Self::supports(&props) => rows.max(1),
115            _ => {
116                return Err(ParquetError::General(
117                    "parallel writer requires a row-count-only row group limit".to_string(),
118                ));
119            }
120        };
121        let (file_writer, factory) =
122            ArrowWriter::try_new(Vec::new(), arrow_schema.clone(), Some(props))?
123                .into_serialized_writer()?;
124        let schema = file_writer.schema_descr();
125        let leaf_fields = (0..schema.num_columns())
126            .map(|leaf| schema.get_column_root_idx(leaf))
127            .collect();
128        let num_fields = arrow_schema.fields().len();
129        Ok(Self {
130            file_writer,
131            factory: Arc::new(factory),
132            arrow_schema,
133            leaf_fields,
134            field_costs: vec![Duration::ZERO; num_fields],
135            async_writer,
136            max_row_group_rows,
137            parallelism: parallelism.max(1),
138            runtime,
139            buffered: Vec::new(),
140            buffered_rows: 0,
141            encoding: Vec::new(),
142            num_row_groups: 0,
143            cancellation: None,
144        })
145    }
146
147    pub(crate) fn with_cancellation(mut self, cancellation: Option<CancellationToken>) -> Self {
148        self.cancellation = cancellation;
149        self
150    }
151
152    /// Buffers `batch`, starting to encode each row group once it is full.
153    pub async fn write(&mut self, batch: &RecordBatch) -> Result<()> {
154        let mut offset = 0;
155        while offset < batch.num_rows() {
156            check_cancelled(self.cancellation.as_ref())?;
157            let len = (self.max_row_group_rows - self.buffered_rows).min(batch.num_rows() - offset);
158            self.buffered.push(batch.slice(offset, len));
159            self.buffered_rows += len;
160            offset += len;
161            if self.buffered_rows == self.max_row_group_rows {
162                self.encode_buffered().await?;
163            }
164        }
165        Ok(())
166    }
167
168    /// Writes all buffered rows as a row group, like [`ArrowWriter::flush`].
169    pub async fn flush(&mut self) -> Result<()> {
170        if self.buffered_rows > 0 {
171            self.encode_buffered().await?;
172        }
173        self.finish_encoding().await
174    }
175
176    /// Writes the remaining rows and the footer, then completes the async writer.
177    pub async fn close(mut self) -> Result<ParquetMetaData> {
178        self.finish().await
179    }
180
181    pub(crate) fn append_key_value_metadata(&mut self, kv: KeyValue) {
182        self.file_writer.append_key_value_metadata(kv);
183    }
184
185    /// Returns the metadata of all encoded and flushed row groups.
186    pub(crate) fn flushed_row_groups(&self) -> &[parquet::file::metadata::RowGroupMetaData] {
187        self.file_writer.flushed_row_groups()
188    }
189
190    /// Finalizes the file while retaining the upload for abort if it fails.
191    pub(crate) async fn finish(&mut self) -> Result<ParquetMetaData> {
192        self.flush().await?;
193        let metadata = self.file_writer.finish()?;
194        self.write_buffered_bytes().await?;
195        self.async_writer.complete().await?;
196        Ok(metadata)
197    }
198
199    /// Discards buffered input and waits for encoders without writing a failed SST.
200    pub(crate) async fn abort(mut self) -> W {
201        self.buffered.clear();
202        abort_encoding_tasks(&mut self.encoding).await;
203        self.async_writer
204    }
205
206    /// Installs controlled tasks to test SST write-error cleanup independently of codec timing.
207    #[cfg(test)]
208    pub(crate) fn set_encoding_tasks_for_test(
209        &mut self,
210        tasks: Vec<JoinHandle<Result<EncodedFields>>>,
211    ) {
212        assert!(self.encoding.is_empty());
213        self.encoding = tasks;
214    }
215
216    /// Starts encoding the buffered rows once the previous row group is written.
217    async fn encode_buffered(&mut self) -> Result<()> {
218        self.finish_encoding().await?;
219        check_cancelled(self.cancellation.as_ref())?;
220
221        let batches: Arc<[RecordBatch]> = mem::take(&mut self.buffered).into();
222        self.buffered_rows = 0;
223        let writers = self.factory.create_column_writers(self.num_row_groups)?;
224        self.num_row_groups += 1;
225
226        // One array produces all leaves of a field, so a field is never split.
227        let mut fields: Vec<FieldWriters> = (0..self.arrow_schema.fields().len())
228            .map(|field| (field, Vec::new()))
229            .collect();
230        for (leaf, writer) in writers.into_iter().enumerate() {
231            fields[self.leaf_fields[leaf]].1.push((leaf, writer));
232        }
233        self.encoding = assign_fields(fields, &self.field_costs, self.parallelism)
234            .into_iter()
235            .map(|fields| {
236                let batches = batches.clone();
237                let schema = self.arrow_schema.clone();
238                let cancellation = self.cancellation.clone();
239                self.runtime
240                    .spawn(move || encode_fields(&schema, &batches, fields, cancellation.as_ref()))
241            })
242            .collect();
243        Ok(())
244    }
245
246    /// Waits for the row group being encoded and appends it to the file.
247    async fn finish_encoding(&mut self) -> Result<()> {
248        if self.encoding.is_empty() {
249            return Ok(());
250        }
251        let mut chunks = Vec::with_capacity(self.leaf_fields.len());
252        let mut tasks = mem::take(&mut self.encoding).into_iter();
253        while let Some(task) = tasks.next() {
254            let encoded = task
255                .await
256                .map_err(|e| ParquetError::External(Box::new(e)))
257                .and_then(|encoded| encoded);
258            let (task_chunks, costs) = match encoded {
259                Ok(encoded) => encoded,
260                Err(error) => {
261                    abort_encoding_tasks(tasks.as_mut_slice()).await;
262                    return Err(error);
263                }
264            };
265            chunks.extend(task_chunks);
266            for (field, cost) in costs {
267                self.field_costs[field] = cost;
268            }
269        }
270        chunks.sort_unstable_by_key(|(leaf, _)| *leaf);
271        let mut row_group = self.file_writer.next_row_group()?;
272        for (_, chunk) in chunks {
273            chunk.append_to_row_group(&mut row_group)?;
274        }
275        row_group.close()?;
276        self.write_buffered_bytes().await
277    }
278
279    /// Moves the bytes assembled so far to the async writer.
280    async fn write_buffered_bytes(&mut self) -> Result<()> {
281        let bytes = mem::take(self.file_writer.inner_mut());
282        if bytes.is_empty() {
283            return Ok(());
284        }
285        self.async_writer.write(Bytes::from(bytes)).await
286    }
287}
288
289/// Aborts queued blocking work and joins running work before its budget is released.
290async fn abort_encoding_tasks(tasks: &mut [JoinHandle<Result<EncodedFields>>]) {
291    for task in tasks.iter() {
292        task.abort();
293    }
294    for task in tasks {
295        // Cleanup failures must not replace the original encoding or source error.
296        let _ = task.await;
297    }
298}
299
300/// Splits `fields` into at most `parallelism` tasks, giving the most expensive
301/// field to the least loaded task first. Fields cost nothing before any row
302/// group is measured, which spreads them evenly.
303fn assign_fields(
304    mut fields: Vec<FieldWriters>,
305    costs: &[Duration],
306    parallelism: usize,
307) -> Vec<Vec<FieldWriters>> {
308    let num_tasks = parallelism.min(fields.len()).max(1);
309    fields.sort_by_key(|(field, _)| std::cmp::Reverse(costs[*field]));
310    let mut tasks: Vec<(Duration, Vec<FieldWriters>)> = (0..num_tasks)
311        .map(|_| (Duration::ZERO, Vec::new()))
312        .collect();
313    for field in fields {
314        let key = |(load, fields): &(Duration, Vec<FieldWriters>)| (*load, fields.len());
315        let mut lightest = 0;
316        for task in 1..tasks.len() {
317            if key(&tasks[task]) < key(&tasks[lightest]) {
318                lightest = task;
319            }
320        }
321        tasks[lightest].0 += costs[field.0];
322        tasks[lightest].1.push(field);
323    }
324    tasks
325        .into_iter()
326        .map(|(_, fields)| fields)
327        .filter(|fields| !fields.is_empty())
328        .collect()
329}
330
331fn check_cancelled(cancellation: Option<&CancellationToken>) -> Result<()> {
332    if cancellation.is_some_and(CancellationToken::is_cancelled) {
333        return Err(ParquetError::External(Box::new(Cancelled)));
334    }
335    Ok(())
336}
337
338/// Encodes `fields` of all `batches` and closes their column writers.
339fn encode_fields(
340    schema: &SchemaRef,
341    batches: &[RecordBatch],
342    fields: Vec<FieldWriters>,
343    cancellation: Option<&CancellationToken>,
344) -> Result<EncodedFields> {
345    let mut chunks = Vec::new();
346    let mut costs = Vec::with_capacity(fields.len());
347    for (field, mut writers) in fields {
348        let start = Instant::now();
349        for batch in batches {
350            check_cancelled(cancellation)?;
351            let leaves = compute_leaves(schema.field(field), batch.column(field))?;
352            if leaves.len() != writers.len() {
353                return Err(ParquetError::General(format!(
354                    "field {} has {} leaf arrays but {} column writers",
355                    schema.field(field).name(),
356                    leaves.len(),
357                    writers.len()
358                )));
359            }
360            for (leaf, (_, writer)) in leaves.iter().zip(writers.iter_mut()) {
361                check_cancelled(cancellation)?;
362                writer.write(leaf)?;
363            }
364        }
365        for (leaf, writer) in writers {
366            check_cancelled(cancellation)?;
367            chunks.push((leaf, writer.close()?));
368        }
369        costs.push((field, start.elapsed()));
370    }
371    Ok((chunks, costs))
372}
373
374#[cfg(test)]
375mod tests {
376    use std::sync::Arc;
377    use std::sync::atomic::{AtomicBool, Ordering};
378
379    use common_runtime::runtime::{BuilderBuild, RuntimeTrait};
380    use datatypes::arrow::array::{
381        ArrayRef, DictionaryArray, Float64Array, Int32Array, Int64Array, StringArray, StructArray,
382    };
383    use datatypes::arrow::datatypes::{DataType, Field, Fields, Schema, UInt32Type};
384    use parquet::basic::{Compression, ZstdLevel};
385    use tokio::sync::oneshot;
386    use tokio::time::timeout;
387
388    use super::*;
389    use crate::compaction::memory_manager::new_compaction_memory_manager;
390
391    fn schema() -> SchemaRef {
392        let nested = Fields::from(vec![
393            Field::new("a", DataType::Int32, true),
394            Field::new("b", DataType::Utf8, true),
395        ]);
396        Arc::new(Schema::new(vec![
397            Field::new("int", DataType::Int64, false),
398            Field::new("float", DataType::Float64, true),
399            Field::new(
400                "tag",
401                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
402                false,
403            ),
404            Field::new("nested", DataType::Struct(nested), true),
405        ]))
406    }
407
408    fn batch(start: usize, len: usize) -> RecordBatch {
409        let rows = start..start + len;
410        let ints = Int64Array::from_iter_values(rows.clone().map(|i| i as i64 * 7));
411        let floats = Float64Array::from_iter(
412            rows.clone()
413                .map(|i| (i % 5 != 0).then_some((i % 13) as f64 / 3.0)),
414        );
415        let tags: DictionaryArray<UInt32Type> = rows
416            .clone()
417            .map(|i| format!("tag-{}", i % 3))
418            .collect::<Vec<_>>()
419            .iter()
420            .map(String::as_str)
421            .collect();
422        let nested = StructArray::from(vec![
423            (
424                Arc::new(Field::new("a", DataType::Int32, true)),
425                Arc::new(Int32Array::from_iter(
426                    rows.clone().map(|i| (i % 4 != 0).then_some(i as i32)),
427                )) as ArrayRef,
428            ),
429            (
430                Arc::new(Field::new("b", DataType::Utf8, true)),
431                Arc::new(StringArray::from_iter(
432                    rows.map(|i| (i % 6 != 0).then(|| format!("v{i}"))),
433                )) as ArrayRef,
434            ),
435        ]);
436        RecordBatch::try_new(
437            schema(),
438            vec![
439                Arc::new(ints),
440                Arc::new(floats),
441                Arc::new(tags),
442                Arc::new(nested),
443            ],
444        )
445        .unwrap()
446    }
447
448    fn props(row_group_rows: usize) -> WriterProperties {
449        WriterProperties::builder()
450            .set_compression(Compression::ZSTD(ZstdLevel::default()))
451            .set_max_row_group_row_count(Some(row_group_rows))
452            .set_data_page_row_count_limit(16)
453            .build()
454    }
455
456    /// One step of a write sequence: a batch of `len` rows, or a flush.
457    #[derive(Clone, Copy)]
458    enum Step {
459        Write(usize),
460        Flush,
461    }
462
463    fn write_serial(steps: &[Step], props: WriterProperties) -> Vec<u8> {
464        let mut buf = Vec::new();
465        let mut writer = ArrowWriter::try_new(&mut buf, schema(), Some(props)).unwrap();
466        let mut start = 0;
467        for step in steps {
468            match *step {
469                Step::Write(len) => {
470                    writer.write(&batch(start, len)).unwrap();
471                    start += len;
472                }
473                Step::Flush => writer.flush().unwrap(),
474            }
475        }
476        writer.close().unwrap();
477        buf
478    }
479
480    async fn write_parallel(
481        steps: &[Step],
482        props: WriterProperties,
483        parallelism: usize,
484    ) -> Vec<u8> {
485        let mut buf = Vec::new();
486        let mut writer = ParallelArrowWriter::try_new(
487            &mut buf,
488            schema(),
489            props,
490            parallelism,
491            EncodeRuntime::Global,
492        )
493        .unwrap();
494        let mut start = 0;
495        for step in steps {
496            match *step {
497                Step::Write(len) => {
498                    writer.write(&batch(start, len)).await.unwrap();
499                    start += len;
500                }
501                Step::Flush => writer.flush().await.unwrap(),
502            }
503        }
504        writer.close().await.unwrap();
505        buf
506    }
507
508    #[tokio::test]
509    async fn test_parallel_writer_matches_arrow_writer() {
510        use Step::*;
511        let cases: Vec<(&str, Vec<Step>)> = vec![
512            ("empty", vec![]),
513            ("partial row group", vec![Write(10)]),
514            ("exact row groups", vec![Write(64), Write(64)]),
515            (
516                "batches across row groups",
517                vec![Write(7), Write(100), Write(3), Write(250), Write(1)],
518            ),
519            ("batch spanning many row groups", vec![Write(1000)]),
520            (
521                "explicit flushes",
522                vec![Write(10), Flush, Flush, Write(70), Flush, Write(5)],
523            ),
524        ];
525        for (name, steps) in cases {
526            let expected = write_serial(&steps, props(64));
527            for parallelism in [1, 2, 3, 16] {
528                let actual = write_parallel(&steps, props(64), parallelism).await;
529                assert!(
530                    expected == actual,
531                    "case {name}, parallelism {parallelism}: {} bytes != {} bytes",
532                    expected.len(),
533                    actual.len()
534                );
535            }
536        }
537    }
538
539    #[rstest::rstest]
540    #[case::encode_error(false)]
541    #[case::encode_panic(true)]
542    #[tokio::test]
543    async fn test_encode_failure_drains_tasks_before_releasing_budget(#[case] panics: bool) {
544        let runtime: common_runtime::Runtime = common_runtime::Builder::default()
545            .worker_threads(1)
546            .max_blocking_threads(1)
547            .build()
548            .unwrap();
549        let mut writer = ParallelArrowWriter::try_new(
550            Vec::new(),
551            schema(),
552            props(64),
553            3,
554            EncodeRuntime::Compact,
555        )
556        .unwrap();
557        let memory = new_compaction_memory_manager(1024 * 1024);
558        let budget = memory.try_acquire(memory.limit_bytes()).unwrap();
559        let batches: Arc<[RecordBatch]> = vec![batch(0, 4)].into();
560        let retained_batches = Arc::downgrade(&batches);
561
562        let failed = runtime.spawn_blocking(move || -> Result<EncodedFields> {
563            if panics {
564                panic!("encode task failed");
565            }
566            Err(ParquetError::General("encode task failed".to_string()))
567        });
568        let (started_tx, started_rx) = oneshot::channel();
569        let (release_tx, release_rx) = oneshot::channel();
570        let column = writer.factory.create_column_writers(0).unwrap().remove(0);
571        let running_batches = batches.clone();
572        let running = runtime.spawn_blocking(move || {
573            started_tx.send(()).unwrap();
574            release_rx.blocking_recv().unwrap();
575            let _encoded = encode_fields(
576                &schema(),
577                &running_batches,
578                vec![(0, vec![(0, column)])],
579                None,
580            )?;
581            Err(ParquetError::General("later encoding failure".to_string()))
582        });
583        // With one blocking thread, this also proves the first task has ended.
584        timeout(Duration::from_secs(10), started_rx)
585            .await
586            .unwrap()
587            .unwrap();
588        let queued_started = Arc::new(AtomicBool::new(false));
589        let queued_started_task = queued_started.clone();
590        let queued = runtime.spawn_blocking(move || {
591            queued_started_task.store(true, Ordering::SeqCst);
592            drop(batches);
593            Ok((Vec::new(), Vec::new()))
594        });
595        writer.encoding = vec![failed, running, queued];
596
597        // Model the compaction caller's guard: it is released when flush returns.
598        let mut finish = Box::pin(async {
599            let _budget = budget;
600            writer.flush().await
601        });
602        assert!(futures::poll!(finish.as_mut()).is_pending());
603        assert!(memory.try_acquire(memory.limit_bytes()).is_none());
604        assert!(retained_batches.upgrade().is_some());
605
606        release_tx.send(()).unwrap();
607        let error = timeout(Duration::from_secs(10), finish)
608            .await
609            .unwrap()
610            .unwrap_err();
611        if panics {
612            let ParquetError::External(source) = error else {
613                panic!("expected the original task panic, got {error}");
614            };
615            assert!(
616                source
617                    .downcast_ref::<common_runtime::JoinError>()
618                    .unwrap()
619                    .is_panic()
620            );
621        } else {
622            assert!(
623                matches!(error, ParquetError::General(message) if message == "encode task failed")
624            );
625        }
626        assert!(!queued_started.load(Ordering::SeqCst));
627        assert!(retained_batches.upgrade().is_none());
628        assert!(memory.try_acquire(memory.limit_bytes()).is_some());
629        assert!(writer.file_writer.flushed_row_groups().is_empty());
630        assert!(writer.async_writer.is_empty());
631    }
632
633    #[test]
634    fn test_parallel_writer_requires_row_count_limit() {
635        assert!(ParallelArrowWriter::<Vec<u8>>::supports(&props(64)));
636        let byte_limited = WriterProperties::builder()
637            .set_max_row_group_bytes(Some(1024))
638            .build();
639        assert!(!ParallelArrowWriter::<Vec<u8>>::supports(&byte_limited));
640        let unlimited = WriterProperties::builder()
641            .set_max_row_group_row_count(None)
642            .build();
643        assert!(!ParallelArrowWriter::<Vec<u8>>::supports(&unlimited));
644        assert!(
645            ParallelArrowWriter::try_new(Vec::new(), schema(), unlimited, 2, EncodeRuntime::Global)
646                .is_err()
647        );
648    }
649
650    #[test]
651    fn test_assign_fields_balances_measured_costs() {
652        let (file_writer, factory) = ArrowWriter::try_new(Vec::new(), schema(), Some(props(64)))
653            .unwrap()
654            .into_serialized_writer()
655            .unwrap();
656        let schema_descr = file_writer.schema_descr();
657        let mut fields: Vec<FieldWriters> = (0..4).map(|field| (field, Vec::new())).collect();
658        for (leaf, writer) in factory
659            .create_column_writers(0)
660            .unwrap()
661            .into_iter()
662            .enumerate()
663        {
664            fields[schema_descr.get_column_root_idx(leaf)]
665                .1
666                .push((leaf, writer));
667        }
668        // The nested field owns both struct leaves.
669        assert_eq!(2, fields[3].1.len());
670
671        let costs = [10, 9, 1, 1].map(Duration::from_millis);
672        let tasks = assign_fields(fields, &costs, 2);
673        let mut loads: Vec<_> = tasks
674            .iter()
675            .map(|task| {
676                task.iter()
677                    .map(|(field, _)| costs[*field])
678                    .sum::<Duration>()
679            })
680            .collect();
681        loads.sort();
682        assert_eq!(
683            vec![Duration::from_millis(10), Duration::from_millis(11)],
684            loads
685        );
686        let mut assigned: Vec<_> = tasks.iter().flatten().map(|(field, _)| *field).collect();
687        assigned.sort();
688        assert_eq!(vec![0, 1, 2, 3], assigned);
689    }
690}