Skip to content

manifest: add new "join" command for joining multiple manifests into one - #44612

Open
poettering wants to merge 5 commits into
systemd:mainfrom
poettering:manifest-join
Open

poettering wants to merge 5 commits into
systemd:mainfrom
poettering:manifest-join

Conversation

@poettering

Copy link
Copy Markdown
Member

No description provided.

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Reviewed b32fcbb (api, architecture, correctness, lifetimes, security, style, tests). All findings are resolved 🎉

Must fix

Workflow run

Comment thread src/manifest/manifest-join.c Resolved
Comment thread src/systemctl/systemctl-mount.c Resolved
@poettering
poettering force-pushed the manifest-join branch 2 times, most recently from 91a853c to dd56779 Compare November 5, 2026 13:31
@github-actions github-actions Bot removed the tree-wide label Nov 5, 2026
Comment thread src/manifest/manifest.c Resolved
@daandemeyer

Copy link
Copy Markdown
Collaborator

codex review:

Reviewed at dd56779. I built it and ran the new unit tests (they pass) and tried the cases below against the built systemd-manifest.

Bugs

1. Can join handle names with 100 or more components?

manifest_join() calls recurse_dir() with n_depth_max=UINT_MAX, which maps to DEFAULT_RECURSION_MAX (100). Every object becomes a directory in tree/, so the file at the bottom costs a level too, and join_write_item() turns RECURSE_DIR_SKIP_DEPTH into a fatal error. make only depth-checks directories, so it happily lists such a file:

d=t; for i in $(seq 1 99); do d=$d/a; done; mkdir -p $d; echo x >$d/f
systemd-manifest make t m      # succeeds
systemd-manifest join m out    # Maximum directory depth reached at 'a/a/…/f', refusing.

With 98 levels both succeed. Other producers can emit names with up to ~2047 components, and the failure only shows up after all inputs were written to the database. Should the walk use a larger explicit bound, with input names capped to match?

Related: with a name nested deeper than RLIMIT_NOFILE (e.g. 1500 components with ulimit -n 1024), rm_rf_children() in join_context_done() runs out of fds and the manifest-join-XXXXXX directory is left behind in /var/tmp. A depth cap on input names would fix both.

2. Should objects be compared as raw JSON?

dispatch_uapi16_object() says null fields are equivalent to absent ones, but join_object_handler() compares with sd_json_variant_equal(), so these conflict:

{"name":"b","size":0}  vs  {"name":"b","size":0,"type":"reg"}   -> differing fields: type
{"name":"b","size":0}  vs  {"name":"b","size":0,"uid":null}     -> differing fields: uid

And since join_resolve_mtime() keeps the stored definition on a tie, {"name":"b","size":0} joined with {"name":"b","size":0,"mTimeNSec":null} produces different bytes depending on which input comes first. That contradicts "the output only depends on the set of objects in the inputs". make never emits these forms, so this only matters for other producers.

3. Is the conflict count meant to count objects?

n_conflicts is incremented per conflicting definition. One object with three different sizes in three inputs reports "Found 2 conflicting objects".

Design

4. Is join INPUT… OUTPUT the right shape?

systemd-manifest join a.m b.m, meant as "join to stdout", replaces b.m with the canonical form of a.m alone, and b.m is never read. If b.m was signed with a key the user doesn't have, it's gone. make and verify default their trailing path to stdout/stdin, so the argument count can't catch this. Would join INPUT… to stdout plus --output= (as in systemd-sbsign and systemd-keyutil) work better? Related: an input of - is opened as a file named - (whereas verify reads stdin), "" is accepted as stdout for the output, and --graceful is silently accepted.

5. Is the union of hardlink groups intended even when the inputs disagree?

mkdir h1 h2; echo x >h1/a; ln h1/a h1/b; echo x >h2/a; echo x >h2/b
systemd-manifest make h1 hm1; systemd-manifest make h2 hm2
systemd-manifest join hm1 hm2 hj
systemd-manifest verify --verify-signature=no h2 hj   # b: Inode token 1 in manifest already used by a different inode, not a hardlink.

So joining a manifest of a tree with one of the same tree after a hardlink was broken yields a manifest that doesn't match the new tree. Hardlinks are the only field where disagreement neither conflicts nor resolves to one input. Would treating it as a conflict, or dropping the token where inputs disagree, fit better?

6. How large are the manifests this is meant for?

Each object costs a file in objects/, a directory in tree/ (plus one per unlisted parent) and up to two symlinks. On ext4 that's roughly 8 KiB and 2 inodes per object, so a 1M-object manifest needs on the order of 8 GB and 2M inodes in /var/tmp, and a single crafted object can create ~2000 directories. readdir_all() with RECURSE_DIR_SORT also loads each directory listing into memory, so a flat manifest still uses memory per object. Since make and join output is already sorted, would a streaming k-way merge of sorted inputs (refusing or pre-sorting unsorted ones) be an option?

