ostrya 0.19.0

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! The server commit of a `Commit` message: a commit that the server makes
//! from a tree and the fields that the client sends.

use std::any::Any;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock};

use ostrya_core::{Checksum, ObjectType, Ref, Type, validate};

use super::finish::{
    Checked, Named, attachment_edits, check_anchor, check_attachment_states, check_ref_paths,
    checked_link_attachments, commit_ref, missing_objects, parse_commit_links,
    partial_attachment_failure, protocol, publish, queue_detached, report, sign_server_commit,
};
use super::hooks::{self, HookRefusal, ReceiveHooks, ReceiveServerCommit};
use super::policy::SessionPolicy;
use super::session::{Failure, ReceiveCommit, ReceiveRefOutcome};
use super::walk;
use crate::MAX_METADATA_SIZE;
use crate::error::Error;
use crate::related::{self, HeldAttachment, RelationField};
use crate::remote::proto::{CommitRequest, MAX_FRAME, Message, ServerCommit};
use crate::remote::{self, RefOutcome};
use crate::repo::Repo;
use crate::repo_fs::RepoDir;
use crate::server_commit::{CommitFields, clock, commit_bytes};
use crate::summary::OSTREE_METADATA_REF;
use crate::transaction::Transaction;
use crate::write::flat_name;

/// The type of a `v` at the depth of a metadata value in a commit.
///
/// The codec of a commit reads and writes its metadata dict with the depth
/// limit counted from the dict. In the dict, the `v` of an entry is under two
/// containers: the `a{sv}` dict and the `{sv}` entry. A tuple with one member
/// of variable size holds the bytes of the member and no framing, so the
/// bytes of a `v` are also the bytes of `((v))`. A check of the bytes as this
/// type applies the depth limit of the commit to the value.
static VALUE_IN_COMMIT: LazyLock<Type> =
    LazyLock::new(|| Type::parse("((v))").expect("valid signature"));

