Skip to content

eBPF-based security platform

testing: prove the tree selector overlap checks and the tree state

Daniel Borkmann6d07197be5a8
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rst
index 2c707f76..ce0fcfdc 100644
--- a/Documentation/contribute/testing/proof-coverage.rst
+++ b/Documentation/contribute/testing/proof-coverage.rst
@@ -273,6 +273,74 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.
symbolic bytes.
- The return decision, ordered writes, cursor, tree ID, manifest
and both projection roots match the independent recovery model
+ * - ``bpm-tree-overlap-model``
+ - ``tree_selectors_disjoint()``, ``selector_covers()`` and the list,
+ prefix and pair checks under them
+ - Every two selectors of up to 2 entries a list and a map and 2
+ values a pair, strings up to 2 bytes
+ - The decisions of the Lean model ``Shirudo.TreeOverlap``, which
+ proves them sound for what a node matches
+ * - ``bpm-tree-overlap-live``
+ - ``tree_add_live()``
+ - Publications of up to 3 operations, at every index; an ``op`` of
+ up to 7 bytes, an id of up to 2, selectors of one architecture or
+ none
+ - ``addLive`` of the Lean model ``Shirudo.TreeOverlap``: live until
+ a later operation is a delete of the same upatch whose selector
+ covers its own
+ * - ``bpm-tree-state-match``
+ - ``tree_selector_matches()`` with ``read_config_stream()`` and the
+ two readers that call it
+ - Selectors of up to 2 release prefixes, build IDs and
+ architectures against any release, machine and build ID, and of
+ up to 2 labels against five fixed label lines or labels that
+ cannot be read; strings up to 2 bytes. The node's files are
+ stubs. Not a selector that names a kernel option
+ - 1 exactly where ``selectorMatches`` of the Lean model
+ ``Shirudo.TreeOverlap`` holds, 0 where not, an error only for
+ labels it could not read; the labels closed and their line
+ released
+ * - ``bpm-tree-state-options``
+ - ``selector_hash_build()``, ``selector_hash_find()``
+ - Selectors of up to 2 kernel options, keys up to 2 bytes, a key
+ twice among them
+ - A key is found at the first pair that has it, where the config's
+ value for it is kept, and no other key
+ * - ``bpm-tree-state-pairs``
+ - ``kv_add()``, ``kv_value()``, ``selector_values_match()``,
+ ``hex32_valid()``
+ - A key or a value of 0 to 2, 255 and 256 bytes into 0 to 2 pairs;
+ up to 2 pairs and values of strings up to 2 bytes; digests up to
+ 65 bytes
+ - A pair is added only below its limit and when both strings fit,
+ whole, and a refusal counts nothing; ``kvValue`` and ``listHolds``
+ of the Lean model ``Shirudo.TreeOverlap``; exactly 64 hex digits
+ * - ``bpm-tree-state-pending``
+ - ``tree_pending_parse()``, ``tree_pending_write()``
+ - Any record ``json_parse()`` hands over and every operation
+ ``tree_operation_validate()`` takes, ids up to 8 bytes; the
+ emitter, the directory or the write failing. ``util/json.c`` is a
+ stub that passes keys and values
+ - Takes exactly a whole record of schema 1 with a positive seq, an
+ upatch name and a sha256 digest; writes schema 1 and the
+ operation's seq, id and digest once, which reads back as the
+ operation's
+ * - ``bpm-tree-state-replay``
+ - ``tree_event_replay()``
+ - Tree eventlogs of 0 to 3 lines of any records; the read or the
+ hash failing. The JSON of a line, ``util/hex.c`` and SHA-256 are
+ stubs
+ - ``replayFrom`` of the Lean model ``Shirudo.TreeSync``: the root
+ exactly when each line has its fields, a sequence number above
+ the one before and the hash of the root before and its digest as
+ its root; a refusal writes nothing and reads no further line
+ * - ``bpm-tree-state-replay-lines``
+ - ``tree_event_replay()`` with ``lines_len()``
+ - Tree eventlogs of 0 to 4 and 6 bytes, any bytes, whose lines hold
+ records that replay but for one at most
+ - Each whole line read once and in order, nothing of a last line
+ without its newline; a log with a NUL refused unread; the log
+ released once
* - ``bpm-upatch-member``
- ``bpm_upatch_member()``, ``bpm_upatch_pair()``
- Lengths 0 to 18
@@ -1049,8 +1117,30 @@ the model follows the C.
succeeds; an extend and its eventlog record are one write
- CBMC: ``bpm-tree-follows`` for ``tree_publication_follows()``,
``bpm-tree-sync-model`` and its two-operation variants for
- sync writes, ``bpm-tree-recovery-model`` for pending recovery;
+ sync writes, ``bpm-tree-recovery-model`` for pending recovery,
+ ``bpm-tree-state-replay`` for ``tree_event_replay()``;
``tree_parse()`` by review
+ * - ``Shirudo.TreeOverlap``, :src:`util/bpm_tree_overlap.c` against
+ ``tree_selector_matches()`` of :src:`util/bpm_tree_state.c`
+ - ``disjoint_sound``: no node matches two selectors that
+ ``tree_selectors_disjoint()`` calls disjoint; ``covers_sound``: a
+ selector that ``selector_covers()`` says covers another matches
+ every node the other matches; ``addLive_false``: an add that
+ ``tree_add_live()`` says is no longer live is followed by a delete
+ of the same upatch that matches every node the add matches;
+ ``prefixes_meet_iff``: two release prefixes take a common release
+ exactly when one takes the other read as a release;
+ ``disjoint_comm``, ``covers_refl``: the order of two selectors
+ does not matter, and a selector covers itself
+ - One node for both selectors: its release, machine, build ID,
+ config values and labels are the same for the two matches, and
+ ``/proc/config.gz`` and ``/boot/config-<release>`` give an option
+ the same value; a match that returns an error is no answer
+ - CBMC, ``bpm-tree-overlap-model`` and ``bpm-tree-overlap-live`` for
+ the publisher's checks, ``bpm-tree-state-match``,
+ ``bpm-tree-state-pairs`` and ``bpm-tree-state-options`` for the
+ node's match, each on short selectors; the match of a kernel
+ option against the config by review
Files without a proof
---------------------
@@ -1070,10 +1160,6 @@ a proof covers.
* - Files
- Why no proof reads them
- * - :src:`util/bpm_tree_overlap.c`, :src:`util/bpm_tree_state.c`
- - No proof is written yet. A harness could carry their logic, in
- whole or in part: the tree state reader and which selectors of a
- tree can meet on one node
* - :src:`util/harden.c`, :src:`util/identity.c`,
:src:`util/image_cache.c`, :src:`util/image_config.c`,
:src:`util/image_guards.c`, :src:`util/image_keys.c`,
@@ -1126,10 +1212,10 @@ The fuzz targets in :doc:`test-coverage` cover these parsers; no proof
does: how ``json_parse()`` dispatches objects, arrays and maps to their
schemas, the OTLP headers a configuration adds, the walk over a
package's tar members, the registry references and URLs, the kernel
-configuration the tree selectors read, the tree log, the eventlog's
-lines, the evidence document beyond its PCRs and its config history,
-the config update record, the site configuration file and the config
-image's settings and tree.
+configuration and the labels the tree selectors read, the tree's
+``state.json``, the eventlog's lines, the evidence document beyond its
+PCRs and its config history, the config update record, the site
+configuration file and the config image's settings and tree.
The ``.upatch`` reader, the TPM structures and the package, index and
tree readers are covered part by part, as the table shows; what joins
those parts has no proof. So it is with the package state:
diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rst
index f82e0ea1..e657c84b 100644
--- a/Documentation/security/threat-model.rst
+++ b/Documentation/security/threat-model.rst
@@ -1058,6 +1058,7 @@ and tree signatures accept algorithms other than ML-DSA (U4).
``Shirudo.JsonString``, ``Shirudo.TreeSync``, ``bpm-tree-follows``,
``bpm-tree-sync-model``, ``bpm-tree-sync-application``,
``bpm-tree-sync-pending``, ``bpm-tree-recovery-model``,
+ ``bpm-tree-state-pending``, ``bpm-tree-state-replay``,
``bpm-tree-reader``, ``json-string``,
``json-limits``
:Residual: R8, R9, U3, U4, U15
diff --git a/testing/proofs/cbmc/bpm-tree-overlap-live.c b/testing/proofs/cbmc/bpm-tree-overlap-live.c
new file mode 100644
index 00000000..b470057d
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-overlap-live.c
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * tree_add_live() of util/bpm_tree_overlap.c is addLive of
+ * testing/proofs/lean4/Shirudo/TreeOverlap.lean on every publication of up
+ * to OPS_MAX operations: an add is live until a later delete of its upatch
+ * covers its selector.
+ */
+
+#define TREE_OVERLAP_LIVE 1
+#define OPS_MAX 3
+#include "bpm-tree-overlap-model.c"
diff --git a/testing/proofs/cbmc/bpm-tree-overlap-model.c b/testing/proofs/cbmc/bpm-tree-overlap-model.c
new file mode 100644
index 00000000..d5139450
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-overlap-model.c
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * tree_selectors_disjoint() and selector_covers() of
+ * util/bpm_tree_overlap.c are disjoint and covers of
+ * testing/proofs/lean4/Shirudo/TreeOverlap.lean on every two selectors of
+ * up to LEN entries a list. bpm-tree-overlap-live.c includes this file for
+ * tree_add_live().
+ */
+
+#include "proof.h"
+#include "../../../util/kernel_release.c"
+#include "../../../util/bpm_tree_overlap.c"
+#include "bpm-tree-overlap-model.h"
+
+#define TEXT_MAX 2
+
+/* No harness here holds a selector against a node. */
+static const char *model_kconfig(const char *key)
+{
+ return NULL;
+}
+
+/*
+ * A selector is held in an operation: CBMC 5.95 reads wrong bytes at an
+ * offset that depends on the data from an object that starts with an array
+ * of char, as a selector on its own does. Only its two pointers are
+ * written, as a write into its 12 KiB makes CBMC copy all of them.
+ */
+static void short_text(const char *s)
+{
+ __CPROVER_assume(!s[TEXT_MAX]);
+}
+
+static void short_list(const char (*list)[TREE_STRING_MAX], int n, int max)
+{
+ __CPROVER_assume(n >= 0 && n <= max);
+ for (int i = 0; i < max; i++)
+ short_text(list[i]);
+}
+
+static void short_pairs(const struct tree_selector_kv *kvs, int n, int max)
+{
+ __CPROVER_assume(n >= 0 && n <= max);
+ for (int i = 0; i < max; i++) {
+ short_text(kvs[i].key);
+ short_list(kvs[i].values, kvs[i].n_values, max);
+ }
+}
+
+#ifdef TREE_OVERLAP_LIVE
+/* ends, of the operation at index and a later one. */
+static bool model_ends(const struct tree_operation *add,
+ const struct tree_operation *later)
+{
+ return model_same(later->op, "delete") &&
+ model_same(later->id, add->id) &&
+ model_covers(&later->selector, &add->selector);
+}
+
+/*
+ * The selectors name architectures alone, one or none, which is enough to
+ * tell a delete that covers the add from one the add covers; the lists
+ * left empty keep the loops over them out of the proof.
+ */
+static void add_live(void)
+{
+ struct tree_operation ops[OPS_MAX];
+ struct tree_publication pub;
+
+ pub.operations = ops;
+ __CPROVER_assume(pub.n_operations >= 0 && pub.n_operations <= OPS_MAX);
+ for (int i = 0; i < OPS_MAX; i++) {
+ struct tree_selector *s = &ops[i].selector;
+
+ /* "delete" and every other string of up to 7 bytes. */
+ __CPROVER_assume(!ops[i].op[7]);
+ short_text(ops[i].id);
+ short_list(s->architecture, s->n_architecture, 1);
+ s->n_kernel_release_prefix = 0;
+ s->n_kernel_build_id = 0;
+ s->n_kconfig = 0;
+ s->n_labels = 0;
+ }
+ for (int index = 0; index < OPS_MAX; index++) {
+ bool live = true;
+
+ if (index >= pub.n_operations)
+ break;
+ for (int i = index + 1; i < OPS_MAX; i++)
+ if (i < pub.n_operations)
+ live &= !model_ends(&ops[index], &ops[i]);
+ __CPROVER_assert(tree_add_live(&pub, index) == live,
+ "addLive of the model");
+ }
+}
+
+void harness(void)
+{
+ add_live();
+}
+#else
+/* A selector tree_parse() or the publisher could hold, and others. */
+static void short_selector(struct tree_selector *s,
+ struct tree_selector_kv *kconfig,
+ struct tree_selector_kv *labels)
+{
+ s->kconfig = kconfig;
+ s->labels = labels;
+ short_list(s->kernel_release_prefix, s->n_kernel_release_prefix, LEN);
+ short_list(s->kernel_build_id, s->n_kernel_build_id, LEN);
+ short_list(s->architecture, s->n_architecture, LEN);
+ short_pairs(kconfig, s->n_kconfig, LEN);
+ short_pairs(labels, s->n_labels, LEN);
+}
+
+void harness(void)
+{
+ struct tree_selector_kv kconfig[2][LEN], labels[2][LEN];
+ struct tree_operation ops[2];
+ const struct tree_selector *a = &ops[0].selector;
+ const struct tree_selector *b = &ops[1].selector;
+
+ short_selector(&ops[0].selector, kconfig[0], labels[0]);
+ short_selector(&ops[1].selector, kconfig[1], labels[1]);
+ __CPROVER_assert(tree_selectors_disjoint(a, b) == model_disjoint(a, b),
+ "disjoint of the model");
+ __CPROVER_assert(selector_covers(a, b) == model_covers(a, b),
+ "covers of the model");
+}
+#endif
diff --git a/testing/proofs/cbmc/bpm-tree-overlap-model.h b/testing/proofs/cbmc/bpm-tree-overlap-model.h
new file mode 100644
index 00000000..716720cb
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-overlap-model.h
@@ -0,0 +1,252 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * testing/proofs/lean4/Shirudo/TreeOverlap.lean restated in C for the
+ * harnesses that hold util/bpm_tree_overlap.c and tree_selector_matches()
+ * to it. A function is named after the Lean definition it restates, and
+ * the harness defines model_kconfig(), the node's kernel config.
+ */
+
+#ifndef SHIRUDO_PROOF_BPM_TREE_OVERLAP_MODEL_H
+#define SHIRUDO_PROOF_BPM_TREE_OVERLAP_MODEL_H
+
+/* Node; build_id is NULL for none. */
+struct model_node {
+ bool uname;
+ const char *release;
+ const char *machine;
+ const char *build_id;
+ const struct tree_kv *labels;
+ int n_labels;
+};
+
+/* The value the node's kernel config gives a key, NULL for none. */
+static const char *model_kconfig(const char *key);
+
+/*
+ * Equality of two strings, the bytes before their NULs. No read here is at
+ * an index that depends on the strings: CBMC 5.95 reads wrong bytes at a
+ * symbolic offset from an object of struct type.
+ */
+static bool model_same(const char *a, const char *b)
+{
+ for (size_t i = 0;; i++) {
+ if (a[i] != b[i])
+ return false;
+ if (!a[i])
+ return true;
+ }
+}
+
+static bool model_list_holds(const char (*list)[TREE_STRING_MAX], int n,
+ const char *value)
+{
+ bool any = false;
+
+ for (int i = 0; i < n; i++)
+ any |= model_same(list[i], value);
+ return any;
+}
+
+static bool model_lists_share(const char (*a)[TREE_STRING_MAX], int na,
+ const char (*b)[TREE_STRING_MAX], int nb)
+{
+ bool any = false;
+
+ for (int i = 0; i < na; i++)
+ any |= model_list_holds(b, nb, a[i]);
+ return any;
+}
+
+static bool model_list_within(const char (*inner)[TREE_STRING_MAX],
+ int n_inner,
+ const char (*outer)[TREE_STRING_MAX],
+ int n_outer)
+{
+ bool all = true;
+
+ for (int i = 0; i < n_inner; i++)
+ all &= model_list_holds(outer, n_outer, inner[i]);
+ return all;
+}
+
+/* continues, with boundary on what is left of the release. */
+static bool model_continues(const char *release, const char *prefix)
+{
+ for (size_t i = 0;; i++) {
+ if (!prefix[i])
+ return !release[i] || release[i] == '.' ||
+ release[i] == '-';
+ if (release[i] != prefix[i])
+ return false;
+ }
+}
+
+static bool model_prefix_matches(const char *release, const char *prefix)
+{
+ return !prefix[0] || model_continues(release, prefix);
+}
+
+static bool model_prefixes_share(const char (*a)[TREE_STRING_MAX], int na,
+ const char (*b)[TREE_STRING_MAX], int nb)
+{
+ bool any = false;
+
+ for (int i = 0; i < na; i++)
+ for (int j = 0; j < nb; j++)
+ any |= model_prefix_matches(a[i], b[j]) ||
+ model_prefix_matches(b[j], a[i]);
+ return any;
+}
+
+static bool model_prefixes_within(const char (*inner)[TREE_STRING_MAX],
+ int n_inner,
+ const char (*outer)[TREE_STRING_MAX],
+ int n_outer)
+{
+ bool all = true;
+
+ for (int i = 0; i < n_inner; i++) {
+ bool any = false;
+
+ for (int j = 0; j < n_outer; j++)
+ any |= model_prefix_matches(inner[i], outer[j]);
+ all &= any;
+ }
+ return all;
+}
+
+static bool model_kvs_exclude(const struct tree_selector_kv *a, int na,
+ const struct tree_selector_kv *b, int nb)
+{
+ bool any = false;
+
+ for (int i = 0; i < na; i++)
+ for (int j = 0; j < nb; j++)
+ any |= model_same(a[i].key, b[j].key) &&
+ !model_lists_share(a[i].values, a[i].n_values,
+ b[j].values, b[j].n_values);
+ return any;
+}
+
+static bool model_kvs_within(const struct tree_selector_kv *inner, int n_inner,
+ const struct tree_selector_kv *outer, int n_outer)
+{
+ bool all = true;
+
+ for (int j = 0; j < n_outer; j++) {
+ bool any = false;
+
+ for (int i = 0; i < n_inner; i++)
+ any |= model_same(inner[i].key, outer[j].key) &&
+ model_list_within(inner[i].values,
+ inner[i].n_values,
+ outer[j].values,
+ outer[j].n_values);
+ all &= any;
+ }
+ return all;
+}
+
+static bool model_disjoint(const struct tree_selector *a,
+ const struct tree_selector *b)
+{
+ return (a->n_architecture && b->n_architecture &&
+ !model_lists_share(a->architecture, a->n_architecture,
+ b->architecture, b->n_architecture)) ||
+ (a->n_kernel_build_id && b->n_kernel_build_id &&
+ !model_lists_share(a->kernel_build_id, a->n_kernel_build_id,
+ b->kernel_build_id, b->n_kernel_build_id)) ||
+ (a->n_kernel_release_prefix && b->n_kernel_release_prefix &&
+ !model_prefixes_share(a->kernel_release_prefix,
+ a->n_kernel_release_prefix,
+ b->kernel_release_prefix,
+ b->n_kernel_release_prefix)) ||
+ model_kvs_exclude(a->kconfig, a->n_kconfig, b->kconfig,
+ b->n_kconfig) ||
+ model_kvs_exclude(a->labels, a->n_labels, b->labels,
+ b->n_labels);
+}
+
+static bool model_covers(const struct tree_selector *outer,
+ const struct tree_selector *inner)
+{
+ return (!outer->n_architecture ||
+ (inner->n_architecture &&
+ model_list_within(inner->architecture, inner->n_architecture,
+ outer->architecture,
+ outer->n_architecture))) &&
+ (!outer->n_kernel_build_id ||
+ (inner->n_kernel_build_id &&
+ model_list_within(inner->kernel_build_id,
+ inner->n_kernel_build_id,
+ outer->kernel_build_id,
+ outer->n_kernel_build_id))) &&
+ (!outer->n_kernel_release_prefix ||
+ (inner->n_kernel_release_prefix &&
+ model_prefixes_within(inner->kernel_release_prefix,
+ inner->n_kernel_release_prefix,
+ outer->kernel_release_prefix,
+ outer->n_kernel_release_prefix))) &&
+ model_kvs_within(inner->kconfig, inner->n_kconfig,
+ outer->kconfig, outer->n_kconfig) &&
+ model_kvs_within(inner->labels, inner->n_labels, outer->labels,
+ outer->n_labels);
+}
+
+static const char *model_kv_value(const struct tree_kv *labels, int n,
+ const char *key)
+{
+ for (int i = 0; i < n; i++)
+ if (model_same(labels[i].key, key))
+ return labels[i].value;
+ return NULL;
+}
+
+/* pairHeld of every pair, on the value the node has or NULL. */
+static bool model_pair_held(const struct tree_selector_kv *pair,
+ const char *value)
+{
+ return value && model_list_holds(pair->values, pair->n_values, value);
+}
+
+static bool model_wildcard(const struct tree_selector *s)
+{
+ return !s->n_kernel_release_prefix && !s->n_kernel_build_id &&
+ !s->n_architecture && !s->n_kconfig && !s->n_labels;
+}
+
+static bool model_matches_on(const struct model_node *n,
+ const struct tree_selector *s)
+{
+ bool release = false, kconfig = true, labels = true;
+
+ for (int i = 0; i < s->n_kernel_release_prefix; i++)
+ release |= model_prefix_matches(n->release,
+ s->kernel_release_prefix[i]);
+ for (int i = 0; i < s->n_kconfig; i++)
+ kconfig &= model_pair_held(&s->kconfig[i],
+ model_kconfig(s->kconfig[i].key));
+ for (int i = 0; i < s->n_labels; i++)
+ labels &= model_pair_held(&s->labels[i],
+ model_kv_value(n->labels, n->n_labels,
+ s->labels[i].key));
+ return (!s->n_kernel_release_prefix || release) &&
+ (!s->n_kernel_build_id ||
+ (n->build_id &&
+ model_list_holds(s->kernel_build_id, s->n_kernel_build_id,
+ n->build_id))) &&
+ (!s->n_architecture ||
+ model_list_holds(s->architecture, s->n_architecture,
+ n->machine)) &&
+ kconfig && labels;
+}
+
+static bool model_selector_matches(const struct model_node *n,
+ const struct tree_selector *s)
+{
+ return model_wildcard(s) || (n->uname && model_matches_on(n, s));
+}
+
+#endif /* SHIRUDO_PROOF_BPM_TREE_OVERLAP_MODEL_H */
diff --git a/testing/proofs/cbmc/bpm-tree-state-match.c b/testing/proofs/cbmc/bpm-tree-state-match.c
new file mode 100644
index 00000000..8df26486
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-state-match.c
@@ -0,0 +1,313 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * tree_selector_matches() of util/bpm_tree_state.c returns 1 exactly where
+ * selectorMatches of testing/proofs/lean4/Shirudo/TreeOverlap.lean holds,
+ * for release prefixes, build IDs, architectures and labels. The node is a
+ * stub; a selector that names a kernel option is not covered here.
+ */
+
+/* util/string.c behind a file that includes its header. */
+#define STRING_INTERNAL
+
+/* CBMC's own memcpy() of a length it does not know runs out of memory. */
+#define PROOF_MEMCPY_BYTEWISE
+
+/* For an errno that keeps what a stub stored. */
+#define PROOF_FILE 1
+
+/*
+ * struct utsname with a first member that is no array of char: CBMC 5.95
+ * reads wrong bytes at an offset that depends on the data, as
+ * release[strlen(prefix)] is, from an object whose type starts with one.
+ */
+#define _SYS_UTSNAME_H 1
+struct utsname {
+ long first;
+ char sysname[65];
+ char nodename[65];
+ char release[65];
+ char version[65];
+ char machine[65];
+ char domainname[65];
+};
+
+#include "proof.h"
+
+#define LIST_MAX 2
+#define TEXT_MAX 2
+#define OPTIONS_MAX 2
+
+/* The node: what uname() and the kernel's notes give, or their failure. */
+static char node_release[TEXT_MAX + 1], node_machine[TEXT_MAX + 1];
+static char node_build_id[TEXT_MAX + 1];
+static bool uname_fails, build_id_fails;
+
+int uname(struct utsname *u)
+{
+ if (uname_fails)
+ return -1;
+ for (int i = 0; i <= TEXT_MAX; i++) {
+ u->release[i] = node_release[i];
+ u->machine[i] = node_machine[i];
+ }
+ return 0;
+}
+
+#include "../../../util/bpm_tree_state.c"
+#include "../../../util/kernel_release.c"
+#include "../../../util/string.c"
+#include "bpm-tree-overlap-model.h"
+
+int kernel_build_id_read(char out[KERNEL_BUILD_ID_STRING_MAX])
+{
+ if (build_id_fails)
+ return -ENOENT;
+ for (int i = 0; i <= TEXT_MAX; i++)
+ out[i] = node_build_id[i];
+ return 0;
+}
+
+/* No selector here names a kernel option. */
+static const char *model_kconfig(const char *key)
+{
+ return NULL;
+}
+
+/*
+ * LEN picks what the selector names: 0 release prefixes, build IDs and
+ * architectures, 1 to 3 labels, read from /etc (1), from an empty config
+ * image (2) or from a file whose first line fails (3). These are constants:
+ * CBMC follows the bytes of a line only when no branch wrote them.
+ */
+#define IMAGE_ACTIVE (LEN == 2)
+#define LINE_FAILS (LEN == 3)
+#define LABEL_LINES (IMAGE_ACTIVE ? 0 : 5)
+#define LABELS (IMAGE_ACTIVE ? 0 : 3)
+
+static const char *const label_lines[] = {
+ "a=x\n", "# c=1\n", " b = y\x20\n", "junk\n", "a=z\n",
+};
+
+/* A blank before the '=' stays in the key, as the format says. */
+static const struct tree_kv node_labels[] = {
+ { "a", "x" }, { "b ", "y" }, { "a", "z" },
+};
+
+static int open_error, stream_error;
+static int n_lines, n_opened, n_closed, n_fd_closed, n_line_freed;
+static char label_line[16];
+static FILE label_stream;
+
+bool image_config_active(void)
+{
+ return IMAGE_ACTIVE;
+}
+
+int image_open(enum image_path which, int flags)
+{
+ __CPROVER_assert(IMAGE_ACTIVE && which == IMAGE_NODE_LABELS,
+ "the labels of the active config image");
+ return open_error ? open_error : 3;
+}
+
+FILE *fdopen(int fd, const char *mode)
+{
+ __CPROVER_assert(fd == 3, "the descriptor image_open() gave");
+ if (stream_error) {
+ errno = -stream_error;
+ return NULL;
+ }
+ n_opened++;
+ return &label_stream;
+}
+
+FILE *fopen(const char *path, const char *mode)
+{
+ __CPROVER_assert(!IMAGE_ACTIVE &&
+ !memcmp(path, "/etc/shirudo/node.labels", 25),
+ "the labels of /etc without a config image");
+ if (open_error) {
+ errno = -open_error;
+ return NULL;
+ }
+ n_opened++;
+ return &label_stream;
+}
+
+int fclose(FILE *f)
+{
+ __CPROVER_assert(f == &label_stream, "the stream that was opened");
+ n_closed++;
+ return 0;
+}
+
+int close(int fd)
+{
+ __CPROVER_assert(fd == 3, "the descriptor image_open() gave");
+ n_fd_closed++;
+ return 0;
+}
+
+int read_text_line(FILE *f, char **line, size_t *cap, size_t max)
+{
+ const char *text;
+ int i;
+
+ if (LINE_FAILS)
+ return -EIO;
+ if (n_lines == LABEL_LINES)
+ return 0;
+ text = label_lines[n_lines++];
+ for (i = 0; text[i]; i++)
+ label_line[i] = text[i];
+ label_line[i] = '\0';
+ *line = label_line;
+ *cap = sizeof(label_line);
+ return 1;
+}
+
+void libc_free(void *p)
+{
+ __CPROVER_assert(!p || p == label_line, "the line that was read");
+ n_line_freed++;
+}
+
+/* The selector lies in an operation, as bpm-tree-overlap-model.c has it. */
+static void short_text(const char *s)
+{
+ __CPROVER_assume(!s[TEXT_MAX]);
+}
+
+static void short_list(const char (*list)[TREE_STRING_MAX], int n, int max)
+{
+ __CPROVER_assume(n >= 0 && n <= max);
+ for (int i = 0; i < max; i++)
+ short_text(list[i]);
+}
+
+static void short_pairs(const struct tree_selector_kv *kvs, int n, int max)
+{
+ __CPROVER_assume(n >= 0 && n <= max);
+ for (int i = 0; i < max; i++) {
+ short_text(kvs[i].key);
+ short_list(kvs[i].values, kvs[i].n_values, LIST_MAX);
+ }
+}
+
+/* 0 or a negative errno, as the kernel numbers them. */
+static bool no_errno(int ret)
+{
+ return ret <= 0 && ret >= -4095;
+}
+
+static void any_text(char *s)
+{
+ char any[TEXT_MAX];
+
+ for (int i = 0; i < TEXT_MAX; i++)
+ s[i] = any[i];
+}
+
+#ifdef TREE_STATE_OPTIONS
+/*
+ * tree_map_pair() keeps a kconfig below TREE_MAX_KCONFIG pairs, half the
+ * table: here up to OPTIONS_MAX, of any keys, a key twice among them. The
+ * pairs lie in bytes: selector_hash_find() reads the pair at the index
+ * the table holds, and CBMC 5.95 reads wrong bytes at such an offset
+ * from an array of pairs.
+ */
+void harness(void)
+{
+ char kconfig[OPTIONS_MAX * sizeof(struct tree_selector_kv)];
+ const struct tree_selector_kv *pairs = (void *)kconfig;
+ int slots[TREE_SELECTOR_HASH_SIZE], first = -1;
+ char *key = any_bytes(TEXT_MAX + 1);
+ struct tree_operation op;
+ struct tree_selector *s = &op.selector;
+
+ s->kconfig = (struct tree_selector_kv *)kconfig;
+ __CPROVER_assume(s->n_kconfig >= 0 && s->n_kconfig <= OPTIONS_MAX);
+ short_text(key);
+ for (int i = 0; i < OPTIONS_MAX; i++)
+ short_text(pairs[i].key);
+ selector_hash_build(s, slots);
+ for (int i = OPTIONS_MAX - 1; i >= 0; i--)
+ if (i < s->n_kconfig && model_same(pairs[i].key, key))
+ first = i;
+ __CPROVER_assert(selector_hash_find(s, slots, key) == first,
+ "a key found at its first pair, or not at all");
+}
+#else
+void harness(void)
+{
+ struct tree_selector_kv labels[LIST_MAX];
+ int any_error[2], any_count[3], config_rc, ret;
+ struct tree_selector *s;
+ struct tree_operation op;
+ struct model_node node;
+ bool any_flag[2], want;
+
+ /* A global starts as zeros to CBMC, a local as anything. */
+ uname_fails = any_flag[0];
+ build_id_fails = any_flag[1];
+ any_text(node_release);
+ any_text(node_machine);
+ any_text(node_build_id);
+ node = (struct model_node){
+ !uname_fails, node_release, node_machine,
+ build_id_fails ? NULL : node_build_id, node_labels, LABELS,
+ };
+ __CPROVER_assert(!tree_selector_matches(NULL), "no selector, no match");
+
+ s = &op.selector;
+ s->kconfig = NULL;
+ s->labels = labels;
+ s->n_kernel_release_prefix = 0;
+ s->n_kernel_build_id = 0;
+ s->n_architecture = 0;
+ s->n_kconfig = 0;
+ s->n_labels = 0;
+ if (LEN == 0) {
+ s->n_kernel_release_prefix = any_count[0];
+ s->n_kernel_build_id = any_count[1];
+ s->n_architecture = any_count[2];
+ short_list(s->kernel_release_prefix,
+ s->n_kernel_release_prefix, LIST_MAX);
+ short_list(s->kernel_build_id, s->n_kernel_build_id, LIST_MAX);
+ short_list(s->architecture, s->n_architecture, LIST_MAX);
+ } else {
+ open_error = any_error[0];
+ stream_error = any_error[1];
+ __CPROVER_assume(no_errno(open_error) &&
+ no_errno(stream_error));
+ s->n_labels = any_count[0];
+ short_pairs(labels, s->n_labels, LIST_MAX);
+ }
+
+ ret = tree_selector_matches(s);
+ want = model_selector_matches(&node, s);
+ if (LEN == 0) {
+ __CPROVER_assert(ret == want, "selectorMatches of the model");
+ return;
+ }
+ if (model_wildcard(s) || uname_fails) {
+ __CPROVER_assert(ret == want && !n_opened,
+ "decided before the node's labels are read");
+ return;
+ }
+ __CPROVER_assert(n_closed == n_opened && n_line_freed == n_opened &&
+ n_fd_closed == (IMAGE_ACTIVE && !open_error &&
+ stream_error),
+ "the labels closed, and their line released");
+ config_rc = open_error ? open_error :
+ IMAGE_ACTIVE && stream_error ? stream_error :
+ LINE_FAILS ? -EIO : 0;
+ if (config_rc)
+ __CPROVER_assert(ret == (config_rc == -ENOENT ? 0 : config_rc),
+ "no labels, no match; unreadable, the error");
+ else
+ __CPROVER_assert(ret == want, "selectorMatches of the model");
+}
+#endif
diff --git a/testing/proofs/cbmc/bpm-tree-state-options.c b/testing/proofs/cbmc/bpm-tree-state-options.c
new file mode 100644
index 00000000..b0f5bada
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-state-options.c
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * The table tree_selector_matches() of util/bpm_tree_state.c looks a kernel
+ * option up in: selector_hash_find() finds a key at the first pair that has
+ * it and no key that none has, so an option has one value, as kconfig of
+ * testing/proofs/lean4/Shirudo/TreeOverlap.lean gives it.
+ */
+
+#define TREE_STATE_OPTIONS 1
+/* The stubs of the node there take a LEN, which no option reads. */
+#define LEN 0
+#include "bpm-tree-state-match.c"
diff --git a/testing/proofs/cbmc/bpm-tree-state-pairs.c b/testing/proofs/cbmc/bpm-tree-state-pairs.c
new file mode 100644
index 00000000..39fd778b
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-state-pairs.c
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * The pairs and digests of util/bpm_tree_state.c: kv_add() stores a pair
+ * whole or not at all, for keys and values of LEN bytes, kv_value() and
+ * selector_values_match() are kvValue and listHolds of
+ * testing/proofs/lean4/Shirudo/TreeOverlap.lean, and hex32_valid() takes
+ * exactly 64 hex digits.
+ */
+
+/* util/malloc.c and util/string.c behind a file that includes their headers. */
+#define MALLOC_INTERNAL
+#define STRING_INTERNAL
+
+/* CBMC's own memcpy() of a length it does not know runs out of memory. */
+#define PROOF_MEMCPY_BYTEWISE
+
+#include "proof.h"
+#include "../../../util/bpm_tree_state.c"
+#include "../../../util/hex.c"
+#include "../../../util/string.c"
+#include "bpm-tree-overlap-model.h"
+
+#define PAIRS_MAX 2
+#define TEXT_MAX 2
+
+/* No harness here holds a selector against a node. */
+static const char *model_kconfig(const char *key)
+{
+ return NULL;
+}
+
+/*
+ * A string of exactly len bytes: any bytes while it is short, and one
+ * byte repeated when it is long, which keeps its length a constant to
+ * CBMC and the copy of it cheap.
+ */
+static char *string_of(size_t len)
+{
+ char *s = any_bytes(len + 1);
+
+ if (len > TEXT_MAX)
+ memset(s, 'k', len);
+ else
+ __CPROVER_assume(strnlen(s, len) == len);
+ s[len] = '\0';
+ return s;
+}
+
+/*
+ * read_config_stream() and the gzip branch of read_config_file() add to
+ * the max pairs of labels[] from a count that starts at 0 and that only
+ * kv_add() moves, so n is at most max and max the pairs there are.
+ */
+static void pair_added(size_t key_len, size_t value_len, int n)
+{
+ /*
+ * As bytes: CBMC 5.95 reads wrong bytes at an offset that depends
+ * on the data from an object whose type starts with an array of
+ * char, as an array of pairs does.
+ */
+ char pairs[PAIRS_MAX * sizeof(struct tree_kv)];
+ struct tree_kv *dst = (struct tree_kv *)pairs;
+ char *key = string_of(key_len), *value = string_of(value_len);
+ char kept_key, kept_value, new_key, new_value;
+ const int was = n, last = PAIRS_MAX - 1;
+ size_t at, k, v;
+ int max, ret;
+
+ __CPROVER_assume(max >= n && max <= PAIRS_MAX &&
+ at < TREE_STRING_MAX && k <= key_len &&
+ v <= value_len);
+ kept_key = dst[0].key[at];
+ kept_value = dst[0].value[at];
+ new_key = dst[last].key[at];
+ new_value = dst[last].value[at];
+ ret = kv_add(dst, &n, max, key, value);
+ if (ret) {
+ __CPROVER_assert(ret == -E2BIG || ret == -ENOSPC,
+ "refused as full or as too long");
+ __CPROVER_assert((ret == -E2BIG) == (was >= max),
+ "-E2BIG exactly at the limit");
+ __CPROVER_assert(ret != -ENOSPC || LEN >= TREE_STRING_MAX,
+ "-ENOSPC only for a string that does not fit");
+ __CPROVER_assert(n == was, "a refused pair is not counted");
+ __CPROVER_assert(ret != -E2BIG ||
+ (dst[last].key[at] == new_key &&
+ dst[last].value[at] == new_value),
+ "nothing written at the limit");
+ } else {
+ __CPROVER_assert(was < max && LEN < TREE_STRING_MAX,
+ "taken below the limit, when both fit");
+ __CPROVER_assert(n == was + 1, "counted once");
+ __CPROVER_assert(dst[was].key[k] == key[k] &&
+ dst[was].value[v] == value[v],
+ "the key and the value stored whole");
+ }
+ __CPROVER_assert(!was || (dst[0].key[at] == kept_key &&
+ dst[0].value[at] == kept_value),
+ "the pairs before it kept");
+}
+
+static void short_text(const char *s)
+{
+ __CPROVER_assume(!s[TEXT_MAX]);
+}
+
+static void value_found(void)
+{
+ char *key = any_bytes(TEXT_MAX + 1);
+ struct tree_kv v[PAIRS_MAX];
+ int n;
+
+ __CPROVER_assume(n >= 0 && n <= PAIRS_MAX);
+ short_text(key);
+ for (int i = 0; i < PAIRS_MAX; i++) {
+ short_text(v[i].key);
+ short_text(v[i].value);
+ }
+ __CPROVER_assert(kv_value(v, n, key) == model_kv_value(v, n, key),
+ "kvValue of the model: the first pair with the key");
+}
+
+static void values_matched(void)
+{
+ char *want = any_bytes(TEXT_MAX + 1);
+ struct tree_selector_kv pair;
+ bool no_pair, no_want;
+ int ret;
+
+ __CPROVER_assume(pair.n_values >= 0 && pair.n_values <= PAIRS_MAX);
+ short_text(want);
+ for (int i = 0; i < PAIRS_MAX; i++)
+ short_text(pair.values[i]);
+ ret = selector_values_match(no_pair ? NULL : &pair,
+ no_want ? NULL : want);
+ __CPROVER_assert(ret == (!no_pair && !no_want &&
+ model_list_holds(pair.values, pair.n_values,
+ want)),
+ "listHolds of the model, and nothing without a value");
+}
+
+static void digest_valid(void)
+{
+ char *hex = any_bytes(66);
+ bool digits = true;
+ size_t i;
+
+ hex[65] = '\0';
+ for (i = 0; i < 64; i++)
+ digits &= (hex[i] >= '0' && hex[i] <= '9') ||
+ (hex[i] >= 'a' && hex[i] <= 'f') ||
+ (hex[i] >= 'A' && hex[i] <= 'F');
+ __CPROVER_assert(hex32_valid(hex) == (digits && !hex[64]),
+ "exactly 64 hex digits");
+}
+
+void harness(void)
+{
+ const size_t len = LEN;
+
+ /* The count decides nothing once a pair is below the limit. */
+ for (int n = 0; n <= (len > TEXT_MAX ? 0 : PAIRS_MAX); n++) {
+ pair_added(LEN, 1, n);
+ pair_added(1, LEN, n);
+ }
+ if (LEN == 1) {
+ value_found();
+ values_matched();
+ digest_valid();
+ }
+}
diff --git a/testing/proofs/cbmc/bpm-tree-state-pending.c b/testing/proofs/cbmc/bpm-tree-state-pending.c
new file mode 100644
index 00000000..9848bf0d
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-state-pending.c
@@ -0,0 +1,267 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * pending.json of util/bpm_tree_state.c: tree_pending_parse() takes exactly
+ * a whole record of schema 1, and what tree_pending_write() writes of an
+ * operation reads back as that operation. util/json.c is a stub that hands
+ * keys and values over; json-roundtrip and json-field prove its bytes.
+ */
+
+/* util/string.c behind a file that includes its header. */
+#define STRING_INTERNAL
+
+/* CBMC's own memcpy() of a length it does not know runs out of memory. */
+#define PROOF_MEMCPY_BYTEWISE
+
+#include "proof.h"
+#include "../../../util/bpm_tree_state.c"
+#include "../../../util/hex.c"
+#include "../../../util/string.c"
+#include "../../../util/upatch.c"
+
+#define ID_MAX 8
+
+/* What the emitter was given: a key and a number or a string. */
+struct member {
+ const char *key;
+ bool number;
+ __s64 value;
+ const char *text;
+};
+
+#define MEMBERS_MAX 4
+
+static struct member members[MEMBERS_MAX];
+static int n_members, n_written;
+static bool opened, closed, reading_back;
+static int emit_error, mkdir_error, write_error, read_back_ret;
+static struct tree_pending read_back;
+static const char *emitted;
+static size_t emitted_len;
+
+/* What json_parse() finds in a document that was not written here. */
+struct found {
+ int ret;
+ bool seen[4];
+ __s64 schema;
+ __s64 seq;
+ char id[TREE_STRING_MAX];
+ char digest[128];
+};
+
+static struct found found;
+
+void json_obj_open(struct json_emit *e)
+{
+ __CPROVER_assert(!opened && !n_members, "one object");
+ opened = true;
+}
+
+void json_kv_int(struct json_emit *e, const char *key, __s64 val)
+{
+ __CPROVER_assert(opened && !closed && n_members < MEMBERS_MAX,
+ "a member of the open object");
+ members[n_members++] = (struct member){ key, true, val, NULL };
+}
+
+void json_kv_string(struct json_emit *e, const char *key, const char *val)
+{
+ __CPROVER_assert(opened && !closed && n_members < MEMBERS_MAX,
+ "a member of the open object");
+ members[n_members++] = (struct member){ key, false, 0, val };
+}
+
+void json_obj_close(struct json_emit *e)
+{
+ size_t len;
+
+ __CPROVER_assert(opened && !closed, "the object closed once");
+ __CPROVER_assume(len <= e->cap);
+ closed = true;
+ e->len = len;
+ e->err = emit_error;
+ emitted = e->buf;
+ emitted_len = len;
+}
+
+int seal_mkdir_p(const char *path, mode_t mode)
+{
+ __CPROVER_assert(!n_written, "the directory before the file");
+ return mkdir_error;
+}
+
+/* The record is read back while the buffer that holds it is there. */
+int seal_write_file(const char *path, const void *data, size_t len,
+ mode_t mode)
+{
+ __CPROVER_assert(closed && !emit_error && data == emitted &&
+ len == emitted_len,
+ "the whole document, when the emitter took it");
+ n_written++;
+ reading_back = true;
+ read_back_ret = tree_pending_parse(data, len, &read_back);
+ reading_back = false;
+ return write_error;
+}
+
+/* The members that name a field, each once, of its type and fitting. */
+static int members_read(struct json_field *f, size_t n)
+{
+ for (size_t i = 0; i < n; i++) {
+ for (int j = 0; j < n_members; j++) {
+ const struct member *m = &members[j];
+ bool number = f[i].type == JSON_T_INT;
+
+ if (strcmp(f[i].key, m->key))
+ continue;
+ if (f[i].seen || m->number != number)
+ return -EINVAL;
+ if (m->number)
+ *(__s64 *)f[i].dst = m->value;
+ else if (strscpy(f[i].dst, m->text, f[i].dst_cap) < 0)
+ return -ENOSPC;
+ f[i].seen = 1;
+ }
+ }
+ return 0;
+}
+
+int json_parse(const char *data, size_t len, struct json_field *f, size_t n)
+{
+ __CPROVER_assert(n == 4 && !strcmp(f[0].key, "schema") &&
+ f[0].type == JSON_T_INT && !strcmp(f[1].key, "seq") &&
+ f[1].type == JSON_T_INT && !strcmp(f[2].key, "id") &&
+ f[2].type == JSON_T_STRING &&
+ f[2].dst_cap == TREE_STRING_MAX &&
+ !strcmp(f[3].key, "operation_digest") &&
+ f[3].type == JSON_T_STRING && f[3].dst_cap == 128,
+ "the record's four fields, each with its room");
+ if (reading_back)
+ return members_read(f, n);
+ if (found.seen[0])
+ *(__s64 *)f[0].dst = found.schema;
+ if (found.seen[1])
+ *(__s64 *)f[1].dst = found.seq;
+ if (found.seen[2])
+ memcpy(f[2].dst, found.id, sizeof(found.id));
+ if (found.seen[3])
+ memcpy(f[3].dst, found.digest, sizeof(found.digest));
+ for (int i = 0; i < 4; i++)
+ f[i].seen = found.seen[i];
+ return found.ret;
+}
+
+/* "sha256:" and 64 hex digits of either case. */
+static bool digest_text(const char *s)
+{
+ bool digits = true;
+
+ for (int i = 7; i < 71; i++)
+ digits &= (s[i] >= '0' && s[i] <= '9') ||
+ (s[i] >= 'a' && s[i] <= 'f') ||
+ (s[i] >= 'A' && s[i] <= 'F');
+ return !memcmp(s, "sha256:", 7) && digits && !s[71];
+}
+
+/* upatch-name proves which names upatch_name_valid() takes. */
+static void parsed(void)
+{
+ struct found any;
+ struct tree_pending out;
+ size_t len, i, d;
+ bool whole;
+ char body;
+ int ret;
+
+ /*
+ * A global starts as zeros to CBMC, a local as anything. An id of
+ * up to ID_MAX bytes and a digest of up to one byte more than a
+ * sha256 digest has, each ended by a constant, where CBMC stops.
+ */
+ found = any;
+ found.id[ID_MAX] = '\0';
+ found.digest[72] = '\0';
+ __CPROVER_assume(found.ret <= 0 && i <= ID_MAX && d <= 72);
+ ret = tree_pending_parse(&body, len, &out);
+ whole = !found.ret && found.seen[0] && found.schema == 1 &&
+ found.seen[1] && found.seq > 0 && found.seen[2] &&
+ upatch_name_valid(found.id) && found.seen[3] &&
+ digest_text(found.digest);
+ __CPROVER_assert(!ret == whole,
+ "exactly a whole record of schema 1 is taken");
+ if (ret) {
+ __CPROVER_assert(ret == (found.ret ? found.ret : -EINVAL),
+ "the parser's error, or -EINVAL");
+ return;
+ }
+ __CPROVER_assert(out.seq == found.seq && out.id[i] == found.id[i] &&
+ out.operation_digest[d] == found.digest[d],
+ "the record as read");
+}
+
+/* Whatever an operation holds as id and digest, the record has room for. */
+_Static_assert(sizeof(((struct tree_operation *)0)->id) <=
+ sizeof(((struct tree_pending *)0)->id) &&
+ sizeof(((struct tree_operation *)0)->operation_digest) <=
+ sizeof(((struct tree_pending *)0)->operation_digest),
+ "an operation's id and digest fit the pending record");
+
+/*
+ * tree sync writes the record of an operation of a publication it has
+ * checked: tree_operation_validate() refuses a seq that is not positive,
+ * an id that is no upatch name and an operation digest that is no sha256
+ * digest, which has 71 bytes. The id has up to ID_MAX bytes here; each
+ * NUL is a constant, where CBMC stops.
+ */
+static void written(void)
+{
+ int any_emit, any_mkdir, any_write;
+ struct tree_operation op;
+ __u8 digest[32];
+ size_t i, d;
+ int ret;
+
+ emit_error = any_emit;
+ mkdir_error = any_mkdir;
+ write_error = any_write;
+ __CPROVER_assume(emit_error <= 0 && mkdir_error <= 0 &&
+ write_error <= 0 && i <= ID_MAX && d <= 71);
+ op.id[ID_MAX] = '\0';
+ op.operation_digest[71] = '\0';
+ __CPROVER_assume(op.seq > 0 && upatch_name_valid(op.id) &&
+ !sha256_digest_decode(op.operation_digest, digest) &&
+ i <= strnlen(op.id, ID_MAX));
+ ret = tree_pending_write(&op);
+ __CPROVER_assert(closed && n_members == 4 &&
+ !strcmp(members[0].key, "schema") &&
+ members[0].number && members[0].value == 1 &&
+ !strcmp(members[1].key, "seq") && members[1].number &&
+ members[1].value == op.seq &&
+ !strcmp(members[2].key, "id") && !members[2].number &&
+ members[2].text == op.id &&
+ !strcmp(members[3].key, "operation_digest") &&
+ !members[3].number &&
+ members[3].text == op.operation_digest,
+ "schema 1 and the operation's seq, id and digest");
+ if (emit_error || mkdir_error) {
+ int error = emit_error ? emit_error : mkdir_error;
+
+ __CPROVER_assert(ret == error && !n_written,
+ "no file without the document and its room");
+ return;
+ }
+ __CPROVER_assert(n_written == 1 && ret == write_error,
+ "written once, with the result of the write");
+ __CPROVER_assert(!read_back_ret && read_back.seq == op.seq &&
+ read_back.id[i] == op.id[i] &&
+ read_back.operation_digest[d] ==
+ op.operation_digest[d],
+ "what is written reads back as the operation's");
+}
+
+void harness(void)
+{
+ parsed();
+ written();
+}
diff --git a/testing/proofs/cbmc/bpm-tree-state-replay-lines.c b/testing/proofs/cbmc/bpm-tree-state-replay-lines.c
new file mode 100644
index 00000000..1dac710e
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-state-replay-lines.c
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * How tree_event_replay() of util/bpm_tree_state.c cuts the tree eventlog
+ * into lines, on every eventlog of LEN bytes: each whole line is read
+ * once and in order, an empty line is skipped, nothing of a last line
+ * without its newline is read, and a log with a NUL is refused unread.
+ * The lines hold records that replay, but for one line at most.
+ */
+
+#define TREE_REPLAY_LINES 1
+#include "bpm-tree-state-replay.c"
diff --git a/testing/proofs/cbmc/bpm-tree-state-replay.c b/testing/proofs/cbmc/bpm-tree-state-replay.c
new file mode 100644
index 00000000..16f9ca15
--- /dev/null
+++ b/testing/proofs/cbmc/bpm-tree-state-replay.c
@@ -0,0 +1,333 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * tree_event_replay() of util/bpm_tree_state.c is replayFrom of
+ * testing/proofs/lean4/Shirudo/TreeSync.lean on every eventlog of LEN
+ * lines: the root exactly when each line continues the chain, else an
+ * error with nothing written. bpm-tree-state-replay-lines.c includes this
+ * file for the bytes of the log. JSON, hex and SHA-256 are stubs.
+ */
+
+#include "proof.h"
+#include "../../../util/bpm_tree_state.c"
+/* lines_len() as the code has it; the file comes from the stub below. */
+#define read_file read_file_unused
+#include "../../../util/io.c"
+#undef read_file
+
+#ifdef TREE_REPLAY_LINES
+/* Each line is a byte and its newline at least. */
+#define LOG_LEN LEN
+#define LINES_MAX (LEN / 2 + 1)
+#else
+#define LOG_LEN (2 * LEN)
+#define LINES_MAX (LEN + 1)
+#endif
+
+/* What json_parse() finds in a line: any fields, any values, or an error. */
+struct record {
+ int ret;
+ bool seen[3];
+ __s64 seq;
+ char digest[128];
+ char root[65];
+};
+
+static struct record records[LINES_MAX];
+static size_t line_at[LINES_MAX], line_len[LINES_MAX];
+static int n_lines;
+static char original[LOG_LEN + 1], log_body[LOG_LEN + 1];
+static int read_error, hash_error, n_freed;
+
+/* CBMC has no strtok_r(); glibc's, with strspn() and strcspn() as loops. */
+char *strtok_r(char *s, const char *delim, char **save)
+{
+ char *token;
+
+ if (!s)
+ s = *save;
+ while (*s && strchr(delim, *s))
+ s++;
+ if (!*s) {
+ *save = s;
+ return NULL;
+ }
+ token = s;
+ while (*s && !strchr(delim, *s))
+ s++;
+ if (*s)
+ *s++ = '\0';
+ *save = s;
+ return token;
+}
+
+/*
+ * The log lies in a buffer of the harness, filled before anything can
+ * fail: CBMC follows the bytes of a line as constants only when no
+ * branch wrote them. xfree() below counts its release.
+ */
+static void any_log(void)
+{
+#ifdef TREE_REPLAY_LINES
+ char any[LOG_LEN + 1];
+
+ memcpy(log_body, any, sizeof(log_body));
+#else
+ /* A line of one byte each, which keeps the lines apart for CBMC. */
+ for (int i = 0; i < LEN; i++) {
+ log_body[2 * i] = 'x';
+ log_body[2 * i + 1] = '\n';
+ }
+#endif
+ log_body[LOG_LEN] = '\0';
+ memcpy(original, log_body, LOG_LEN + 1);
+}
+
+/*
+ * The log is handed out before the read can fail, so that CBMC knows
+ * where it lies whatever the read returns; a failed read is checked to
+ * parse and release nothing.
+ */
+int read_file(const char *path, size_t max, void *out, size_t *len)
+{
+ *(char **)out = log_body;
+ *len = LOG_LEN;
+ return read_error;
+}
+
+void xfree(void *ptr, size_t size)
+{
+ __CPROVER_assert(ptr == log_body && size == LOG_LEN + 1,
+ "the log released whole");
+ n_freed++;
+}
+
+int json_parse(const char *data, size_t len, struct json_field *f, size_t n)
+{
+ const struct record *r;
+
+ __CPROVER_assert(n_lines < LINES_MAX, "no more lines than the log has");
+ __CPROVER_assert(n == 3 && f[0].type == JSON_T_INT &&
+ f[1].type == JSON_T_STRING && f[1].dst_cap == 128 &&
+ f[2].type == JSON_T_STRING && f[2].dst_cap == 65,
+ "a line's three fields, each with its room");
+ __CPROVER_assert(len == strlen(data), "a line is parsed whole");
+ line_at[n_lines] = (size_t)(data - log_body);
+ line_len[n_lines] = len;
+ r = &records[n_lines++];
+ if (r->seen[0])
+ *(__s64 *)f[0].dst = r->seq;
+ if (r->seen[1])
+ memcpy(f[1].dst, r->digest, sizeof(r->digest));
+ if (r->seen[2]) {
+ /* The NUL as a constant ends CBMC's strlen() of the root. */
+ memcpy(f[2].dst, r->root, sizeof(r->root));
+ ((char *)f[2].dst)[sizeof(r->root) - 1] = '\0';
+ }
+ for (int i = 0; i < 3; i++)
+ f[i].seen = r->seen[i];
+ return r->ret;
+}
+
+/*
+ * util/hex.c has proofs of its own. Here 2 * n hex digits are any string
+ * that does not start with '!', and decode to its first n bytes.
+ */
+int hex_decode(const char *hex, __u8 *out, size_t n)
+{
+ __CPROVER_assert(n == 32, "a SHA-256 digest");
+ if (hex[0] == '!')
+ return -EINVAL;
+ for (size_t i = 0; i < n; i++)
+ out[i] = (__u8)hex[i];
+ return 0;
+}
+
+int sha256_digest_decode(const char *digest, __u8 out[32])
+{
+ return digest[0] == 's' ? hex_decode(digest + 7, out, 32) : -EINVAL;
+}
+
+/* SHA-256 as any function of 64 bytes that keeps their order apart. */
+static void model_hash(const __u8 *in, __u8 out[32])
+{
+ for (int i = 0; i < 32; i++) {
+ __u8 d = in[32 + i];
+
+ out[i] = in[i] ^ (((d & 0x7f) << 1) | (d >> 7));
+ }
+}
+
+int sha256_calc(const void *data, size_t len, __u8 out[32])
+{
+ __CPROVER_assert(len == 64, "the root before and the digest");
+ if (hash_error)
+ return hash_error;
+ model_hash(data, out);
+ return 0;
+}
+
+static bool text_of_64(const char *s)
+{
+ bool whole = true;
+
+ for (int i = 0; i < 64; i++)
+ whole &= s[i] != '\0';
+ return whole && !s[64];
+}
+
+/*
+ * One step of replayFrom: the line is above seq and records the hash of
+ * the chain and its digest, which the chain then is.
+ */
+static bool model_line(const struct record *r, __s64 *seq, __u8 chain[32])
+{
+ __u8 in[64], root[32], next[32];
+
+ if (r->ret || !r->seen[0] || !r->seen[1] || !r->seen[2] ||
+ r->seq <= *seq || !text_of_64(r->root) ||
+ hex_decode(r->root, root, 32) ||
+ sha256_digest_decode(r->digest, in + 32))
+ return false;
+ memcpy(in, chain, 32);
+ model_hash(in, next);
+ if (memcmp(next, root, 32))
+ return false;
+ *seq = r->seq;
+ memcpy(chain, next, 32);
+ return true;
+}
+
+/*
+ * The lines json_parse() saw are the whole lines of the log, in order:
+ * each runs from the start of a line to its newline, and no byte before
+ * the end of what was read, all of it without a refusal, is outside them
+ * but a newline. The loops run to constants, which CBMC unwinds no
+ * further.
+ */
+static void lines_whole(int ret)
+{
+ size_t whole = LOG_LEN, read_to = 0;
+
+ while (whole && original[whole - 1] != '\n')
+ whole--;
+ for (int i = 0; i < LINES_MAX; i++) {
+ size_t from = line_at[i], to = from + line_len[i];
+
+ if (i >= n_lines)
+ break;
+ __CPROVER_assert(line_len[i] && to < whole && from >= read_to,
+ "a line with its newline, after the last one");
+ __CPROVER_assert(original[to] == '\n' &&
+ (!from || original[from - 1] == '\n'),
+ "from the start of a line to its newline");
+ read_to = to + 1;
+ }
+ for (size_t at = 0; at < LOG_LEN; at++) {
+ bool in_line = false;
+
+ for (int i = 0; i < LINES_MAX; i++)
+ in_line |= i < n_lines && at >= line_at[i] &&
+ at < line_at[i] + line_len[i];
+ __CPROVER_assert(!in_line || original[at] != '\n', "one line");
+ __CPROVER_assert(in_line || original[at] == '\n' ||
+ at >= (ret ? read_to : whole),
+ "no line skipped");
+ }
+}
+
+#ifdef TREE_REPLAY_LINES
+/*
+ * Records that replay, each a line above the one before with a digest
+ * of its own, but for the one at bad, which json_parse() refuses.
+ */
+static void chained_records(int bad)
+{
+ __u8 in[64], chain[32] = {};
+
+ for (int i = 0; i < LINES_MAX; i++) {
+ struct record *r = &records[i];
+
+ memcpy(in, chain, 32);
+ memset(in + 32, 1 << i, 32);
+ model_hash(in, chain);
+ __CPROVER_assert(chain[0] && chain[0] != '!',
+ "a root the stubs decode");
+ r->ret = i == bad ? -EINVAL : 0;
+ r->seen[0] = true;
+ r->seen[1] = true;
+ r->seen[2] = true;
+ r->seq = i + 1;
+ memset(r->digest, 1 << i, 71);
+ memcpy(r->digest, "sha256:", 7);
+ memcpy(r->root, chain, 32);
+ memset(r->root + 32, 'r', 32);
+ }
+}
+#endif
+
+void harness(void)
+{
+ __u8 out[32], was[32], chain[32] = {};
+ int any_read_error, any_hash_error;
+ bool nul = false, lines = true;
+#ifdef TREE_REPLAY_LINES
+ int bad;
+#else
+ struct record any_records[LINES_MAX];
+#endif
+ __s64 seq = 0;
+ int ret;
+
+ /* A global starts as zeros to CBMC, a local as anything. */
+ read_error = any_read_error;
+ hash_error = any_hash_error;
+ __CPROVER_assume(read_error <= 0 && hash_error <= 0);
+#ifdef TREE_REPLAY_LINES
+ chained_records(bad);
+#else
+ memcpy(records, any_records, sizeof(records));
+ for (int i = 0; i < LINES_MAX; i++)
+ __CPROVER_assume(!records[i].digest[127] &&
+ !records[i].root[64] && records[i].ret <= 0);
+#endif
+ any_log();
+ memcpy(was, out, 32);
+ ret = tree_event_replay(out);
+ __CPROVER_assert(n_freed == !read_error,
+ "the log released once, when it was read");
+ if (read_error) {
+ __CPROVER_assert(ret == read_error && !n_lines &&
+ !memcmp(out, was, 32),
+ "a log that cannot be read is its error");
+ return;
+ }
+ for (int i = 0; i < LOG_LEN; i++)
+ nul |= !original[i];
+ if (nul) {
+ __CPROVER_assert(ret == -EINVAL && !n_lines &&
+ !memcmp(out, was, 32),
+ "a log with a NUL is refused unread");
+ return;
+ }
+ lines_whole(ret);
+ for (int i = 0; i < LINES_MAX; i++) {
+ bool line;
+
+ if (i >= n_lines)
+ break;
+ line = !hash_error && model_line(&records[i], &seq, chain);
+ __CPROVER_assert(line || i == n_lines - 1,
+ "nothing read after a line that is refused");
+ lines &= line;
+ }
+ __CPROVER_assert(!ret == lines, "replayFrom of the model");
+ if (ret)
+ __CPROVER_assert((ret == -EINVAL || ret == hash_error) &&
+ !memcmp(out, was, 32),
+ "a refusal writes no root");
+ else
+ __CPROVER_assert(!memcmp(out, chain, 32),
+ "the root of the last line, or 32 zeros");
+}
diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.list
index e1e11b07..4df5555f 100644
--- a/testing/proofs/cbmc/proofs.list
+++ b/testing/proofs/cbmc/proofs.list
@@ -125,3 +125,11 @@ conditions-rows --object-bits 12 --max-field-sensitivity-array-size 192 --unwin
conditions-detail --object-bits 12 --unwind 195 --unwindset vsnprintf.2:836 LEN=193,1024
bpm-state-entry --unwind 1 --unwindset vsnprintf.1:31,vsnprintf.2:7,strcmp.0:42,memcmp.0:32,strlen.0:130,bpm_component_ok.0:130 LEN=0,1
bpm-state-emit --object-bits 12 --unwind 1 --unwindset bpm_state_emit.0:3,put_string_n.1:54,put_raw.0:3,vsnprintf.2:3,format_number.0:3,format_number.3:3,strlen.0:250,strcmp.0:250 LEN=0,26,27,123,124,247,248
+bpm-tree-overlap-model --unwind 3 --unwindset strcmp.0:4,strlen.0:4,strncmp.0:4,model_same.0:4,model_continues.0:4 LEN=2
+bpm-tree-overlap-live --unwind 2 --unwindset strcmp.0:9,model_same.0:9,add_live.0:4,add_live.1:4,add_live.2:4,tree_add_live.0:4
+bpm-tree-state-pairs --unwind 4 --unwindset strnlen.0:258,memcpy.0:258,strlen.0:67,hex_decode.0:33,digest_valid.0:65 LEN=0-2,255,256
+bpm-tree-state-replay --unwind 8 --unwindset strlen.0:66,hex_decode.0:33,text_of_64.0:65,model_hash.0:33,memneq_explicit.0:33,memcmp.0:33 LEN=0-3
+bpm-tree-state-replay-lines --unwind 8 --unwindset strlen.0:66,hex_decode.0:33,text_of_64.0:65,model_hash.0:33,memneq_explicit.0:33,memcmp.0:33 LEN=0-4,6
+bpm-tree-state-pending --unwind 5 --unwindset upatch_name_valid.0:10,strnlen.0:74,memcpy.0:257,strlen.0:66,strcmp.0:18,hex_decode.0:33,digest_text.0:65,memcmp.0:8,strncmp.0:8
+bpm-tree-state-match --unwind 4 --unwindset read_config_stream.0:7,read_config_stream.1:9,read_config_stream.2:9,read_config_stream.3:9,read_config_stream.4:9,read_text_line.0:9,strlen.0:9,strchr.0:9,strnlen.0:9,memcpy.0:9,memcmp.0:26 LEN=0-3
+bpm-tree-state-options --unwind 4
diff --git a/testing/proofs/lean4/Shirudo.lean b/testing/proofs/lean4/Shirudo.lean
index c943e4f9..3b1f15bb 100644
--- a/testing/proofs/lean4/Shirudo.lean
+++ b/testing/proofs/lean4/Shirudo.lean
@@ -13,3 +13,4 @@ import Shirudo.JsonString
import Shirudo.ConfigActivation
import Shirudo.UpatchLoad
import Shirudo.TreeSync
+import Shirudo.TreeOverlap
diff --git a/testing/proofs/lean4/Shirudo/TreeOverlap.lean b/testing/proofs/lean4/Shirudo/TreeOverlap.lean
new file mode 100644
index 00000000..94221bc0
--- /dev/null
+++ b/testing/proofs/lean4/Shirudo/TreeOverlap.lean
@@ -0,0 +1,588 @@
+-- SPDX-License-Identifier: BSD-2-Clause
+-- Copyright (c) 2026 Authors of shirudo
+
+/-!
+Which operations of an upatch tree can meet on one node. `disjoint`,
+`covers` and `addLive` follow util/bpm_tree_overlap.c, `selectorMatches`
+follows `tree_selector_matches()` of util/bpm_tree_state.c, and the
+theorems show the first three sound for the fourth: both selectors are
+held against one node, whose two kernel configs agree.
+-/
+
+namespace Shirudo.TreeOverlap
+
+/-- A C string: its bytes before the NUL. -/
+abbrev Str := List Nat
+
+/-! ### Lists of values -/
+
+/-- `list_holds()`, and the loops of `tree_selector_matches()` and
+`selector_values_match()` that look for one string: `strcmp()` finds
+`value` in the list. -/
+def listHolds (list : List Str) (value : Str) : Bool :=
+ list.any (fun s => s == value)
+
+/-- `lists_share()`: a value of `a` is in `b`. -/
+def listsShare (a b : List Str) : Bool :=
+ a.any (fun s => listHolds b s)
+
+/-- `list_within()`: every value of `inner` is in `outer`. -/
+def listWithin (inner outer : List Str) : Bool :=
+ inner.all (fun s => listHolds outer s)
+
+theorem listHolds_iff (list : List Str) (value : Str) :
+ listHolds list value = true ↔ value ∈ list := by
+ simp [listHolds]
+
+theorem listsShare_iff (a b : List Str) :
+ listsShare a b = true ↔ ∃ v, v ∈ a ∧ v ∈ b := by
+ simp [listsShare, listHolds_iff]
+
+theorem listWithin_iff (inner outer : List Str) :
+ listWithin inner outer = true ↔ ∀ v, v ∈ inner → v ∈ outer := by
+ simp [listWithin, listHolds_iff]
+
+theorem listsShare_comm (a b : List Str) : listsShare a b = listsShare b a := by
+ rw [Bool.eq_iff_iff, listsShare_iff, listsShare_iff]
+ exact ⟨fun ⟨v, ha, hb⟩ => ⟨v, hb, ha⟩, fun ⟨v, hb, ha⟩ => ⟨v, ha, hb⟩⟩
+
+/-! ### Release prefixes -/
+
+/-- `.` and `-`, which end a component of a kernel release. -/
+def dot : Nat := 0x2e
+def dash : Nat := 0x2d
+
+/-- What `kernel_release_prefix_matches()` lets follow a prefix in a
+release: its end, a `.` or a `-`. -/
+def boundary : Str → Bool
+ | [] => true
+ | c :: _ => c == dot || c == dash
+
+/-- `strncmp(release, prefix, strlen(prefix))` finding no difference, and
+then the byte of the release after the prefix. -/
+def continues : Str → Str → Bool
+ | release, [] => boundary release
+ | [], _ :: _ => false
+ | x :: release, y :: pre => x == y && continues release pre
+
+/-- `kernel_release_prefix_matches()`: an empty prefix takes every
+release. -/
+def prefixMatches (release pre : Str) : Bool :=
+ pre.isEmpty || continues release pre
+
+/-- `prefixes_share()`: one prefix takes the other read as a release. -/
+def prefixesShare (a b : List Str) : Bool :=
+ a.any (fun x => b.any (fun y => prefixMatches x y || prefixMatches y x))
+
+/-- `prefixes_within()`: each prefix of `inner`, read as a release, is
+taken by one of `outer`. -/
+def prefixesWithin (inner outer : List Str) : Bool :=
+ inner.all (fun x => outer.any (fun y => prefixMatches x y))
+
+theorem boundary_left (c t : Str) (h : boundary (c ++ t) = true) :
+ boundary c = true := by
+ cases c with
+ | nil => rfl
+ | cons x c => simpa [boundary] using h
+
+theorem boundary_append (c t : Str) (hc : boundary c = true)
+ (ht : boundary t = true) : boundary (c ++ t) = true := by
+ cases c with
+ | nil => simpa using ht
+ | cons x c => simpa [boundary] using hc
+
+/-- The release is the prefix and a rest that starts a new component. -/
+theorem continues_iff (release pre : Str) :
+ continues release pre = true ↔
+ ∃ t, release = pre ++ t ∧ boundary t = true := by
+ induction pre generalizing release with
+ | nil => simp [continues]
+ | cons y pre ih =>
+ cases release with
+ | nil => simp [continues]
+ | cons x release =>
+ simp only [continues, Bool.and_eq_true, beq_iff_eq, ih, List.cons_append,
+ List.cons.injEq]
+ constructor
+ · rintro ⟨rfl, t, rfl, ht⟩
+ exact ⟨t, ⟨rfl, rfl⟩, ht⟩
+ · rintro ⟨t, ⟨rfl, rfl⟩, ht⟩
+ exact ⟨rfl, t, rfl, ht⟩
+
+theorem prefixMatches_iff (release pre : Str) :
+ prefixMatches release pre = true ↔
+ pre = [] ∨ ∃ t, release = pre ++ t ∧ boundary t = true := by
+ simp [prefixMatches, continues_iff]
+
+/-- A prefix takes itself read as a release. -/
+theorem prefixMatches_self (s : Str) : prefixMatches s s = true :=
+ (prefixMatches_iff s s).2 (Or.inr ⟨[], by simp, rfl⟩)
+
+/-- Two prefixes that take one release: the longer continues the shorter
+at a component boundary, so the shorter takes it read as a release. -/
+theorem prefixes_meet (release a b : Str)
+ (ha : prefixMatches release a = true)
+ (hb : prefixMatches release b = true) :
+ prefixMatches a b = true ∨ prefixMatches b a = true := by
+ rw [prefixMatches_iff] at ha hb
+ rcases hb with rfl | ⟨tb, hrb, hbt⟩
+ · exact Or.inl ((prefixMatches_iff a []).2 (Or.inl rfl))
+ rcases ha with rfl | ⟨ta, hra, hat⟩
+ · exact Or.inr ((prefixMatches_iff b []).2 (Or.inl rfl))
+ rw [hra] at hrb
+ rcases List.append_eq_append_iff.1 hrb with ⟨c, rfl, rfl⟩ | ⟨c, rfl, rfl⟩
+ · exact Or.inr ((prefixMatches_iff _ _).2
+ (Or.inr ⟨c, rfl, boundary_left c tb hat⟩))
+ · exact Or.inl ((prefixMatches_iff _ _).2
+ (Or.inr ⟨c, rfl, boundary_left c ta hbt⟩))
+
+/-- The comment above `prefixes_share()`: two prefixes take a common
+release exactly when one takes the other read as a release. -/
+theorem prefixes_meet_iff (a b : Str) :
+ (∃ release, prefixMatches release a = true ∧
+ prefixMatches release b = true) ↔
+ (prefixMatches a b = true ∨ prefixMatches b a = true) := by
+ constructor
+ · rintro ⟨release, ha, hb⟩
+ exact prefixes_meet release a b ha hb
+ · rintro (h | h)
+ · exact ⟨a, prefixMatches_self a, h⟩
+ · exact ⟨b, h, prefixMatches_self b⟩
+
+/-- A prefix that takes another read as a release takes every release
+the other takes. -/
+theorem prefix_within (release inner outer : Str)
+ (hio : prefixMatches inner outer = true)
+ (hri : prefixMatches release inner = true) :
+ prefixMatches release outer = true := by
+ rw [prefixMatches_iff] at hio hri
+ rw [prefixMatches_iff]
+ rcases hio with rfl | ⟨t1, rfl, h1⟩
+ · exact Or.inl rfl
+ rcases hri with h | ⟨t2, rfl, h2⟩
+ · have h' : outer = [] ∧ t1 = [] := by simpa using h
+ exact Or.inl h'.1
+ · exact Or.inr ⟨t1 ++ t2, by simp, boundary_append t1 t2 h1 h2⟩
+
+theorem prefixesShare_iff (a b : List Str) :
+ prefixesShare a b = true ↔
+ ∃ x, x ∈ a ∧ ∃ y, y ∈ b ∧
+ (prefixMatches x y = true ∨ prefixMatches y x = true) := by
+ simp [prefixesShare]
+
+theorem prefixesShare_comm (a b : List Str) :
+ prefixesShare a b = prefixesShare b a := by
+ rw [Bool.eq_iff_iff, prefixesShare_iff, prefixesShare_iff]
+ exact ⟨fun ⟨x, hx, y, hy, h⟩ => ⟨y, hy, x, hx, h.symm⟩,
+ fun ⟨y, hy, x, hx, h⟩ => ⟨x, hx, y, hy, h.symm⟩⟩
+
+/-! ### Selectors -/
+
+/-- `struct tree_selector_kv`: a kernel option or a label and the values
+a selector takes for it. -/
+structure Pair where
+ key : Str
+ values : List Str
+
+/-- `kvs_exclude()`: a key both name, with no value in common. -/
+def kvsExclude (a b : List Pair) : Bool :=
+ a.any (fun x => b.any (fun y =>
+ x.key == y.key && !listsShare x.values y.values))
+
+/-- `kvs_within()`: each pair of `outer` is held by a pair of `inner`
+with its key and no value outside its own. -/
+def kvsWithin (inner outer : List Pair) : Bool :=
+ outer.all (fun y => inner.any (fun x =>
+ x.key == y.key && listWithin x.values y.values))
+
+/-- `struct tree_selector`. -/
+structure Selector where
+ releasePrefix : List Str
+ buildId : List Str
+ architecture : List Str
+ kconfig : List Pair
+ labels : List Pair
+
+/-- `tree_selectors_disjoint()`. -/
+def disjoint (a b : Selector) : Bool :=
+ (!a.architecture.isEmpty && !b.architecture.isEmpty &&
+ !listsShare a.architecture b.architecture) ||
+ (!a.buildId.isEmpty && !b.buildId.isEmpty &&
+ !listsShare a.buildId b.buildId) ||
+ (!a.releasePrefix.isEmpty && !b.releasePrefix.isEmpty &&
+ !prefixesShare a.releasePrefix b.releasePrefix) ||
+ kvsExclude a.kconfig b.kconfig || kvsExclude a.labels b.labels
+
+/-- `selector_covers()`. -/
+def covers (outer inner : Selector) : Bool :=
+ (outer.architecture.isEmpty ||
+ (!inner.architecture.isEmpty &&
+ listWithin inner.architecture outer.architecture)) &&
+ (outer.buildId.isEmpty ||
+ (!inner.buildId.isEmpty && listWithin inner.buildId outer.buildId)) &&
+ (outer.releasePrefix.isEmpty ||
+ (!inner.releasePrefix.isEmpty &&
+ prefixesWithin inner.releasePrefix outer.releasePrefix)) &&
+ kvsWithin inner.kconfig outer.kconfig &&
+ kvsWithin inner.labels outer.labels
+
+/-! ### What a node takes a selector to mean -/
+
+/-- What `tree_selector_matches()` reads of the node it runs on: the
+release and the machine of `uname()`, `none` when it fails, the build ID
+`kernel_build_id_read()` gives, `none` when it gives none, the value the
+kernel config has for an option, `none` for an option it does not name,
+and the pairs of node.labels in the order of the file. -/
+structure Node where
+ uname : Option (Str × Str)
+ buildId : Option Str
+ kconfig : Str → Option Str
+ labels : List (Str × Str)
+
+/-- `kv_value()`: the value of the first pair with the key. -/
+def kvValue : List (Str × Str) → Str → Option Str
+ | [], _ => none
+ | (k, v) :: rest, key => if k == key then some v else kvValue rest key
+
+/-- One pair of a selector against the node: the node has a value for
+the key and `selector_values_match()` finds it among the pair's. -/
+def pairHeld (value : Str → Option Str) (p : Pair) : Bool :=
+ match value p.key with
+ | none => false
+ | some v => listHolds p.values v
+
+/-- The build IDs of a selector against the node's: a node without one
+matches none. -/
+def buildIdHeld (id : Option Str) (ids : List Str) : Bool :=
+ match id with
+ | none => false
+ | some v => listHolds ids v
+
+/-- A selector that names nothing, the tree's wildcard. -/
+def wildcard (s : Selector) : Bool :=
+ s.releasePrefix.isEmpty && s.buildId.isEmpty && s.architecture.isEmpty &&
+ s.kconfig.isEmpty && s.labels.isEmpty
+
+/-- `tree_selector_matches()` after `uname()`: each list that names
+something takes the node's value, and each pair too. -/
+def matchesOn (release machine : Str) (n : Node) (s : Selector) : Bool :=
+ (s.releasePrefix.isEmpty ||
+ s.releasePrefix.any (fun p => prefixMatches release p)) &&
+ (s.buildId.isEmpty || buildIdHeld n.buildId s.buildId) &&
+ (s.architecture.isEmpty || listHolds s.architecture machine) &&
+ s.kconfig.all (pairHeld n.kconfig) &&
+ s.labels.all (pairHeld (kvValue n.labels))
+
+/-- `tree_selector_matches()` returning 1: the wildcard matches before
+the node is read, and nothing else matches where `uname()` fails. -/
+def selectorMatches (n : Node) (s : Selector) : Bool :=
+ wildcard s ||
+ match n.uname with
+ | none => false
+ | some (release, machine) => matchesOn release machine n s
+
+/-! ### Soundness against that meaning -/
+
+theorem kvsExclude_iff (a b : List Pair) :
+ kvsExclude a b = true ↔
+ ∃ x, x ∈ a ∧ ∃ y, y ∈ b ∧ x.key = y.key ∧
+ listsShare x.values y.values = false := by
+ simp [kvsExclude]
+
+theorem kvsExclude_comm (a b : List Pair) :
+ kvsExclude a b = kvsExclude b a := by
+ rw [Bool.eq_iff_iff, kvsExclude_iff, kvsExclude_iff]
+ constructor
+ · rintro ⟨x, hx, y, hy, hk, hs⟩
+ exact ⟨y, hy, x, hx, hk.symm, by rw [listsShare_comm]; exact hs⟩
+ · rintro ⟨y, hy, x, hx, hk, hs⟩
+ exact ⟨x, hx, y, hy, hk.symm, by rw [listsShare_comm]; exact hs⟩
+
+theorem pairHeld_iff (value : Str → Option Str) (p : Pair) :
+ pairHeld value p = true ↔ ∃ v, value p.key = some v ∧ v ∈ p.values := by
+ unfold pairHeld
+ cases h : value p.key with
+ | none => simp
+ | some v => simp [listHolds_iff]
+
+/-- A node has one value for a key: pairs of one key that the node holds
+share that value. -/
+theorem held_not_exclude (value : Str → Option Str) (a b : List Pair)
+ (ha : a.all (pairHeld value) = true) (hb : b.all (pairHeld value) = true) :
+ kvsExclude a b = false := by
+ rw [← Bool.not_eq_true, kvsExclude_iff]
+ rintro ⟨x, hx, y, hy, hk, hs⟩
+ obtain ⟨v, hv, hvx⟩ := (pairHeld_iff value x).1 (List.all_eq_true.1 ha x hx)
+ obtain ⟨w, hw, hwy⟩ := (pairHeld_iff value y).1 (List.all_eq_true.1 hb y hy)
+ rw [hk, hw] at hv
+ have hwv : w = v := Option.some.inj hv
+ have : listsShare x.values y.values = true :=
+ (listsShare_iff _ _).2 ⟨v, hvx, hwv ▸ hwy⟩
+ rw [hs] at this
+ cases this
+
+/-- The pairs of `outer` hold on a node on which those of `inner` do. -/
+theorem held_within (value : Str → Option Str) (inner outer : List Pair)
+ (hw : kvsWithin inner outer = true)
+ (hi : inner.all (pairHeld value) = true) :
+ outer.all (pairHeld value) = true := by
+ rw [List.all_eq_true]
+ intro y hy
+ have hy' := List.all_eq_true.1 hw y hy
+ obtain ⟨x, hx, hxy⟩ := List.any_eq_true.1 hy'
+ rw [Bool.and_eq_true, beq_iff_eq, listWithin_iff] at hxy
+ obtain ⟨v, hv, hvx⟩ := (pairHeld_iff value x).1 (List.all_eq_true.1 hi x hx)
+ exact (pairHeld_iff value y).2 ⟨v, by rw [← hxy.1]; exact hv, hxy.2 v hvx⟩
+
+theorem wildcard_matchesOn (release machine : Str) (n : Node) (s : Selector)
+ (h : wildcard s = true) : matchesOn release machine n s = true := by
+ simp only [wildcard, Bool.and_eq_true, List.isEmpty_iff] at h
+ obtain ⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩ := h
+ simp [matchesOn, h1, h2, h3, h4, h5]
+
+theorem wildcard_not_disjoint (a b : Selector) (h : wildcard a = true) :
+ disjoint a b = false := by
+ simp only [wildcard, Bool.and_eq_true, List.isEmpty_iff] at h
+ obtain ⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩ := h
+ simp [disjoint, kvsExclude, h1, h2, h3, h4, h5]
+
+/-- Only the wildcard covers the wildcard. -/
+theorem covers_wildcard (outer inner : Selector) (h : covers outer inner = true)
+ (hw : wildcard inner = true) : wildcard outer = true := by
+ simp only [wildcard, Bool.and_eq_true, List.isEmpty_iff] at hw
+ obtain ⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩ := hw
+ simp only [covers, kvsWithin, h1, h2, h3, h4, h5, List.isEmpty_nil,
+ Bool.not_true, Bool.false_and, Bool.or_false, List.any_nil,
+ Bool.and_eq_true, List.all_eq_true] at h
+ obtain ⟨⟨⟨⟨g1, g2⟩, g3⟩, g4⟩, g5⟩ := h
+ have k4 : outer.kconfig = [] := by
+ cases hk : outer.kconfig with
+ | nil => rfl
+ | cons y ys =>
+ exact absurd (g4 y (by rw [hk]; exact List.mem_cons_self)) (by simp)
+ have k5 : outer.labels = [] := by
+ cases hk : outer.labels with
+ | nil => rfl
+ | cons y ys =>
+ exact absurd (g5 y (by rw [hk]; exact List.mem_cons_self)) (by simp)
+ simp [wildcard, g1, g2, g3, k4, k5]
+
+/-- No release, machine, build ID, config and labels match two selectors
+that `tree_selectors_disjoint()` calls disjoint. -/
+theorem disjoint_matchesOn (release machine : Str) (n : Node) (a b : Selector)
+ (h : disjoint a b = true)
+ (ha : matchesOn release machine n a = true)
+ (hb : matchesOn release machine n b = true) : False := by
+ simp only [matchesOn, Bool.and_eq_true, Bool.or_eq_true,
+ List.isEmpty_iff] at ha hb
+ obtain ⟨⟨⟨⟨har, hai⟩, haa⟩, hak⟩, hal⟩ := ha
+ obtain ⟨⟨⟨⟨hbr, hbi⟩, hba⟩, hbk⟩, hbl⟩ := hb
+ simp only [disjoint, Bool.or_eq_true, Bool.and_eq_true, Bool.not_eq_true',
+ List.isEmpty_eq_false_iff, held_not_exclude n.kconfig _ _ hak hbk,
+ held_not_exclude (kvValue n.labels) _ _ hal hbl, or_false,
+ Bool.false_eq_true] at h
+ rcases h with (⟨⟨hna, hnb⟩, hs⟩ | ⟨⟨hna, hnb⟩, hs⟩) | ⟨⟨hna, hnb⟩, hs⟩
+ · rcases haa with haa | haa
+ · exact hna haa
+ rcases hba with hba | hba
+ · exact hnb hba
+ have : listsShare a.architecture b.architecture = true :=
+ (listsShare_iff _ _).2
+ ⟨machine, (listHolds_iff _ _).1 haa, (listHolds_iff _ _).1 hba⟩
+ rw [hs] at this
+ cases this
+ · rcases hai with hai | hai
+ · exact hna hai
+ rcases hbi with hbi | hbi
+ · exact hnb hbi
+ cases hid : n.buildId with
+ | none => simp [buildIdHeld, hid] at hai
+ | some id =>
+ simp only [buildIdHeld, hid] at hai hbi
+ have : listsShare a.buildId b.buildId = true :=
+ (listsShare_iff _ _).2
+ ⟨id, (listHolds_iff _ _).1 hai, (listHolds_iff _ _).1 hbi⟩
+ rw [hs] at this
+ cases this
+ · rcases har with har | har
+ · exact hna har
+ rcases hbr with hbr | hbr
+ · exact hnb hbr
+ obtain ⟨x, hx, hrx⟩ := List.any_eq_true.1 har
+ obtain ⟨y, hy, hry⟩ := List.any_eq_true.1 hbr
+ have : prefixesShare a.releasePrefix b.releasePrefix = true :=
+ (prefixesShare_iff _ _).2
+ ⟨x, hx, y, hy, prefixes_meet release x y hrx hry⟩
+ rw [hs] at this
+ cases this
+
+/-- A selector that `selector_covers()` says covers another takes the
+release, machine, build ID, config and labels the other takes. -/
+theorem covers_matchesOn (release machine : Str) (n : Node)
+ (outer inner : Selector) (h : covers outer inner = true)
+ (hi : matchesOn release machine n inner = true) :
+ matchesOn release machine n outer = true := by
+ simp only [matchesOn, Bool.and_eq_true, Bool.or_eq_true,
+ List.isEmpty_iff] at hi
+ obtain ⟨⟨⟨⟨hir, hii⟩, hia⟩, hik⟩, hil⟩ := hi
+ simp only [covers, Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true',
+ List.isEmpty_iff, List.isEmpty_eq_false_iff] at h
+ obtain ⟨⟨⟨⟨ha, hb⟩, hr⟩, hk⟩, hl⟩ := h
+ simp only [matchesOn, Bool.and_eq_true, Bool.or_eq_true, List.isEmpty_iff]
+ refine ⟨⟨⟨⟨?_, ?_⟩, ?_⟩, held_within _ _ _ hk hik⟩, held_within _ _ _ hl hil⟩
+ · rcases hr with hr | ⟨hne, hw⟩
+ · exact Or.inl hr
+ rcases hir with hir | hir
+ · exact absurd hir hne
+ obtain ⟨x, hx, hrx⟩ := List.any_eq_true.1 hir
+ obtain ⟨y, hy, hxy⟩ := List.any_eq_true.1 (List.all_eq_true.1 hw x hx)
+ exact Or.inr (List.any_eq_true.2
+ ⟨y, hy, prefix_within release x y hxy hrx⟩)
+ · rcases hb with hb | ⟨hne, hw⟩
+ · exact Or.inl hb
+ rcases hii with hii | hii
+ · exact absurd hii hne
+ cases hid : n.buildId with
+ | none => simp [buildIdHeld, hid] at hii
+ | some id =>
+ simp only [buildIdHeld, hid] at hii ⊢
+ exact Or.inr ((listHolds_iff _ _).2
+ ((listWithin_iff _ _).1 hw id ((listHolds_iff _ _).1 hii)))
+ · rcases ha with ha | ⟨hne, hw⟩
+ · exact Or.inl ha
+ rcases hia with hia | hia
+ · exact absurd hia hne
+ exact Or.inr ((listHolds_iff _ _).2
+ ((listWithin_iff _ _).1 hw machine ((listHolds_iff _ _).1 hia)))
+
+/-- No node matches two selectors that `tree_selectors_disjoint()` calls
+disjoint. -/
+theorem disjoint_sound (n : Node) (a b : Selector) (h : disjoint a b = true) :
+ ¬(selectorMatches n a = true ∧ selectorMatches n b = true) := by
+ rintro ⟨ha, hb⟩
+ cases hwa : wildcard a with
+ | true => rw [wildcard_not_disjoint a b hwa] at h; cases h
+ | false =>
+ cases hu : n.uname with
+ | none => simp [selectorMatches, hwa, hu] at ha
+ | some u =>
+ obtain ⟨release, machine⟩ := u
+ simp only [selectorMatches, hwa, hu, Bool.false_or] at ha
+ have hb' : matchesOn release machine n b = true := by
+ cases hwb : wildcard b with
+ | true => exact wildcard_matchesOn release machine n b hwb
+ | false => simpa [selectorMatches, hwb, hu] using hb
+ exact disjoint_matchesOn release machine n a b h ha hb'
+
+/-- A selector that `selector_covers()` says covers another matches
+every node the other matches. -/
+theorem covers_sound (n : Node) (outer inner : Selector)
+ (h : covers outer inner = true) (hi : selectorMatches n inner = true) :
+ selectorMatches n outer = true := by
+ cases hwi : wildcard inner with
+ | true => simp [selectorMatches, covers_wildcard outer inner h hwi]
+ | false =>
+ cases hu : n.uname with
+ | none => simp [selectorMatches, hwi, hu] at hi
+ | some u =>
+ obtain ⟨release, machine⟩ := u
+ simp only [selectorMatches, hwi, hu, Bool.false_or] at hi
+ simp [selectorMatches, hu,
+ covers_matchesOn release machine n outer inner h hi]
+
+/-- The order of its two selectors does not matter to
+`tree_selectors_disjoint()`. -/
+theorem disjoint_comm (a b : Selector) : disjoint a b = disjoint b a := by
+ simp only [disjoint, listsShare_comm b.architecture,
+ listsShare_comm b.buildId, prefixesShare_comm b.releasePrefix,
+ kvsExclude_comm b.kconfig, kvsExclude_comm b.labels,
+ Bool.and_comm (!b.architecture.isEmpty),
+ Bool.and_comm (!b.buildId.isEmpty),
+ Bool.and_comm (!b.releasePrefix.isEmpty)]
+
+theorem listWithin_self (l : List Str) : listWithin l l = true :=
+ (listWithin_iff l l).2 (fun _ h => h)
+
+/-- A selector covers itself: a delete with the selector of an add
+reaches every node the add reached. -/
+theorem covers_refl (s : Selector) : covers s s = true := by
+ have hp : prefixesWithin s.releasePrefix s.releasePrefix = true := by
+ simp only [prefixesWithin, List.all_eq_true, List.any_eq_true]
+ exact fun x hx => ⟨x, hx, prefixMatches_self x⟩
+ have hk : ∀ l : List Pair, kvsWithin l l = true := by
+ intro l
+ simp only [kvsWithin, List.all_eq_true, List.any_eq_true, Bool.and_eq_true,
+ beq_iff_eq]
+ exact fun y hy => ⟨y, hy, rfl, listWithin_self y.values⟩
+ simp only [covers, listWithin_self, hp, hk, Bool.and_true]
+ cases s.architecture <;> cases s.buildId <;> cases s.releasePrefix <;> rfl
+
+/-! ### An add that a later delete ends -/
+
+/-- An operation of a publication, as far as `tree_add_live()` reads it:
+whether its `op` is `delete`, its upatch name and its selector. -/
+structure Op where
+ delete : Bool
+ id : Str
+ selector : Selector
+
+/-- The test of the loop of `tree_add_live()`: a delete of the same
+upatch whose selector covers the add's. -/
+def ends (add later : Op) : Bool :=
+ later.delete && later.id == add.id && covers later.selector add.selector
+
+/-- `tree_add_live()`: no operation after `index` ends the one at it. -/
+def addLive (ops : List Op) (index : Nat) : Bool :=
+ match ops[index]? with
+ | none => true
+ | some add => (ops.drop (index + 1)).all (fun later => !ends add later)
+
+/-- `tree_add_live()` says no exactly when an operation after `index`
+ends the one at it. -/
+theorem addLive_iff (ops : List Op) (index : Nat) :
+ addLive ops index = false ↔
+ ∃ add later j, ops[index]? = some add ∧ index < j ∧
+ ops[j]? = some later ∧ ends add later = true := by
+ unfold addLive
+ cases hadd : ops[index]? with
+ | none => simp
+ | some add =>
+ simp only [Option.some.injEq, exists_and_left, exists_eq_left']
+ rw [← Bool.not_eq_true, List.all_eq_true]
+ constructor
+ · intro h
+ apply Classical.byContradiction
+ intro hn
+ apply h
+ intro later hl
+ obtain ⟨k, hk⟩ := List.mem_iff_getElem?.1 hl
+ rw [List.getElem?_drop] at hk
+ cases he : ends add later with
+ | false => rfl
+ | true => exact absurd ⟨later, index + 1 + k, by omega, hk, he⟩ hn
+ · rintro ⟨later, j, hj, hl, he⟩ h
+ have hm : later ∈ ops.drop (index + 1) := by
+ rw [List.mem_iff_getElem?]
+ exact ⟨j - (index + 1), by
+ rw [List.getElem?_drop]
+ have : index + 1 + (j - (index + 1)) = j := by omega
+ rw [this]; exact hl⟩
+ have := h later hm
+ rw [he] at this
+ cases this
+
+/-- An add that `tree_add_live()` says is no longer live is followed by
+a delete of the same upatch whose selector matches every node the add's
+selector matches. -/
+theorem addLive_false (ops : List Op) (index : Nat)
+ (h : addLive ops index = false) :
+ ∃ add later j, ops[index]? = some add ∧ index < j ∧
+ ops[j]? = some later ∧ later.delete = true ∧ later.id = add.id ∧
+ ∀ n, selectorMatches n add.selector = true →
+ selectorMatches n later.selector = true := by
+ obtain ⟨add, later, j, hadd, hj, hl, he⟩ := (addLive_iff ops index).1 h
+ simp only [ends, Bool.and_eq_true, beq_iff_eq] at he
+ exact ⟨add, later, j, hadd, hj, hl, he.1.1, he.1.2,
+ fun n hn => covers_sound n later.selector add.selector he.2 hn⟩
+
+end Shirudo.TreeOverlap