Simplifications

  • join_object_key() is sha256_direct_hex(name, SIZE_MAX).
  • JoinContext.db_fd/db_path and their setup/cleanup duplicate ManifestContext.db_fd/db_path, hardlink_db_acquire() and manifest_context_done(). Could join use the context's database instead?
  • verb_join() repeats the signing block of verb_make() (load_certificate()/load_private_key() under #if HAVE_OPENSSL), the output handling (fopen_tmpfile_linkable(), pager, flink_tmpfile()), the --certificate= without --private-key= check and the JSON default. There's no combined loader in crypto-util.h, but two static helpers in manifest.c would keep the verbs in sync.
  • mkdirat_p() has a single caller, and chaseat(tree_fd, tree_fd, name, CHASE_MKDIR_0755, NULL, NULL) already does this (0755 is fine inside the 0700 temp dir). As a general helper it also accepts .. and absolute paths and follows symlinks, which its comment doesn't mention.
  • PATH_REFUSE_TRAILING_SLASH has a single caller, which already refuses /. || endswith(s, "/") in uapi16_name_is_valid() would do the same.
  • join_load_object() opens a FILE that sd_json_parse_file_at() would open itself from dir_fd and path.
  • dispatch_mtime() re-parses the incoming object's mTimeNSec, which is already in o->mtime_nsec.

Docs, comments, tests

  • The man page doesn't say join refuses --field=, --hash= and --voa-context=. The join section even says "see --field=".
  • "does not verify the inputs in any way" is a bit strong: the parser still refuses malformed input (the echo garbage test relies on that).
  • Objects of unknown media type are dropped by uapi16_manifest_read(), so the output isn't quite "the union of all objects". Should the man page say so?
  • The layout comment says tree/ has "an empty directory for each object", but the directories contain their children, and unlisted parents get one too.
  • The join_write_item() comment says any enumeration failure is fatal, but the SKIP_OPEN_INODE/SKIP_STAT_INODE events fall through to RECURSE_DIR_CONTINUE.
  • The --help header and <refpurpose> still say "Generate and verify".
  • "uapi16-manifest: refuse object names with trailing slashes": the spec says "MUST NOT start or end with a slash", which might be worth quoting. The same check now also applies to contents[].file.
  • No test that the parser refuses "a/", none for RECURSE_DIR_SEEK0 being masked for subdirectories in recurse_dir(), and none for null or tied mtimes in join.
  • The comment in manifest-join.h breaks after "combined across inputs. The", and the --private-key= paragraph wasn't reflowed after the edit.

Open questions

  • A single-input join re-sorts objects by strcmp(). The spec allows version or time ordering within a directory, and repart writes GPT manifests in partition order. Does any consumer rely on object order?
  • If $TMPDIR is casefolded, A and a share one tree/ directory, and join_write_object() skips the missing key with only a debug message. Would comparing the number of written objects with n_objects be worth it?

@daandemeyer daandemeyer added reviewed/needs-rework 🔨 PR has been reviewed and needs another round of reworks and removed please-review PR is ready for (re-)review by a maintainer labels Nov 9, 2026
@poettering

Copy link
Copy Markdown
Member Author

I addressed many of codex' points (but it seems to me the quality is a bit lower than claude's), and rebased on top of your certificate/priv key loading work. ptal.

@poettering poettering added please-review PR is ready for (re-)review by a maintainer and removed reviewed/needs-rework 🔨 PR has been reviewed and needs another round of reworks labels Nov 11, 2026
path_is_normalized() accepts trailing slashes, which is generally the
right thing to do, since a trailing slash carries meaning: the path must
refer to a directory. However, sometimes we want the fully canonical form
of a path, where the same path written with and without the slash is not
considered two distinct normalized paths. Add a flag for that.

The root directory "/" is accepted even with the flag set, since it has
no other form.
The specification requires object names to be normalized paths. Let's
insist on the fully canonical form, so that the same object cannot be
named in two different ways, with and without trailing slash.
This rewinds the directory fd before reading it. That's useful if the fd
was read before, but also if entries were added to the directory since
it was opened: btrfs only returns entries that existed when the
directory was opened, until the fd is rewound.

recurse_dir() only rewinds the top-level fd, subdirectories are opened
freshly anyway.
Uapi16Object deliberately omits a bunch of fields the specification
defines, as well as any extension fields. Consumers that need to look at
or pass along the complete object (such as the upcoming manifest joining
logic) hence had no way to get at it. Let's keep a reference to the JSON
object the structure was parsed from.
This joins multiple UAPI.16 manifests into one. Objects listed in more
than one input must be identical (except for their inode tokens),
otherwise the join fails. The only exception are modification times: if
two definitions of an object differ in that only, the newest one wins.
Hardlink groups are combined across inputs, transitively: if one input
says X and Y are hardlinked, and another one says Y and Z are, all three
end up in the same group.