/// Runs the checks of a `Commit` with a server commit, then writes the
/// commit and its refs and commits `txn` under the update lock.
///
/// `named` holds the refs of `Hello`, their canonical forms, and their
/// paths. `commit_meta` holds the detached metadata dicts of the session.
///
/// # Checks
///
/// The checks run in this order. The first failure ends the session, and the
/// session publishes nothing.
///
/// 1. The branch and each tag are valid refs, and no local ref among them is
///    64 lowercase hex characters. Each bound name is a valid ref name with
///    no `:` (`invalid-ref`). The message holds no ref update and no
///    `force`, the branch and each tag are refs of `Hello`, no ref occurs two
///    times among them, the branch and each tag are in one namespace, a
///    commit can hold each metadata value within the depth limit of 128
///    levels of containers, and no two attachments have one name
///    (`protocol`).
/// 2. The `CommitReply` fits in a frame of [`MAX_FRAME`], with an old commit
///    on the branch (`limit-exceeded`).
/// 3. The function reads the full set of attachments: the attachments that
///    field 2 of the server commit names, then the attachments that field 2
///    of each of these names, one level at a time, as [`attachment_set`]
///    states. A staged commit of the set that does not parse, or that has a
///    defective entry in field 2, is `protocol`. A defective entry in field 2
///    of a held commit of the set is `internal`. Then each detached metadata
///    dict is for a staged or a held commit of the set, and each staged commit
///    is in the set (`protocol`), as [`check_session_objects`] states. If one
///    of these two checks fails and the repository marks a held commit of the
///    set partial, the failure is `missing-objects` for that commit, as in
///    step 5.
/// 4. No ref is the local collection anchor ref of a repository with a
///    collection id, and `policy` gives the rule of the server commit, with
///    the rights of each ref in its namespace (`ref-denied`).
/// 5. Each commit of the set is staged or held (`missing-objects`, with each
///    absent commit listed in level order), and each held commit of the set
///    is complete (`missing-objects`, with no object listed). This step uses
///    the states that step 3 read, and reads no tree.
/// 6. The tree of the commit and the tree of each staged commit of the set
///    are complete (`missing-objects`).
///
/// With an empty field 2, steps 3 and 5 read nothing. The bindings and the
/// signature verification of a commit that the client built do not apply.
///
/// # Hooks
///
/// After the checks, the staged objects become durable. At the same time, if
/// `[ex-ostrya] keep-detached-related` of the repository is `false`, this
/// function drops `ostrya.related` from the dict of each staged commit of the
/// set, and plans the merge of that dict with no signature. A merged dict
/// over the size limit is `limit-exceeded`, before the hook. If `hooks` are
/// given, [`ReceiveHooks::before_server_commit`] runs next with the server
/// commit, the canonical name of its branch and of each tag, and the sorted
/// attachments. If the hook refuses, the session ends with the code of the
/// refusal. The default method of the trait refuses with `ref-denied`, so a
/// host without the method refuses each server commit at this step.
///
/// If a failure occurs after the hook, the carried value drops once. If the
/// update lock is held, it drops after the release of the lock.
/// `after_update` does not run.
///
/// # Under the update lock
///
/// Then this function takes the update lock and reads the refs. At the same
/// time, it reads the stored dict of each planned merge again and queues the
/// merge in the transaction. The checks of the ref paths of
/// [`finish`](super::finish::finish) apply, with a write to each ref. The
/// branch comes first, then each tag in order:
///
/// - `orphan` on a branch that is present needs `d` on the branch
///   (`non-fast-forward`).
/// - A tag that is present is `ref-mismatch`.
///
/// Then this function builds the commit. Its parent is the commit of the
/// branch, or none with `orphan` or for an absent branch. Its metadata comes
/// from the commit builder that the tree push to a bucket repository also
/// uses. The `ostree.ref-binding` holds the name of the branch and of each
/// tag without the `@ID:` part, and each bound name. The
/// `ostree.collection-binding` is the id of the namespace of the branch: the
/// collection id of the repository for a local ref, with no key in a
/// repository with no collection id. Field 2 holds the attachments of the
/// client, sorted by name in byte order. Its timestamp is the value of the
/// client, else the system clock. Before the build, if a stored dict of a
/// planned merge changed after the plan, a merged dict over the size limit
/// is `limit-exceeded`. The server keys of the rule sign the commit, and no
/// other commit. The branch moves to the commit, and each tag is created at
/// the commit. A bound name gets no ref. A failure of the build is
/// `internal`.
///
/// The steps of [`publish`] follow. The commits of the session are the new
/// commit and each staged commit of the set. The report holds the outcome of
/// the branch, then the outcome of each tag.
///
/// # After the update lock
///
/// [`publish`] releases the update lock. If `hooks` are given,
/// [`ReceiveHooks::after_update`] runs next with the report and the carried
/// value. An error of the hook is `internal`, with the message cut at 4096
/// bytes at a character boundary. After an error of the hook, the refs stay
/// written.
pub(super) async fn finish(
    repo: &Repo,
    policy: &dyn SessionPolicy,
    hooks: Option<&dyn ReceiveHooks>,
    txn: Transaction,
    named: Named<'_>,
    mut commit_meta: HashMap<Checksum, Vec<u8>>,
    request: CommitRequest,
) -> Checked<ReceiveCommit> {
    let CommitRequest {
        updates,
        force,
        server_commit,
    } = request;
    let Some(mut sc) = server_commit.map(|sc| *sc) else {
        unreachable!("the commit of a session passes a request with a server commit")
    };
    let own = repo.config().collection_id();
    let indices = check_names(own, &named, &sc, updates.len(), force)?;
    let paths: Arc<[String]> = indices.iter().map(|&i| named.paths[i].clone()).collect();
    check_metadata(&sc)?;
    let related = std::mem::take(&mut sc.related);
    let related = related::sorted_new(related).map_err(|e| protocol(e.to_string()))?;
    check_reply_fits(&sc)?;
    let staged_commits = txn.staged_of_type(ObjectType::Commit);
    let set = attachment_set(&txn, &related, &staged_commits).await?;
    check_session_objects(&staged_commits, &mut commit_meta, &set, &related)?;
    drop(staged_commits);
    // The client text of each name goes into the reply. The server commit
    // keeps the canonical names.
    let ServerCommit {
        branch: branch_text,
        tags: tag_texts,
        bind_refs,
        root_dirtree,
        root_dirmeta,
        subject,
        body,
        metadata,
        timestamp,
        orphan,
        ..
    } = sc;
    let mut names = indices.iter().map(|&i| named.refs[i].clone());
    let sc = ReceiveServerCommit {
        branch: names.next().expect("a server commit names its branch"),
        tags: names.collect(),
        bind_refs,
        root_dirtree,
        root_dirmeta,
        subject,
        body,
        metadata,
        related,
        timestamp,
        orphan,
    };
    drop(indices);
    for name in std::iter::once(&sc.branch).chain(&sc.tags) {
        check_anchor(own.is_some(), name)?;
    }
    let rule = policy.server_commit_rule(&sc.branch, &sc.tags)?;
    let Attachments {
        staged,
        below,
        held,
    } = set;
    check_attachment_states(
        &attachment_names(&sc.related, &below),
        &held,
        "the server commit and the attachments below it name as attachments",
    )?;
    drop((below, held));
    let roots = staged.iter().map(|(_, root)| *root);
    let root = (sc.root_dirtree, sc.root_dirmeta);
    let missing = walk::completeness(&txn, std::iter::once(root).chain(roots)).await?;
    if missing.total > 0 {
        return Err(missing_objects(
            missing,
            "the trees of the server commit and of its staged attachments reach",
        ));
    }
    let staged: Vec<Checksum> = staged.into_iter().map(|(commit, _)| commit).collect();
    let (synced, edits) =
        futures_lite::future::zip(txn.sync_staged(), attachment_edits(repo, commit_meta)).await;
    synced.map_err(Failure::Internal)?;
    let edits = edits?;

    // Declared before the update lock, so on each failure the carried value
    // drops after the lock is released. On success it goes to `after_update`,
    // after the lock is released.
    let carried: Option<Box<dyn Any + Send>> = match hooks {
        None => None,
        Some(hooks) => Some(
            hooks
                .before_server_commit(&sc)
                .await
                .map_err(HookRefusal::into_failure)?,
        ),
    };
    let held = repo.lock_update().await.map_err(Failure::Internal)?;
    let anchor = policy.regenerates_summary() && repo.config().collection_id().is_some();
    // The read of the refs and the queue of the detached metadata are
    // independent, so they run at the same time. A failure of the refs comes
    // first.
    let (states, queued) = futures_lite::future::zip(
        repo.read_ref_states(Arc::clone(&paths), anchor.then_some(OSTREE_METADATA_REF)),
        async {
            if edits.is_empty() {
                return Ok(());
            }
            queue_detached(repo, &txn, edits).await
        },
    )
    .await;
    let (states, anchor_parent) = states.map_err(Failure::Internal)?;
    let written: Vec<(&str, &str, bool)> = std::iter::once(branch_text.as_str())
        .chain(tag_texts.iter().map(String::as_str))
        .zip(paths.iter())
        .map(|(name, path)| (name, path.as_str(), true))
        .collect();
    let current = check_ref_paths(&written, &states)?;
    drop(written);
    let tip = current[0];
    if let Some(tip) = tip
        && sc.orphan
        && !rule.allow_orphan_over_branch
    {
        return Err(Failure::Wire(remote::Error::NonFastForward(format!(
            "ref '{branch_text}' is at {tip}, and the policy does not allow a commit with no \
             parent on it"
        ))));
    }
    for (tag, current) in tag_texts.iter().zip(&current[1..]) {
        if let Some(commit) = current {
            return Err(Failure::Wire(remote::Error::RefMismatch {
                message: format!(
                    "ref '{tag}' is at {commit}, and a tag of a server commit creates its ref"
                ),
                name: tag.clone(),
                current: Some(*commit),
            }));
        }
    }
    queued?;

    let collection_id = match &sc.branch {
        Ref::Collection { id, .. } => Some(id.as_str()),
        _ => own,
    };
    let timestamp = match sc.timestamp {
        Some(timestamp) => timestamp,
        None => clock().map_err(Failure::Internal)?,
    };
    let fields = CommitFields {
        refs: std::iter::once(&sc.branch)
            .chain(&sc.tags)
            .map(Ref::name)
            .chain(sc.bind_refs.iter().map(String::as_str))
            .collect(),
        root_dirtree: sc.root_dirtree,
        root_dirmeta: sc.root_dirmeta,
        subject: &sc.subject,
        body: &sc.body,
        metadata: &sc.metadata,
        related: &sc.related,
        orphan: sc.orphan,
    };
    let bytes = Arc::new(
        commit_bytes(&fields, tip, timestamp, collection_id)
            .map_err(|e| Failure::Internal(e.into()))?,
    );
    drop(fields);
    // The commit bytes hold the other fields of the server commit. They are
    // freed here, so they are not held while the hook of the host runs.
    let ReceiveServerCommit {
        branch,
        tags,
        bind_refs,
        subject,
        body,
        metadata,
        related,
        ..
    } = sc;
    drop((bind_refs, subject, body, metadata, related));
    let commit = txn
        .write_metadata(ObjectType::Commit, None, &bytes)
        .await
        .map_err(Failure::Internal)?;
    sign_server_commit(repo, &txn, commit, &bytes, rule.signers).await?;
    drop(bytes);

    let moves = tip != Some(commit);
    if moves {
        txn.set_ref(&branch, Some(&commit));
    }
    for tag in &tags {
        txn.set_ref(tag, Some(&commit));
    }
    let changed = moves || !tags.is_empty();
    // The future of the publication is large. The box keeps it out of the
    // future of the checks.
    let (stats, warnings) = Box::pin(publish(
        repo,
        policy,
        txn,
        held,
        changed,
        anchor_parent,
        std::iter::once(commit).chain(staged).collect(),
    ))
    .await?;
    // The state of the checks is freed here, so it is not held while the
    // hook of the host runs.
    drop((paths, states, current));

    let refs = std::iter::once((branch, tip))
        .chain(tags.into_iter().map(|tag| (tag, None)))
        .map(|(name, old)| ReceiveRefOutcome {
            name,
            old,
            new: Some(commit),
        })
        .collect();
    let reply = outcomes(branch_text, tag_texts, tip, commit);
    let report = report(policy, refs, stats, warnings);
    if let (Some(hooks), Some(carried)) = (hooks, carried)
        && let Err(mut message) = hooks.after_update(&report, carried).await
    {
        hooks::cut(&mut message);
        return Err(Failure::Wire(remote::Error::Internal(message)));
    }
    Ok(ReceiveCommit { report, reply })
}

/// Returns the names of the refs of `sc`, as the client sent them: the
/// branch, then each tag.
fn refs(sc: &ServerCommit) -> impl Iterator<Item = &str> {
    std::iter::once(sc.branch.as_str()).chain(sc.tags.iter().map(String::as_str))
}

/// Returns the outcomes of a server commit: the branch from `tip` to
/// `commit`, then each tag from absent to `commit`.
fn outcomes(
    branch: String,
    tags: Vec<String>,
    tip: Option<Checksum>,
    commit: Checksum,
) -> Vec<RefOutcome> {
    std::iter::once(RefOutcome {
        name: branch,
        old: tip,
        new: Some(commit),
    })
    .chain(tags.into_iter().map(|name| RefOutcome {
        name,
        old: None,
        new: Some(commit),
    }))
    .collect()
}

/// Returns the `invalid-ref` failure of `name`, or the failure on the server
/// side of an error that is not a refusal of the name.
fn name_failure(e: Error, what: &str, name: &str) -> Failure {
    match e {
        Error::InvalidRefspec(_) => Failure::Wire(remote::Error::InvalidRef(format!(
            "invalid {what} '{name}'"
        ))),
        other => Failure::Internal(other),
    }
}

/// Checks the names of `sc` and the form of the message, and returns the
/// index in `named` of the branch, then of each tag.
///
/// `own` is the collection id of the repository. `updates` is the number of
/// ref updates of the message, and `force` is its `force` flag.
///
/// - The branch and each tag are refs, and no local ref among them is 64
///   lowercase hex characters, after the map of `@ID:NAME` with `ID` `own`
///   to the local ref `NAME` (`invalid-ref`).
/// - Each bound name passes the refspec rule and has no `:` (`invalid-ref`).
/// - The message holds no update and no `force` (`protocol`).
/// - The branch and each tag are refs of `Hello`, with the text of `Hello`,
///   and none occurs two times among them (`protocol`).
/// - The branch and each tag are in one namespace (`protocol`).
fn check_names(
    own: Option<&str>,
    named: &Named<'_>,
    sc: &ServerCommit,
    updates: usize,
    force: bool,
) -> Checked<Vec<usize>> {
    for name in refs(sc) {
        commit_ref(own, name, true)?;
    }
    for name in &sc.bind_refs {
        crate::validate_refspec(name).map_err(|e| name_failure(e, "bound name", name))?;
        if name.contains(':') {
            return Err(Failure::Wire(remote::Error::InvalidRef(format!(
                "invalid bound name '{name}'"
            ))));
        }
    }
    if updates > 0 {
        return Err(protocol(format!(
            "the Commit message holds a server commit and {updates} ref updates"
        )));
    }
    if force {
        return Err(protocol(
            "the Commit message holds a server commit and force".into(),
        ));
    }
    let found = Named::indices(&named.by_name(), refs(sc), "written")?;
    let branch = &named.refs[found[0]];
    for &i in &found[1..] {
        let tag = &named.refs[i];
        if !tag.same_namespace(branch) {
            return Err(protocol(format!(
                "tag '{tag}' is not in the namespace of the branch '{branch}' of the server \
                 commit"
            )));
        }
    }
    Ok(found)
}