The inputs are not verified in any way: signatures are ignored and
dropped, and beyond the identity of objects listed multiple times no
consistency checks are made. That's what "verify" is for. The output is
signed if --private-key= is specified.

To process manifests of arbitrary size without holding them in memory,
the objects are collected in a temporary database directory below
/var/tmp/. It mirrors the object names as a directory tree, so that
walking it sorted yields the objects in the very same order "make"
generates them. Hence the output is deterministic, regardless of the
order of the inputs and of the objects within them, and joining the
manifest of a tree with a manifest of the same tree after files have
been added to it results in the latter. With a single input this is a
way to sign, re-sign or unsign a manifest.

@brauner brauner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After our discussion on Sunday, I looked at how join behaves with very large
manifests since as I have similar design questions in ufat.

So really, I had this gun cocked and loaded. I'm sorry.

So let's say you have a manifest describing the dataset for an LLM with tens
of millions of objects. I had Claude build the PR and measured
systemd-manifest join on xfs with an LD_PRELOAD shim that counts calls and
stops the process right before it removes its database.

The union-find for the hardlink groups can go quadratic. join_group_find()
does neither path compression nor union by rank. Instead, a merge always links
the higher root to the lower one so the chain from a group to its root can get
as long as the number of groups, and join_group_find() walks it with one
readlinkat() per hop. join_write_object() does that walk for every object
that has an inode token.

The first lists n pairs of hardlinked files, b1/c1 up to bn/cn, in name
order. The second lists only b1 to bn, all hardlinked to each other, in
reverse name order. The man page says the order of objects within an input
doesn't matter so that's a valid input:

objects    readlinkat()    time
   2000          1.5M      2.0s
   4000          6.0M      6.9s
   8000           24M       27s
  16000           96M      104s

At a million objects that's about 4 * 10^11 calls, which going by these numbers
takes days...

A single input does it too if it repeats names with the inode tokens of other
objects. uapi16_manifest_read() doesn't refuse duplicate names and the two
definitions compare equal once the inode token is filtered out. 8000 such
objects take 36s.

With both inputs sorted it stays at 8 calls per object, 16000 objects in 3.7s.
I tried pointing every group join_group_find() walks past at the root (with
symlinkat_atomic_full()) and that fixes it. Then it's 12 calls per object,
4.0s for the 16000 objects in reverse order and 2.3s for the 8000 repeated
names, with the same output as before.

The space needed is another problem. Every object costs a file in objects/
and a directory in tree/. So joining a single manifest with 1M objects (142
MiB) peaked at about 4 GiB and 2M inodes in the database and took 4m20s, 58s of
which went to removing the database again.

On ext4 it should be about twice the space since every directory gets a block
of its own. IOW, a manifest with 10M objects is a couple of GB but needs 40-80
GB and 20M inodes in /var/tmp.

And since var_tmp_dir() prefers $TMPDIR all of that ends up in memory if
$TMPDIR is on tmpfs. So 200k objects took 781 MiB of tmpfs, a page per object
plus inodes and dentries, so 40 GB and more for 10M objects.

Memory also still grows with the input. recurse_dir() with RECURSE_DIR_SORT
reads each directory of tree/ in full and keeps the listings of all parents
alive while descending. With 1M files in one directory join peaks at 54 MiB,
with the same files in directories of 1000 at 12 MiB. So a flat 10M file
dataset needs about half a GB for that alone.

Also, a file with 100 components fails with "Failed to enumerate join database:
Too many levels of symbolic links", and only after all inputs have been copied
into the database. So a join that gets killed, for example by SIGPIPE when its
output goes to head, leaves its database behind in /var/tmp until tmpfiles
ages it out. For a large join that's tens of GB.

And objects/ is a single flat directory with a 64 character name per object.
Without large_dir, which isn't enabled by default, ext4's htree has two
levels and I think that runs out somewhere around 10M such names.

Since make writes objects sorted anyway I wonder whether this wouldn't be
better done as an external merge sort? Sort runs that fit into a fixed memory
budget, spill them to a temporary file, and k-way merge them. That's sequential
I/O, about the size of the inputs in temporary space, and memory that doesn't
grow with the input.

Sorted inputs wouldn't need the run phase at all. The hardlink groups don't fit
into a single merge pass because output tokens are numbered by first appearance
and a later object can still tie two groups together. But objects with inode
tokens are usually a small fraction of a manifest and could get a pass of their
own.

@keszybz keszybz added reviewed/needs-rework 🔨 PR has been reviewed and needs another round of reworks and removed please-review PR is ready for (re-)review by a maintainer labels Nov 17, 2026
@keszybz

keszybz commented Nov 17, 2026

Copy link
Copy Markdown
Member

Yep, sounds like the approach with db under /var/tmp is not the right way.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

5 participants