/// Checks that a commit can hold each metadata value of `sc` (`protocol`).
///
/// The bytes of each value must be a `v` in normal form, which the decoder
/// of the message checks with the depth limit of a `v`. In a commit, the
/// `v` is two levels deeper, so this check applies the depth limit of the
/// commit. The commit takes the bytes of each value as they are, so without
/// this check a value that is too deep gives a commit that does not parse.
fn check_metadata(sc: &ServerCommit) -> Checked<()> {
    for (key, value) in &sc.metadata {
        validate(&VALUE_IN_COMMIT, value).map_err(|e| {
            protocol(format!(
                "a commit cannot hold the metadata value under '{key}': {e}"
            ))
        })?;
    }
    Ok(())
}

/// Checks that the `CommitReply` of `sc` fits in a frame of [`MAX_FRAME`].
///
/// The reply holds the branch with an old commit and each tag with no old
/// commit. A tag that is present fails under the lock, so this is the longest
/// reply. A reply over the limit is `limit-exceeded`.
fn check_reply_fits(sc: &ServerCommit) -> Checked<()> {
    let any_commit = Checksum::from_bytes([0; 32]);
    let longest = Message::CommitReply(outcomes(
        sc.branch.clone(),
        sc.tags.clone(),
        Some(any_commit),
        any_commit,
    ));
    let body = longest.encode_body().map_err(Failure::Wire)?;
    let len = body.len() as u64 + 1;
    if len > u64::from(MAX_FRAME) {
        return Err(Failure::Wire(remote::Error::LimitExceeded(format!(
            "the reply to the server commit with {} tags can need a frame of {len} bytes, over \
             the limit {MAX_FRAME}",
            sc.tags.len()
        ))));
    }
    Ok(())
}

/// Checks the commit objects and the detached metadata dicts of the session
/// against the attachments `set` of the server commit, whose field 2 is
/// `related` (`protocol`).
///
/// - Each detached metadata dict is for a staged commit of `set`, or for a
///   commit of `set` that the repository holds. The first other dict in the
///   order of the checksums is the refusal.
/// - Each commit of `staged`, the commits that the session staged, is a
///   staged commit of `set`. The first other staged commit in the order of
///   the checksums is the refusal.
///
/// The walk of [`attachment_set`] reads no field 2 of a commit that the
/// repository marks partial, so an object of the session can be below such a
/// commit. If one of these checks fails and `set` holds a commit that the
/// repository marks partial, the failure is the `missing-objects` failure of
/// the first such commit in level order, as [`check_attachment_states`]
/// gives it.
///
/// Then the call drops each dict of a held commit from `commit_meta`, so
/// that dict gets no merge and no write. The repository held the commit and
/// its dict before the session. Each dict that stays is for a staged commit
/// of `set`.
fn check_session_objects(
    staged: &[Checksum],
    commit_meta: &mut HashMap<Checksum, Vec<u8>>,
    set: &Attachments,
    related: &[(String, Checksum)],
) -> Checked<()> {
    let members: HashSet<&Checksum> = set.staged.iter().map(|(commit, _)| commit).collect();
    let held = |commit: &Checksum| {
        set.held
            .get(commit)
            .is_some_and(|state| *state != HeldAttachment::Absent)
    };
    let dict = commit_meta
        .keys()
        .filter(|commit| !members.contains(commit) && !held(commit))
        .min();
    let commit = staged
        .iter()
        .filter(|commit| !members.contains(commit))
        .min();
    if (dict.is_some() || commit.is_some())
        && set
            .held
            .values()
            .any(|state| *state == HeldAttachment::Partial)
        && let Some(failure) =
            partial_attachment_failure(&attachment_names(related, &set.below), &set.held)
    {
        return Err(failure);
    }
    if let Some(commit) = dict {
        return Err(protocol(format!(
            "detached metadata for commit {commit} in a session with a server commit: the \
             commit is not a staged or held attachment of the server commit"
        )));
    }
    if let Some(commit) = commit {
        return Err(protocol(format!(
            "commit {commit} is staged in a session with a server commit, and is not an \
             attachment of the server commit"
        )));
    }
    commit_meta.retain(|commit, _| members.contains(commit));
    Ok(())
}

/// The attachments of a server commit, as [`attachment_set`] reads them.
#[derive(Default)]
struct Attachments {
    /// Each staged commit of the set, with its root dirtree and root dirmeta,
    /// in level order.
    staged: Vec<(Checksum, (Checksum, Checksum))>,
    /// Each commit of the set below the first level, the commit that first
    /// names it, and the name of that entry, in level order.
    below: Vec<(Checksum, Checksum, String)>,
    /// The state of each commit of the set that the session did not stage.
    held: HashMap<Checksum, HeldAttachment>,
}

/// Returns each commit of the set of attachments, the commit that first
/// names it, and the name of that entry, in level order.
///
/// The first level comes from `related`, field 2 of the server commit, and
/// has no naming commit. `below` holds the levels below it, as
/// [`Attachments`] holds them.
fn attachment_names<'a>(
    related: &'a [(String, Checksum)],
    below: &'a [(Checksum, Checksum, String)],
) -> Vec<(Checksum, Option<Checksum>, Cow<'a, str>)> {
    let mut known = HashSet::new();
    related
        .iter()
        .filter(|(_, attachment)| known.insert(*attachment))
        .map(|(name, attachment)| (*attachment, None, Cow::Borrowed(name.as_str())))
        .chain(below.iter().map(|(attachment, naming, name)| {
            (*attachment, Some(*naming), Cow::Borrowed(name.as_str()))
        }))
        .collect()
}

/// Reads the full set of attachments of a server commit whose field 2 is
/// `related`.
///
/// The set holds the attachments that `related` names, then the attachments
/// that field 2 of each of these commits names, one level at a time, until a
/// level is empty. `staged` holds the commits that the session staged. The
/// walk reads field 2 of a staged commit from the staging directory, and of a
/// held commit with no partial marker from the object store. It reads field
/// 2 of no held commit with a partial marker, and of no absent commit. It
/// reads each commit object one time, reads no tree, and builds no value
/// tree of a metadata dict. All reads run in one trip to the blocking pool.
/// With an empty `related`, the call reads nothing.
///
/// # Errors
///
/// - `protocol` for a staged commit of the set that does not parse, or for
///   an entry of its field 2 with an empty name or with a checksum that is
///   not 32 bytes.
/// - `internal` for such an entry in field 2 of a held commit, and for each
///   error of a read.
async fn attachment_set(
    txn: &Transaction,
    related: &[(String, Checksum)],
    staged: &[Checksum],
) -> Checked<Attachments> {
    if related.is_empty() {
        return Ok(Attachments::default());
    }
    let repo = txn.repo().clone();
    let staging = txn.staging_dir().clone();
    let staged: HashSet<Checksum> = staged.iter().copied().collect();
    let mut known = HashSet::new();
    let first: Vec<Checksum> = related
        .iter()
        .map(|(_, attachment)| *attachment)
        .filter(|attachment| known.insert(*attachment))
        .collect();
    ostrya_rt::unblock(move || attachment_levels_blocking(&repo, &staging, &staged, first)).await
}

/// Walks the attachments below the first level `first` on the calling
/// thread, as [`attachment_set`] states.
///
/// `staging` is the staging directory of the session, and `staged` holds
/// each commit that the session staged. `first` holds each commit of the
/// first level one time.
fn attachment_levels_blocking(
    repo: &Repo,
    staging: &RepoDir,
    staged: &HashSet<Checksum>,
    first: Vec<Checksum>,
) -> Checked<Attachments> {
    let mut set = Attachments::default();
    let mut known: HashSet<Checksum> = first.iter().copied().collect();
    let mut level = first;
    while !level.is_empty() {
        let mut next = Vec::new();
        for attachment in level {
            let entries = if staged.contains(&attachment) {
                let flat = flat_name(&attachment, ObjectType::Commit, repo.mode());
                let bytes = staging
                    .read_capped(&flat, MAX_METADATA_SIZE)
                    .map_err(|e| Failure::Internal(e.into()))?;
                let unparsable = |e| protocol(format!("commit {attachment} does not parse: {e}"));
                let links = parse_commit_links(&bytes).map_err(unparsable)?;
                set.staged.push((attachment, links.root));
                checked_link_attachments(&attachment, links.related).map_err(|e| match e {
                    Error::Core(e) => unparsable(e),
                    e => protocol(e.to_string()),
                })?
            } else {
                let state =
                    related::held_attachment_blocking(repo, None, &attachment, |_, entries| {
                        related::checked_entries(
                            RelationField::Attachments,
                            Some(attachment),
                            entries,
                        )
                    })
                    .map_err(Failure::Internal)?;
                let (state, entries) = match state {
                    HeldAttachment::Absent => (HeldAttachment::Absent, Vec::new()),
                    HeldAttachment::Partial => (HeldAttachment::Partial, Vec::new()),
                    HeldAttachment::Complete { value } => {
                        (HeldAttachment::Complete { value: () }, value)
                    }
                };
                set.held.insert(attachment, state);
                entries
            };
            for (name, below) in entries {
                if known.insert(below) {
                    next.push(below);
                    set.below.push((below, attachment, name));
                }
            }
        }
        level = next;
    }
    Ok(set)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ostrya_core::{Commit, Value, to_bytes};

    /// An entry of the client: `key` and the bytes of the `v` `value`.
    fn entry(key: &str, value: Value) -> (String, Vec<u8>) {
        (key.into(), to_bytes(&Type::Variant, &value).unwrap())
    }

    /// A server commit on `main` with the metadata `metadata`.
    fn with_metadata(metadata: Vec<(String, Vec<u8>)>) -> ServerCommit {
        ServerCommit {
            branch: "main".into(),
            tags: Vec::new(),
            bind_refs: Vec::new(),
            root_dirtree: Checksum::from_bytes([1; 32]),
            root_dirmeta: Checksum::from_bytes([2; 32]),
            subject: String::new(),
            body: String::new(),
            metadata,
            related: Vec::new(),
            timestamp: None,
            orphan: false,
        }
    }

    /// The metadata check accepts a value exactly when a commit that holds
    /// it serializes and parses. The deepest value that a commit holds is a
    /// `y` under 125 levels of maybe.
    #[test]
    fn the_metadata_check_follows_the_depth_of_a_commit() {
        for levels in 123..=127 {
            let ty = (0..levels).fold(Type::Byte, |ty, _| Type::maybe(ty));
            let value = (0..levels).fold(Value::Byte(1), |value, _| {
                Value::Maybe(Some(Box::new(value)))
            });
            let value = Value::variant(ty, value);
            let commit = Commit {
                metadata: Value::Array(vec![Value::Tuple(vec![
                    Value::Str("deep".into()),
                    value.clone(),
                ])]),
                parent: None,
                related: Vec::new(),
                subject: String::new(),
                body: String::new(),
                timestamp: 0,
                root_dirtree: Checksum::from_bytes([1; 32]),
                root_dirmeta: Checksum::from_bytes([2; 32]),
            };
            let sc = with_metadata(vec![entry("deep", value)]);
            let checked = check_metadata(&sc);
            assert_eq!(checked.is_ok(), levels <= 125, "{levels} levels");
            let bytes = commit.serialize();
            assert_eq!(bytes.is_ok(), levels <= 125, "{levels} levels");
            if let Ok(bytes) = bytes {
                assert_eq!(Commit::parse(&bytes).unwrap(), commit, "{levels} levels");
            }
            if levels > 125 {
                assert!(
                    matches!(checked, Err(Failure::Wire(remote::Error::Protocol(_)))),
                    "{levels} levels"
                );
            }
        }
    }

    /// The reply bound of a server commit is exact: the largest count of
    /// tags that passes gives a reply that fits, and one tag more does not.
    #[test]
    fn the_reply_bound_of_a_server_commit_is_the_encoded_size() {
        let commit = |count: usize| ServerCommit {
            tags: (0..count).map(|i| format!("tag-{i:015}")).collect(),
            ..with_metadata(Vec::new())
        };
        let encoded = |count: usize| {
            let sc = commit(count);
            let any = Checksum::from_bytes([3; 32]);
            Message::CommitReply(outcomes(sc.branch, sc.tags, Some(any), any))
                .encode_body()
                .unwrap()
                .len()
                + 1
        };
        let (mut low, mut high) = (0, 30_000);
        assert!(check_reply_fits(&commit(low)).is_ok());
        assert!(check_reply_fits(&commit(high)).is_err());
        while high - low > 1 {
            let mid = (low + high) / 2;
            if check_reply_fits(&commit(mid)).is_ok() {
                low = mid;
            } else {
                high = mid;
            }
        }
        assert!(encoded(low) <= MAX_FRAME as usize);
        assert!(encoded(high) > MAX_FRAME as usize);
        match check_reply_fits(&commit(high)) {
            Err(Failure::Wire(remote::Error::LimitExceeded(m))) => {
                assert!(m.contains(&format!("{high} tags")), "{m}")
            }
            _ => panic!("expected limit-exceeded"),
        }
    }
}