eBPF-based security platform
bpm: record a tree operation's outcome and a publication at acceptance
John Fastabendf5f1c55894a9
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rstindex 9949e724..e169aa91 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -247,11 +247,15 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.- ``cmd_bpm_tree_sync()``, ``tree_recover_pending()``,``tree_publication_check()``, ``tree_publication_follows()``- The full command with 0 or 1 operation, every pending state,- selector answer and first failing I/O call, or no failure.- Names have one byte and the previous root has 32 symbolic bytes.- - Writes match the Lean model ``Shirudo.TreeSync`` in order;- nothing is written after a failure and every expected write- happens when nothing fails+ selector answer, install answer and first failing I/O call, or no+ failure. Names have one byte, and the previous root and the+ history root the outcomes record holds at the cursor have 32+ symbolic bytes each.+ - Writes match the Lean model ``Shirudo.TreeSync`` in order, the+ cut of the outcomes record, each outcome line with its code and+ both roots, and the state written at acceptance with the+ publication's head and base included; nothing is written after a+ failure and every expected write happens when nothing fails* - ``bpm-tree-sync-application``- ``cmd_bpm_tree_sync()``- Two operations with no pending record; every selector answer@@ -268,11 +272,14 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.* - ``bpm-tree-recovery-model``- ``tree_recover_pending()``- Publications with 0 to 2 operations, a matching or unrelated- pending record, each TPM replay class, the measured flag and- every first failing I/O call. The previous root has all 32- symbolic bytes.- - The return decision, ordered writes, cursor, tree ID, manifest- and both projection roots match the independent recovery model+ pending record, each TPM replay class, the measured flag,+ whether the upatch is loaded and every first failing I/O call.+ The previous root and the history root have all 32 symbolic+ bytes.+ - The return decision, ordered writes, the outcome lines of the+ operations passed over and of the pending one, cursor, tree ID,+ manifest, recorded head and base, both projection roots and the+ history root match the independent recovery model* - ``bpm-tree-overlap-model``- ``tree_selectors_disjoint()``, ``selector_covers()`` and the list,prefix and pair checks under them@@ -1118,11 +1125,18 @@ the model follows the C.between an append and its commit; ``applied_signed``,``applied_consistent``: an applied operation is one of a signedpublication of the tree, and that of every one when the signer never- gives a number two operations+ gives a number two operations; ``outcomes_cover``,+ ``outcomes_fixed``, ``lastSeq_le_head``: the outcomes record has a+ line for every operation from 1 to the cursor, in order, no line+ at or below the cursor ever changes, and the cursor never passes+ the head of the recorded publication- A manifest digest names one publication; the hash is injective on(root, digest) and never 64 zeros; only sync writes the tree files,each write whole, one sync at a time; the unlink of ``pending.json``- succeeds; an extend and its eventlog record are one write+ succeeds; an extend and its eventlog record are one write. An+ outcome line holds whether the selector matched, not which of 1+ and 3, and no history root; the check that the record covers the+ cursor is a theorem, not a branch of the model- CBMC: ``bpm-tree-follows`` for ``tree_publication_follows()``,``bpm-tree-sync-model`` and its two-operation variants forsync writes, ``bpm-tree-recovery-model`` for pending recovery,diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 1a1529dc..27d6aa6b 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -500,6 +500,13 @@ signed config image.* - ``t7105-bpm-tree-loaded``- An add whose upatch is already loaded with its payload counts asinstalled; a direct load of it is still refused+ * - ``t7106-bpm-tree-outcomes``+ - The outcomes record: a line for an applied, an unmatched and a+ module-absent operation, one line for each ``seq`` after a sync+ killed between the register extend and its state, and the+ accepted publication on record after a sync that failed at a+ fetch; the record agrees with the tree eventlog and the+ operations' digests throughout``otel`` (8)~~~~~~~~~~~~@@ -715,7 +722,7 @@ Coverage by area``bpm_oci``, ``bpm_package``* - upatch tree- ``t3011``, ``t5004``, ``t7005``, ``t7101``, ``t7102``,- ``t7103``, ``t7104``, ``t7105``, ``t9105``. Fuzz: ``tree``,+ ``t7103``, ``t7104``, ``t7105``, ``t7106``, ``t9105``. Fuzz: ``tree``,``tree-state``, ``kconfig``. Unit: ``bpm_tree``,``bpm_tree_overlap``, ``bpm_tree_state``, ``kernel_build_id``,``kernel_release``@@ -778,7 +785,7 @@ The threats are those of :doc:`/security/threat-model`.- ``t1006``, ``t4101``, ``t6115``, ``t6126``* - T7 The delivery path- ``t7002``, ``t7003``, ``t7005``, ``t7101``, ``t7102``,- ``t7103``, ``t7104``, ``t7105``, ``t8005``, ``t9105``+ ``t7103``, ``t7104``, ``t7105``, ``t7106``, ``t8005``, ``t9105``* - T8 Quantum-capable adversaries- ``t2001``, ``t2002``, ``t5001``, ``t8005``* - T9 A target lying about its statediff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 15c25546..6aa45696 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -402,7 +402,7 @@ worker per available CPU reported by ``nproc``. Each worker builds a loadartifact and its matching unload artifact. The ordinary fixture builders, includingthe policy and observability fixtures, and the independent unload artifactsalso build in CPU-sized batches. Payload hashes are read after their builders-finish, and the tree test registry is generated after its unload artifact.+finish, and the tree test registry is generated after its unload artifacts.Boot an interactive VM~~~~~~~~~~~~~~~~~~~~~~diff --git a/Documentation/operate/plan/overhead.rst b/Documentation/operate/plan/overhead.rstindex 0f5b2cd6..a5b9da60 100644--- a/Documentation/operate/plan/overhead.rst+++ b/Documentation/operate/plan/overhead.rst@@ -405,6 +405,11 @@ Disk writes- ``bpm upgrade`` rewrites ``bpm/state.json`` with ``fsync()`` everyminute, also when nothing changed. ``bpm repo update`` rewrites thecached index of every repository.+- ``bpm tree sync`` rewrites ``bpm/upatch-tree/state.json`` with+ ``fsync()`` twice every minute with a tree configured, also when+ nothing changed, and appends a line of about 220 bytes to+ ``bpm/upatch-tree/outcomes`` with ``fsync()`` for every new tree+ operation. It reads that file once at the start of a sync.- shirudo appends every eventlog record with ``fsync()``.- Map export creates an empty lock file for every map it exports in``/var/lib/shirudo/locks``, named by the kernel's map ID. Map IDs changediff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex 31e08833..77dd2a25 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -178,16 +178,24 @@ reading its options.#. It fetches the publication and checks its tree ID, generation, parentand sequence numbers against the state in``/var/lib/shirudo/bpm/upatch-tree/state.json``.+#. It drops from ``upatch-tree/outcomes`` what a sync that stopped left+ past the recorded ``last_seq``, refuses a record that does not cover+ it, completes an operation that sync left in progress, and records+ the publication in ``state.json``.#. For each new operation whose selector matches the node labels(``etc/shirudo/node.labels`` of the config image, or``/etc/shirudo/node.labels``), it fetches and verifies the artifact,loads (``add``) or unloads (``delete``) it, extends the register with- a tree event and records the new projection root.+ a tree event and records the new projection root. Every new+ operation, matched or not, gets its line in ``outcomes``.#. It prints a JSON report to standard output, or to ``--report``.-With ``--dry-run``, it reports which operations would apply and changes-nothing. An ``add`` whose kprobe target module is not loaded is skipped-and recorded as ``skipped: module not loaded``.+With ``--dry-run``, it reports which operations would apply and applies+none: it neither records the publication nor writes a line for a new+operation, but it still drops the leftovers in ``outcomes`` and+completes an operation left in progress. An ``add`` whose kprobe target+module is not loaded is skipped and recorded as ``skipped: module not+loaded``.tree append-----------diff --git a/Documentation/reference/failure-categories.rst b/Documentation/reference/failure-categories.rstindex 153dd1de..b022a5f6 100644--- a/Documentation/reference/failure-categories.rst+++ b/Documentation/reference/failure-categories.rst@@ -611,9 +611,14 @@ rc=<rc> (<strerror>)`` and exits 1:* - ``operation_validate``- An operation of the publication is malformed or its digest doesnot match.+ * - ``outcomes_check``+ - The ``outcomes`` record does not cover the recorded ``last_seq``:+ it is missing (``ENOENT``), has a gap or a malformed line, or ends+ early (``EBADMSG``), or it cannot be read or cut. Nothing is+ applied.* - ``pending_recovery``- An interrupted operation cannot be reconciled with the tree- eventlog.+ eventlog, or its ``outcomes`` lines or state cannot be written.* - ``selector_evaluate``- The selector cannot be evaluated: the node labels or the kernelconfig cannot be read. The cursor stays on the operation.@@ -635,8 +640,13 @@ rc=<rc> (<strerror>)`` and exits 1:- The register extend failed.* - ``tree_event_append``- The tree eventlog record cannot be appended.- * - ``tree_state_commit``, ``tree_state_commit_final``- - ``state.json`` cannot be written.+ * - ``tree_outcome_append``+ - The operation's ``outcomes`` line cannot be appended. The cursor+ stays before the operation.+ * - ``tree_state_commit_accept``, ``tree_state_commit``,+ ``tree_state_commit_final``+ - ``state.json`` cannot be written: when the publication is+ recorded, after an operation, or at the end of the sync.* - ``tree_status_write``- The per-operation status file cannot be written.diff --git a/Documentation/reference/files.rst b/Documentation/reference/files.rstindex 2019adaa..8ed65630 100644--- a/Documentation/reference/files.rst+++ b/Documentation/reference/files.rst@@ -166,12 +166,18 @@ the label as foreign. In the initrd, ``init`` binds* - ``bpm/upatch-tree/state.json``- ``bpm tree sync``- ``0600``- - Tree cursor: tree id, generation, last sequence number,- projection root, manifest digest.+ - Tree cursor: tree id, last sequence number and projection root,+ and the generation, manifest digest and head of the publication+ the target last accepted.* - ``bpm/upatch-tree/tree-eventlog``- ``bpm tree sync``- ``0600``- Append-only record of applied tree operations.+ * - ``bpm/upatch-tree/outcomes``+ - ``bpm tree sync``+ - ``0600``+ - One line for every tree operation the target processed, applied+ or not, with its outcome and the roots after it. Never pruned.* - ``bpm/upatch-tree/pending.json``- ``bpm tree sync``- ``0600``diff --git a/Documentation/reference/formats/bpm-formats.rst b/Documentation/reference/formats/bpm-formats.rstindex 6f369271..0cac29be 100644--- a/Documentation/reference/formats/bpm-formats.rst+++ b/Documentation/reference/formats/bpm-formats.rst@@ -533,12 +533,17 @@ not published.* - File- Content* - ``state.json``- - JSON object with ``schema`` (1), ``tree_id``, ``generation`` and- ``manifest_digest`` of the last applied publication, ``last_seq``,- ``projection_root`` and ``projection_root_tpm``. ``last_seq`` also- moves past operations whose selector does not match. ``head_seq``- and ``segment_base_seq`` are the ``head.seq`` and ``base.seq`` of- the publication the node last synced to. A state without one of+ - JSON object with ``schema`` (1), ``tree_id``, ``generation``,+ ``manifest_digest``, ``head_seq`` and ``segment_base_seq`` of the+ publication the node last accepted, ``last_seq``,+ ``projection_root`` and ``projection_root_tpm``. ``head_seq`` and+ ``segment_base_seq`` are the publication's ``head.seq`` and+ ``base.seq``. A sync records a publication once it passes the+ checks above and an interrupted operation is completed, before it+ processes the first new operation, so a sync that stops among them+ leaves ``last_seq`` at or below ``head_seq`` and the node refuses+ an older generation from then on. ``last_seq`` also moves past+ operations whose selector does not match. A state without one of``tree_id``, ``last_seq``, the two roots, ``head_seq`` and``segment_base_seq`` is refused.* - ``tree-eventlog``@@ -548,12 +553,37 @@ not published.previous root followed by the raw operation digest, starting from32 zero bytes. A last line without its newline is an append thatdid not finish: the replay skips it and the next append drops it.+ * - ``outcomes``+ - One JSON object per line and processed operation, in order from+ ``seq`` 1, with ``schema`` (1), ``seq``, ``outcome``,+ ``projection_root`` and ``history_root``. ``outcome`` is 1 for an+ operation that was applied, 2 for one whose selector did not+ match and 3 for an ``add`` that was measured but not loaded+ because of ``attach_target_missing``. ``projection_root`` is the+ node's projection root after the operation, which an unmatched+ one leaves where it was. ``history_root`` is the SHA-256 of+ ``shirudo-tree-history``, a NUL byte, the previous history root+ and the raw operation digest, starting from 32 zero bytes: it+ counts every operation, whatever its outcome, so it is the same+ on every node at the same ``seq``. A line is written and synced+ to disk before the ``state.json`` that covers it, and a line at+ or below ``last_seq`` is never rewritten. Lines past ``last_seq``+ and a last line without its newline are what a sync that stopped+ left: the next sync drops them before it appends. It then refuses+ a state with ``last_seq`` above 0 whose ``outcomes`` is missing+ (``ENOENT``), or has a gap or a malformed line or ends before+ ``last_seq`` (``EBADMSG``). Nothing rebuilds or prunes the file.* - ``pending.json``- JSON object with ``schema`` (1), ``seq``, ``id`` and``operation_digest`` while an operation is in progress. The nextsync completes the operation without applying it again when thetree eventlog or this boot's eventlog already records it, and- applies it again otherwise. An ``add`` applied again whose upatch+ applies it again otherwise. Completing it writes the ``outcomes``+ lines the stopped sync did not commit: outcome 2 for each+ operation between ``last_seq`` and the pending one, which that+ sync passed over, then the pending operation's, 3 when it is an+ ``add`` whose upatch is not loaded, with its ``status/<id>``, and+ 1 otherwise. An ``add`` applied again whose upatcha stopped sync already loaded with its payload counts asinstalled.* - ``artifacts/<hex>.upatch``diff --git a/Documentation/reference/versions.rst b/Documentation/reference/versions.rstindex be86e942..f3c5ac37 100644--- a/Documentation/reference/versions.rst+++ b/Documentation/reference/versions.rst@@ -203,7 +203,8 @@ State the target keeps for itself:- Refused as malformed (``EBADMSG``). The active config can thennot be verified, and commands stop with ``shirudo: image state:``and the error.- * - ``state.json`` and ``pending.json`` of the upatch tree+ * - ``state.json`` and ``pending.json`` of the upatch tree and the+ lines of its ``outcomes``- 1- Refused by ``bpm tree sync``.diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex e657c84b..91daa9b5 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -1028,7 +1028,10 @@ it against the active config's non-revoked BPF signer set. Everymember must also be present in the sealed ``.bpf`` keyring. A publicationcarries a digest for each operation, is the one the target recorded orhas a higher generation, and names its parent, which the target-compares when the generation is exactly one higher. A delete applies+compares when the generation is exactly one higher. The target records+a publication when it accepts it, before it applies the first new+operation, so one it stopped in the middle of is not followed by an+older one. A delete appliesthe signed unload directive whose name equals the operation's id.The transport is TLS 1.3 only, with the hybrid groups@@ -1050,7 +1053,7 @@ and tree signatures accept algorithms other than ML-DSA (U4).:Refusal: the ``bpm`` command fails and installs nothing:Counters: none:Tests: ``t7005``, ``t7101``, ``t7102``, ``t7103``, ``t7104``,- ``t7105``, ``t8005``+ ``t7105``, ``t7106``, ``t8005``:Proofs: ``bpm-tar-header``, ``bpm-tar-octal``, ``bpm-archive-path``,``bpm-oci-challenge``, ``bpm-oci-token``, ``bpm-oci-header``,``bpm-oci-descriptor``, ``bpm-semver-model``, ``Shirudo.SemVer``,diff --git a/builtin-bpm.c b/builtin-bpm.cindex fa12b56e..08d04a59 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -54,6 +54,7 @@#include "util/paths.h"#include "util/seal.h"#include "util/upatch.h"+#include "util/upatch_pins.h"#include "util/upatch_rodata.h"struct bpm_source {@@ -1816,6 +1817,15 @@ static void tree_status_clear(const char *id)unlink(path);}+static int tree_status_update(const char *id, bool module_absent)+{+ if (!module_absent) {+ tree_status_clear(id);+ return 0;+ }+ return tree_status_write(id, "skipped: module not loaded");+}+/** event = SHA256("shirudo-tree\0" || seq || operation_digest). The* tree's own projection stays a file chain; the register is what an@@ -1864,19 +1874,73 @@ static int tree_measure_operation(const struct tree_operation *op,return ret;}+static int tree_outcome_record(__s64 seq, const __u8 operation_digest[32],+ enum tree_outcome outcome,+ const __u8 projection_root[32],+ __u8 history_root[32])+{+ int ret;++ ret = chain_history_step(history_root, operation_digest, history_root);+ if (ret)+ return ret;+ return tree_outcome_append(seq, outcome, projection_root, history_root);+}++static int tree_outcome_unmatched(const struct tree_operation *op,+ const __u8 projection_root[32],+ __u8 history_root[32])+{+ __u8 digest[32];++ if (sha256_digest_decode(op->operation_digest, digest))+ return -EINVAL;+ return tree_outcome_record(op->seq, digest, TREE_OUTCOME_UNMATCHED,+ projection_root, history_root);+}++/*+ * The operations between the cursor and the pending one had no match in+ * the sync that stopped: it would have committed the cursor at one that+ * had.+ */+static int tree_outcomes_passed(const struct tree_publication *pub,+ __s64 last_seq, __s64 pending_seq,+ const __u8 projection_root[32],+ __u8 history_root[32])+{+ int ret;++ for (int i = 0; i < pub->n_operations; i++) {+ const struct tree_operation *op = &pub->operations[i];++ if (op->seq >= pending_seq)+ break;+ if (op->seq <= last_seq)+ continue;+ ret = tree_outcome_unmatched(op, projection_root, history_root);+ if (ret)+ return ret;+ }+ return 0;+}+/** Complete the only non-idempotent window: the process may have* measured the operation, or appended its tree event too, before the* sealed cursor was committed. Applying it again would extend the- * register with it a second time this boot.+ * register with it a second time this boot. The install's answer went+ * with the process, so an add whose upatch is not loaded is one whose+ * module was absent.*/static int tree_recover_pending(const struct tree_publication *pub,- struct tree_state *state)+ struct tree_state *state,+ __u8 history_root[32]){struct tree_pending pending;const struct tree_operation *op = NULL;__u8 digest[32], previous[32], next[32], replay[32];- bool applied = false, event_present = false;+ bool applied = false, event_present = false, absent;int ret;ret = tree_pending_read(&pending);@@ -1932,10 +1996,23 @@ static int tree_recover_pending(const struct tree_publication *pub,if (ret)return ret;}+ ret = tree_outcomes_passed(pub, state->last_seq, op->seq, previous,+ history_root);+ if (ret)+ return ret;+ absent = !strcmp(op->op, "add") && !upatch_loaded_pins(op->id);+ ret = tree_outcome_record(op->seq, digest,+ absent ? TREE_OUTCOME_MODULE_ABSENT :+ TREE_OUTCOME_APPLIED,+ next, history_root);+ if (ret)+ return ret;hex_encode(next, sizeof(next), state->projection_root);hex_encode(next, sizeof(next), state->projection_root_tpm);state->last_seq = op->seq;ret = tree_state_write(state);+ if (!ret)+ ret = tree_status_update(op->id, absent);if (ret)return ret;unlink(BPM_TREE_PENDING_PATH);@@ -1975,6 +2052,7 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)struct tree_state state = {};char manifest_digest[BPM_MAX_DIGEST];char report[PATH_MAX] = {};+ __u8 root[32], history_root[32];bool dry_run = false, have_state = false;int selected = 0, skipped = 0, applied = 0, module_skipped = 0;int tpm_available = 0;@@ -2053,17 +2131,42 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)memset(state.projection_root_tpm, '0', 64);state.projection_root_tpm[64] = '\0';}- state.head_seq = pub.head_seq;- state.segment_base_seq = pub.base_seq;- ret = tree_recover_pending(&pub, &state);+ ret = tree_outcomes_resume(state.last_seq, history_root);+ if (ret) {+ tree_sync_report_error("outcomes_check", NULL, ret);+ goto out;+ }+ ret = tree_recover_pending(&pub, &state, history_root);if (ret) {tree_sync_report_error("pending_recovery", NULL, ret);goto out;}+ /*+ * Recorded before its first operation is processed, so that a+ * sync that stops among them leaves the cursor within the+ * publication the state names.+ */+ if (!dry_run) {+ state.generation = pub.generation;+ bpm_copy_string(state.manifest_digest, sizeof(state.manifest_digest),+ manifest_digest);+ state.head_seq = pub.head_seq;+ state.segment_base_seq = pub.base_seq;+ ret = tree_state_write(&state);+ if (ret) {+ tree_sync_report_error("tree_state_commit_accept", NULL, ret);+ goto out;+ }+ }+ if (hex_decode(state.projection_root, root, sizeof(root))) {+ tree_sync_report_error("projection_root_decode", NULL, -EINVAL);+ ret = -EINVAL;+ goto out;+ }tpm_available = chain_bound();for (int i = 0; i < pub.n_operations; i++) {struct tree_operation *op = &pub.operations[i];- __u8 digest[32], previous[32], next[32];+ __u8 digest[32], next[32];char artifact[PATH_MAX];bool skipped_module = false;@@ -2076,8 +2179,14 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)}if (!ret) {skipped++;- if (!dry_run)- state.last_seq = op->seq;+ if (dry_run)+ continue;+ ret = tree_outcome_unmatched(op, root, history_root);+ if (ret) {+ tree_sync_report_error("tree_outcome_append", op, ret);+ goto out;+ }+ state.last_seq = op->seq;continue;}selected++;@@ -2118,12 +2227,7 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)tree_sync_report_error("upatch_install", op, ret);goto out;}- if (hex_decode(state.projection_root, previous, 32)) {- tree_sync_report_error("projection_root_decode", op, -EINVAL);- ret = -EINVAL;- goto out;- }- ret = sha256_2(previous, 32, digest, 32, next);+ ret = sha256_2(root, 32, digest, 32, next);if (ret) {tree_sync_report_error("projection_root_hash", op, ret);goto out;@@ -2133,6 +2237,7 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)tree_sync_report_error("register_extend", op, ret);goto out;}+ memcpy(root, next, sizeof(root));hex_encode(next, 32, state.projection_root);hex_encode(next, 32, state.projection_root_tpm);ret = tree_event_append(op->seq, op->operation_digest, next);@@ -2140,6 +2245,15 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)tree_sync_report_error("tree_event_append", op, ret);goto out;}+ ret = tree_outcome_record(op->seq, digest,+ skipped_module ?+ TREE_OUTCOME_MODULE_ABSENT :+ TREE_OUTCOME_APPLIED,+ next, history_root);+ if (ret) {+ tree_sync_report_error("tree_outcome_append", op, ret);+ goto out;+ }state.last_seq = op->seq;applied++;ret = tree_state_write(&state);@@ -2147,22 +2261,15 @@ static int cmd_bpm_tree_sync(int argc, const char **argv)tree_sync_report_error("tree_state_commit", op, ret);goto out;}- if (skipped_module)- ret = tree_status_write(op->id, "skipped: module not loaded");- else- tree_status_clear(op->id);+ ret = tree_status_update(op->id, skipped_module);if (ret) {tree_sync_report_error("tree_status_write", op, ret);goto out;}unlink(BPM_TREE_PENDING_PATH);}+ /* A run of operations without a match at the end moved the cursor. */if (!dry_run) {- state.generation = pub.generation;- bpm_copy_string(state.manifest_digest, sizeof(state.manifest_digest),- manifest_digest);- if (!state.tree_id[0])- bpm_copy_string(state.tree_id, sizeof(state.tree_id), pub.tree_id);ret = tree_state_write(&state);if (ret) {tree_sync_report_error("tree_state_commit_final", NULL, ret);diff --git a/testing/functional/bpm/t7106-bpm-tree-outcomes.sh b/testing/functional/bpm/t7106-bpm-tree-outcomes.shnew file mode 100644index 00000000..6bfe0a1f--- /dev/null+++ b/testing/functional/bpm/t7106-bpm-tree-outcomes.sh@@ -0,0 +1,280 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t7106 -- the outcomes record has one line for every operation the node+# processed: applied, unmatched and module absent, after a sync that was+# killed between the register extend and its state, and after one that+# failed at a fetch, which leaves the publication it accepted on record.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"++FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+REGISTRY="$FIXTURES/tree-oci"+TREE_DIR=/var/lib/shirudo/bpm/upatch-tree+OUTCOMES=$TREE_DIR/outcomes+TREE_EVENTLOG=$TREE_DIR/tree-eventlog+PENDING=$TREE_DIR/pending.json+EVENTLOG=/var/lib/shirudo/eventlog+ABSENT=shirudo-test-uprobe-multi+MATCH_PIN=/run/shirudo/bpffs/upatches/shirudo-test-tree-match/link+SKIP_PIN=/run/shirudo/bpffs/upatches/shirudo-test-tree-skip/link+WORK=$(mktemp -d)+SERVED="$WORK/registry"+TREE_REPO="$SERVED/shirudo/upatch-tree"+HOLDER_PID=++for fixture in \+ "$REGISTRY/shirudo/upatch-tree/manifests/outcomes" \+ "$REGISTRY/shirudo/upatch-tree/manifests/stopped" \+ "$REGISTRY/shirudo/upatch-tree/manifests/fetched" \+ "$FIXTURES/shirudo-test-tree-match.unload.upatch" \+ "$FIXTURES/shirudo-test-tree-skip.unload.upatch" \+ "$FIXTURES/cert.der" \+ "./helper/test-oci-registry.py"+do+ [ -s "$fixture" ] || test_skip_all "missing tree fixture: $fixture"+done+[ -d "$REGISTRY/shirudo/tree-absent" ] &&+ [ -d "$REGISTRY/shirudo/tree-skip-unload" ] ||+ test_skip_all "missing tree fixture artifacts"++[ "$(tree_state_field tree_id)" = shirudo-test-tree ] &&+ [ "$(tree_state_field last_seq)" = 7 ] &&+ [ ! -e "$MATCH_PIN" ] && [ ! -e "$SKIP_PIN" ] ||+ test_skip_all "tree state is not where t7105 leaves it"+# The upatch of operation 10 probes this file, which only the upatch+# family's tests put there.+[ ! -e /tmp/shirudo-test-uprobe-target ] ||+ test_skip_all "the uprobe target of operation 10 is present"++release_tree_eventlog()+{+ [ -n "$HOLDER_PID" ] || return 0+ kill "$HOLDER_PID" 2>/dev/null || true+ wait "$HOLDER_PID" 2>/dev/null || true+ HOLDER_PID=+}++cleanup()+{+ release_tree_eventlog+ tree_registry_stop+ for name in shirudo-test-tree-match shirudo-test-tree-skip; do+ [ -e "/run/shirudo/bpffs/upatches/$name/link" ] || continue+ "$SHIRUDO_BIN" upatch unload \+ "$FIXTURES/$name.unload.upatch" \+ --no-precheck >/dev/null 2>&1 || true+ done+ tree_cleanup_config+ rm -rf "$WORK"+}+trap cleanup EXIT++# The record holds exactly the lines of seq 1 to $1, each with the history+# root its operation digests fold to and the projection root the tree+# eventlog has at it: outcome 1 or 3 where the eventlog has a line, 2+# where it has none. The arguments after $1 are the outcomes of the last+# lines.+outcomes_agree()+{+ python3 - "$OUTCOMES" "$TREE_EVENTLOG" "$TREE_REPO" "$@" <<'PY'+import hashlib+import json+import pathlib+import sys++outcomes, eventlog, repo = map(pathlib.Path, sys.argv[1:4])+head = int(sys.argv[4])+want = [int(code) for code in sys.argv[5:]]++manifest = json.loads((repo / "manifests" / "fetched").read_bytes())+document = (repo / "blobs" / manifest["layers"][0]["digest"]).read_bytes()+digests = {op["seq"]: bytes.fromhex(op["operation_digest"][len("sha256:"):])+ for op in json.loads(document)["operations"]}+applied = {}+for text in eventlog.read_text(encoding="utf-8").splitlines():+ event = json.loads(text)+ applied[event["seq"]] = event["projection_root"]++lines = [json.loads(text)+ for text in outcomes.read_text(encoding="utf-8").splitlines()]+seqs = [line["seq"] for line in lines]+if seqs != list(range(1, head + 1)):+ sys.exit(f"outcomes has the lines {seqs}, not 1 to {head}")+if set(applied) - set(seqs):+ sys.exit(f"the tree eventlog has lines past {head}: {sorted(applied)}")+projection = "00" * 32+history = bytes(32)+for line in lines:+ seq = line["seq"]+ history = hashlib.sha256(b"shirudo-tree-history\0" + history ++ digests[seq]).digest()+ if seq in applied:+ projection = applied[seq]+ codes = (1, 3)+ else:+ codes = (2,)+ if line["schema"] != 1 or line["outcome"] not in codes:+ sys.exit(f"line {seq} has outcome {line['outcome']}, not one of {codes}")+ if line["projection_root"] != projection:+ sys.exit(f"line {seq} has another projection root than the eventlog")+ if line["history_root"] != history.hex():+ sys.exit(f"line {seq} has another history root than its digests give")+got = [line["outcome"] for line in lines][len(lines) - len(want):]+if got != want:+ sys.exit(f"the last outcomes are {got}, not {want}")+PY+}++outcomes_last()+{+ python3 -c '+import json, sys+lines = open(sys.argv[1], encoding="utf-8").read().splitlines()+last = json.loads(lines[-1])+print(len(lines), last["seq"], last["outcome"])+' "$OUTCOMES"+}++# Hold the lock tree_event_append() takes, so that a sync stops where it+# appends an operation's line: after the register extend, before the+# outcomes line and the state.+hold_tree_eventlog()+{+ python3 -c '+import fcntl, os, sys, time+fd = os.open(sys.argv[1], os.O_RDONLY)+fcntl.flock(fd, fcntl.LOCK_EX)+open(sys.argv[2], "w").close()+time.sleep(600)+' "$TREE_EVENTLOG" "$WORK/held" &+ HOLDER_PID=$!+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ [ -e "$WORK/held" ] && return 0+ sleep 1+ done+ return 1+}++# Wait until this boot's eventlog has the tree_op record of seq $1.+tree_op_measured()+{+ python3 - "$EVENTLOG" "$1" <<'PY'+import json+import sys+import time++seq = int(sys.argv[2])+for _ in range(600):+ with open(sys.argv[1], encoding="utf-8") as stream:+ for text in stream:+ try:+ record = json.loads(text)+ except ValueError:+ continue+ if record.get("type") == "tree_op" and \+ record.get("tree", {}).get("seq") == seq:+ sys.exit(0)+ time.sleep(0.1)+sys.exit(1)+PY+}++# The registry serves a copy, so that an artifact can go missing.+cp -R "$REGISTRY" "$SERVED"+tree_configure outcomes+tree_registry_start "$SERVED" "$WORK"++test_expect_success 'the record covers what t7101 to t7105 processed' '+ outcomes_agree 7 1 2 1 1 1 1 1 &&+ [ "$(tree_state_field head_seq)" = 7 ] &&+ [ "$(tree_state_field segment_base_seq)" = 0 ]+'++test_expect_success 'an applied, an unmatched and a module-absent operation get outcomes 1, 2 and 3' '+ tree_sync "$WORK/outcomes.json" &&+ [ "$(report_field selected <"$WORK/outcomes.json")" = 2 ] &&+ [ "$(report_field skipped <"$WORK/outcomes.json")" = 1 ] &&+ [ "$(report_field applied <"$WORK/outcomes.json")" = 2 ] &&+ [ "$(report_field module_skipped <"$WORK/outcomes.json")" = 1 ] &&+ [ "$(report_field last_seq <"$WORK/outcomes.json")" = 10 ] &&+ [ -e "$MATCH_PIN" ] &&+ [ ! -e "/run/shirudo/bpffs/upatches/$ABSENT" ] &&+ [ "$(cat "$TREE_DIR/status/$ABSENT")" = "skipped: module not loaded" ] &&+ outcomes_agree 10 1 2 3 &&+ [ "$(tree_state_field generation)" = 7 ] &&+ [ "$(tree_state_field head_seq)" = 10 ]+'++# A test body runs in a subshell, which could not hand the lock holder+# to the cleanup: stop the sync here and let the body look at what is left.+tree_configure stopped+STOPPED=no+if hold_tree_eventlog; then+ BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync \+ --report "$WORK/stopped.json" >/dev/null 2>&1 &+ SYNC_PID=$!+ if tree_op_measured 12; then+ STOPPED=yes+ fi+ kill -9 "$SYNC_PID" 2>/dev/null || true+ wait "$SYNC_PID" 2>/dev/null || true+fi+release_tree_eventlog++test_expect_success 'a sync killed after the register extend leaves the cursor and a pending operation' '+ [ "$STOPPED" = yes ] &&+ [ ! -e "$WORK/stopped.json" ] &&+ [ -e "$PENDING" ] &&+ [ -e "$SKIP_PIN" ] &&+ [ "$(tree_state_field last_seq)" = 10 ] &&+ [ "$(tree_state_field generation)" = 8 ] &&+ [ "$(tree_state_field head_seq)" = 12 ] &&+ [ "$(outcomes_last)" = "11 11 2" ]+'++test_expect_success 'the next sync completes it with one line for each seq, 2 for the unmatched one' '+ tree_sync "$WORK/recovered.json" &&+ [ "$(report_field selected <"$WORK/recovered.json")" = 0 ] &&+ [ "$(report_field skipped <"$WORK/recovered.json")" = 0 ] &&+ [ "$(report_field applied <"$WORK/recovered.json")" = 0 ] &&+ [ "$(report_field last_seq <"$WORK/recovered.json")" = 12 ] &&+ [ ! -e "$PENDING" ] &&+ [ -e "$SKIP_PIN" ] &&+ outcomes_agree 12 2 1 &&+ [ "$(tree_state_field last_seq)" = 12 ]+'++test_expect_success 'a sync that fails at a fetch leaves the publication it accepted on record' '+ tree_configure fetched &&+ mv "$SERVED/shirudo/tree-skip-unload" "$WORK/tree-skip-unload" &&+ ! BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync \+ --report "$WORK/failed.json" >/dev/null 2>"$WORK/failed.err" &&+ grep -q "phase=artifact_fetch_or_verify seq=13 " "$WORK/failed.err" &&+ [ ! -e "$WORK/failed.json" ] &&+ [ "$(tree_state_field generation)" = 9 ] &&+ [ "$(tree_state_field head_seq)" = 13 ] &&+ [ "$(tree_state_field last_seq)" = 12 ] &&+ [ -e "$SKIP_PIN" ] &&+ outcomes_agree 12+'++test_expect_success 'the next sync finishes that publication' '+ mv "$WORK/tree-skip-unload" "$SERVED/shirudo/tree-skip-unload" &&+ tree_sync "$WORK/finished.json" &&+ [ "$(report_field selected <"$WORK/finished.json")" = 1 ] &&+ [ "$(report_field applied <"$WORK/finished.json")" = 1 ] &&+ [ "$(report_field last_seq <"$WORK/finished.json")" = 13 ] &&+ [ ! -e "$SKIP_PIN" ] &&+ [ ! -e "$PENDING" ] &&+ outcomes_agree 13 1 &&+ [ "$(tree_state_field generation)" = 9 ] &&+ [ "$(tree_state_field head_seq)" = 13 ] &&+ [ "$(tree_state_field last_seq)" = 13 ]+'++test_donediff --git a/testing/proofs/cbmc/bpm-tree-recovery-model.c b/testing/proofs/cbmc/bpm-tree-recovery-model.cindex 93fca53f..c15749f8 100644--- a/testing/proofs/cbmc/bpm-tree-recovery-model.c+++ b/testing/proofs/cbmc/bpm-tree-recovery-model.c@@ -30,12 +30,17 @@ static void recovery_start(struct tree_state *actual, struct mstate *model)model->last_seq = have_state ? disk_state.last_seq : 0;model->manifest[0] = have_state ? disk_state.manifest_digest[0] : '\0';model->manifest[1] = '\0';- for (int i = 0; i < 32; i++)+ model->head_seq = have_state ? disk_state.head_seq : 0;+ model->base_seq = have_state ? disk_state.segment_base_seq : 0;+ for (int i = 0; i < 32; i++) {model->root[i] = have_state ?(__u8)disk_state.projection_root[i] : '0';+ model->hist[i] = disk_history[i];+ }}static void recovery_state_matches(const struct tree_state *actual,+ const __u8 *history,const struct mstate *model){bool tpm_root_set = !have_state ||@@ -51,10 +56,15 @@ static void recovery_state_matches(const struct tree_state *actual,__CPROVER_assert(actual->manifest_digest[0] == model->manifest[0] &&actual->manifest_digest[1] == model->manifest[1],"recovery keeps the manifest");+ __CPROVER_assert(actual->head_seq == model->head_seq &&+ actual->segment_base_seq == model->base_seq,+ "recovery keeps the recorded head and base");for (int i = 0; i < 32; i++) {__CPROVER_assert((__u8)actual->projection_root[i] ==model->root[i],"recovery records the expected root bytes");+ __CPROVER_assert(history[i] == model->hist[i],+ "recovery leaves the history root at the cursor");if (tpm_root_set)__CPROVER_assert((__u8)actual->projection_root_tpm[i] ==model->root[i],@@ -66,6 +76,7 @@ void harness(void){struct tree_state actual = {};struct mstate model = {};+ __u8 history[32];__u32 first_failure;bool model_ok;int ret;@@ -76,12 +87,13 @@ void harness(void)__CPROVER_assume(checked());any_replay_root();recovery_start(&actual, &model);+ memcpy(history, disk_history, sizeof(history));model_ok = recover(&model);- ret = tree_recover_pending(&fetched, &actual);+ ret = tree_recover_pending(&fetched, &actual, history);__CPROVER_assert(failed || (ret == 0) == model_ok,"recovery accepts the same pending state as the model");__CPROVER_assert(failed || n_got == n_want,"recovery makes every expected write");if (!failed && model_ok)- recovery_state_matches(&actual, &model);+ recovery_state_matches(&actual, history, &model);}diff --git a/testing/proofs/cbmc/bpm-tree-sync-model.c b/testing/proofs/cbmc/bpm-tree-sync-model.cindex 78b3c1b5..ab3f5649 100644--- a/testing/proofs/cbmc/bpm-tree-sync-model.c+++ b/testing/proofs/cbmc/bpm-tree-sync-model.c@@ -14,7 +14,10 @@* Strings are of one byte, as sync only compares them; hashes, hex and paths* are stubs the model does not depend on. The functions after the stubs* restate the Lean definitions: checked() is Checked, follows() Follows,- * recover() recover and run() run, with its loop.+ * recover() recover and run() run, with its loop. An outcome line carries+ * more here than in the Lean model: its code, 1 or 3 by what the install or+ * the pins say, and the history root, a fold the sync starts from the root+ * its record holds at the cursor.*//* As proof.h, before the system headers can include <ctype.h>. */@@ -38,9 +41,15 @@int tree_operation_validate(const struct tree_operation *op);#include "../../../builtin-bpm.c"-enum { W_PENDING, W_MEASURE, W_APPEND, W_STATE, W_UNLINK };+enum {+ W_PENDING, W_MEASURE, W_APPEND, W_STATE, W_UNLINK, W_OUTCOME,+ W_TRUNCATE,+};-/* A write and what it carries: the operation, seq, digest or root, state. */+/*+ * A write and what it carries: the operation, seq, digest or root, state,+ * and for an outcome line its code and the history root.+ */struct write {int kind;int op;@@ -49,9 +58,14 @@ struct write {__s64 generation;char manifest[2];char tree_id[2];+ __s64 head_seq;+ __s64 base_seq;+ int outcome;+ __u8 h[32];};-#define MAX_WRITES (4 + 5 * LEN)+/* The cut, recovery's append, lines, state and unlink, the record, the loop. */+#define MAX_WRITES (8 + 7 * LEN)static struct write want[MAX_WRITES];static int n_got, n_want;@@ -68,6 +82,10 @@ static struct tree_operation ops[LEN ? LEN : 1];static struct tree_publication fetched;static char fetched_manifest[2];static bool sel_match[LEN ? LEN : 1], sel_fail[LEN ? LEN : 1];+static __u8 disk_history[32];+static bool op_add[LEN ? LEN : 1], module_absent[LEN ? LEN : 1];+static bool pins_loaded;+static int installing = -1;static __s64 measure_seq;static __u8 measure_d[32];@@ -131,6 +149,13 @@ static void model_hash(const __u8 *a, const __u8 *b, __u8 *out)out[i] = (__u8)((a[i] * 3 + b[i] + 1) & 0xff);}+/* As model_hash(), and another function of the two, as the tag makes it. */+static void model_history(const __u8 *a, const __u8 *b, __u8 *out)+{+ for (int i = 0; i < 32; i++)+ out[i] = (__u8)((a[i] * 5 + b[i] + 7) & 0xff);+}+static void digest_of(const char *s, __u8 out[32]){memset(out, 0, 32);@@ -359,16 +384,57 @@ int tree_state_write(const struct tree_state *s)hex_decode(s->projection_root, w.d, 32);copy_short(w.manifest, s->manifest_digest);copy_short(w.tree_id, s->tree_id);+ w.head_seq = s->head_seq;+ w.base_seq = s->segment_base_seq;+ record(&w);+ return 0;+}++int tree_outcomes_resume(__s64 last_seq, __u8 history_root[32])+{+ struct write w = { .kind = W_TRUNCATE, .seq = last_seq };++ memset(history_root, 0, 32);+ if (fail_here())+ return -EBADMSG;+ record(&w);+ memcpy(history_root, disk_history, 32);+ return 0;+}++int chain_history_step(const __u8 prev[32], const __u8 operation_digest[32],+ __u8 out[32])+{+ model_history(prev, operation_digest, out);+ return fail_here() ? -EIO : 0;+}++int tree_outcome_append(__s64 seq, enum tree_outcome outcome,+ const __u8 projection_root[32],+ const __u8 history_root[32])+{+ struct write w = { .kind = W_OUTCOME, .seq = seq, .outcome = outcome };++ if (fail_here())+ return -EIO;+ memcpy(w.d, projection_root, 32);+ memcpy(w.h, history_root, 32);record(&w);return 0;}+bool upatch_loaded_pins(const char *name)+{+ return pins_loaded;+}+int tree_pending_write(const struct tree_operation *op){struct write w = { .kind = W_PENDING, .op = op_of(op) };if (fail_here())return -EIO;+ installing = w.op;record(&w);return 0;}@@ -455,13 +521,17 @@ void upatch_close(struct upatch *u){}+/* The operation pending.json names is the one sync installs. */int upatch_install(const char *path){int ret;- __CPROVER_assume(ret == 0 || ret == UPATCH_INSTALL_TARGET_MISSING ||- ret == 1 || ret == -EIO);- if (ret && ret != UPATCH_INSTALL_TARGET_MISSING)+ __CPROVER_assert(installing >= 0 && installing < LEN,+ "an install follows its pending record");+ if (installing >= 0 && installing < LEN && module_absent[installing])+ return UPATCH_INSTALL_TARGET_MISSING;+ __CPROVER_assume(ret == 0 || ret == 1 || ret == -EIO);+ if (ret)failed = true;return ret;}@@ -587,6 +657,10 @@ struct mstate {__s64 last_seq;__u8 root[32];char manifest[2];+ __s64 head_seq;+ __s64 base_seq;+ /* Not in state.json: the history root sync holds at last_seq. */+ __u8 hist[32];};static void want_write(int kind, int op, __s64 seq, const __u8 *d,@@ -610,9 +684,35 @@ static void want_write(int kind, int op, __s64 seq, const __u8 *d,want[index].manifest[1] = '\0';want[index].tree_id[0] = st->tree_id[0];want[index].tree_id[1] = '\0';+ want[index].head_seq = st->head_seq;+ want[index].base_seq = st->base_seq;}}+static void want_outcome(__s64 seq, int outcome, const __u8 *root,+ const __u8 *hist)+{+ int index;++ __CPROVER_assert(n_want < MAX_WRITES, "expected write log fits");+ index = n_want++;+ want[index].kind = W_OUTCOME;+ want[index].seq = seq;+ want[index].outcome = outcome;+ for (int i = 0; i < 32; i++)+ want[index].d[i] = root[i];+ for (int i = 0; i < 32; i++)+ want[index].h[i] = hist[i];+}++static bool same_history(const struct write *actual, int index)+{+ for (int i = 0; i < 32; i++)+ if (actual->h[i] != want[index].h[i])+ return false;+ return true;+}+static bool same_digest(const struct write *actual, int index){for (int i = 0; i < 32; i++)@@ -640,7 +740,15 @@ static bool same_write(const struct write *a, int index)a->manifest[0] == want[index].manifest[0] &&a->manifest[1] == want[index].manifest[1] &&a->tree_id[0] == want[index].tree_id[0] &&- a->tree_id[1] == want[index].tree_id[1];+ a->tree_id[1] == want[index].tree_id[1] &&+ a->head_seq == want[index].head_seq &&+ a->base_seq == want[index].base_seq;+ case W_OUTCOME:+ return a->seq == want[index].seq &&+ a->outcome == want[index].outcome &&+ same_digest(a, index) && same_history(a, index);+ case W_TRUNCATE:+ return a->seq == want[index].seq;default:return true;}@@ -674,6 +782,37 @@ static bool follows(const struct mstate *s)s->last_seq <= fetched.head_seq;}+/*+ * What recovery writes once the pending operation is applied and its line+ * is in the tree eventlog: a line for each operation the stopped sync passed+ * over, the operation's own, the state and the unlink.+ */+static void want_recovered(struct mstate *st, const struct tree_operation *o,+ const __u8 *d, const __u8 *next)+{+ int index = op_of(o);+ __u8 passed[32];++ for (int i = 0; i < fetched.n_operations; i++) {+ if (ops[i].seq >= o->seq)+ break;+ if (ops[i].seq <= st->last_seq)+ continue;+ digest_of(ops[i].operation_digest, passed);+ model_history(st->hist, passed, st->hist);+ want_outcome(ops[i].seq, TREE_OUTCOME_UNMATCHED, st->root,+ st->hist);+ }+ model_history(st->hist, d, st->hist);+ want_outcome(o->seq, index >= 0 && op_add[index] && !pins_loaded ?+ TREE_OUTCOME_MODULE_ABSENT : TREE_OUTCOME_APPLIED,+ next, st->hist);+ memcpy(st->root, next, 32);+ st->last_seq = o->seq;+ want_write(W_STATE, 0, 0, NULL, st);+ want_write(W_UNLINK, 0, 0, NULL, NULL);+}+/* false for a refusal before it writes anything. */static bool recover(struct mstate *st){@@ -702,10 +841,7 @@ static bool recover(struct mstate *st)if (replay_kind == 1)return false;if (replay_kind == 2 && !memcmp(replay_root, next, 32)) {- memcpy(st->root, next, 32);- st->last_seq = o->seq;- want_write(W_STATE, 0, 0, NULL, st);- want_write(W_UNLINK, 0, 0, NULL, NULL);+ want_recovered(st, o, d, next);return true;}if (replay_kind == 2 && memcmp(replay_root, st->root, 32))@@ -713,10 +849,7 @@ static bool recover(struct mstate *st)if (!measured)return true;want_write(W_APPEND, op_of(o), o->seq, next, NULL);- memcpy(st->root, next, 32);- st->last_seq = o->seq;- want_write(W_STATE, 0, 0, NULL, st);- want_write(W_UNLINK, 0, 0, NULL, NULL);+ want_recovered(st, o, d, next);return true;}@@ -734,26 +867,42 @@ static void run(void)st.root[i] = have_state ? (__u8)disk_state.projection_root[i] : '0';st.manifest[0] = have_state ? disk_state.manifest_digest[0] : '\0';st.manifest[1] = '\0';- if (!checked() || !follows(have_state ? &st : NULL) || !recover(&st))+ st.head_seq = have_state ? disk_state.head_seq : 0;+ st.base_seq = have_state ? disk_state.segment_base_seq : 0;+ memcpy(st.hist, disk_history, 32);+ if (!checked() || !follows(have_state ? &st : NULL))+ return;+ want_write(W_TRUNCATE, 0, st.last_seq, NULL, NULL);+ if (!recover(&st))return;+ st.generation = fetched.generation;+ copy_short(st.manifest, fetched_manifest);+ st.head_seq = fetched.head_seq;+ st.base_seq = fetched.base_seq;+ want_write(W_STATE, 0, 0, NULL, &st);for (int i = 0; i < fetched.n_operations; i++) {if (ops[i].seq <= st.last_seq)continue;+ digest_of(ops[i].operation_digest, d);if (!sel_match[i]) {+ model_history(st.hist, d, st.hist);+ want_outcome(ops[i].seq, TREE_OUTCOME_UNMATCHED,+ st.root, st.hist);st.last_seq = ops[i].seq;continue;}- digest_of(ops[i].operation_digest, d);want_write(W_PENDING, i, 0, NULL, NULL);want_write(W_MEASURE, i, ops[i].seq, d, NULL);model_hash(st.root, d, st.root);want_write(W_APPEND, i, ops[i].seq, st.root, NULL);+ model_history(st.hist, d, st.hist);+ want_outcome(ops[i].seq, op_add[i] && module_absent[i] ?+ TREE_OUTCOME_MODULE_ABSENT : TREE_OUTCOME_APPLIED,+ st.root, st.hist);st.last_seq = ops[i].seq;want_write(W_STATE, 0, 0, NULL, &st);want_write(W_UNLINK, 0, 0, NULL, NULL);}- st.generation = fetched.generation;- copy_short(st.manifest, fetched_manifest);want_write(W_STATE, 0, 0, NULL, &st);}@@ -787,7 +936,7 @@ static void any_publication(void)fetched = pub;for (int i = 0; i < LEN; i++) {struct tree_operation *o = &ops[i];- bool add, match, fail;+ bool add, match, fail, absent;__s64 seq;__CPROVER_assume(seq > 0 && (!i || seq - 1 == ops[i - 1].seq));@@ -801,6 +950,8 @@ static void any_publication(void)any_name(o->artifact.payload_sha256, false);sel_match[i] = match;sel_fail[i] = fail;+ op_add[i] = add;+ module_absent[i] = absent;}any_name(fetched_manifest, false);}@@ -811,22 +962,26 @@ static void any_publication(void)*/static void any_node(void){- bool state_there, pending_there, op_measured;- __s64 generation, last_seq, seq;+ bool state_there, pending_there, op_measured, loaded;+ __s64 generation, last_seq, seq, head_seq, base_seq;char tree, manifest, id, digest;int replay;have_state = state_there;have_pending = pending_there;measured = op_measured;+ pins_loaded = loaded;disk_state.tree_id[0] = state_there ? tree : '\0';disk_state.manifest_digest[0] = state_there ? manifest : '\0';disk_state.generation = state_there ? generation : 0;disk_state.last_seq = state_there ? last_seq : 0;+ disk_state.head_seq = state_there ? head_seq : 0;+ disk_state.segment_base_seq = state_there ? base_seq : 0;for (int i = 0; i < 32; i++) {- __u8 b;+ __u8 b, h;disk_state.projection_root[i] = state_there ? (char)b : '\0';+ disk_history[i] = h;}__CPROVER_assume(seq > 0 && id && digest);disk_pending.seq = pending_there ? seq : 0;diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.listindex 4df5555f..b3536ee3 100644--- a/testing/proofs/cbmc/proofs.list+++ b/testing/proofs/cbmc/proofs.list@@ -26,10 +26,10 @@ upatch-rodata -I ../../../vendor/libbpf/include/uapi -I ../../../vendor/libbpfstring-number-model --unwind 6measured-fold-model --unwind 7bpm-tree-follows --unwind 4-bpm-tree-sync-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-1-bpm-tree-sync-application --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2-bpm-tree-sync-pending --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2-bpm-tree-recovery-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,any_node.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66,recovery_start.0:33,recovery_state_matches.0:33 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-2+bpm-tree-sync-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-1+bpm-tree-sync-application --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2+bpm-tree-sync-pending --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2+bpm-tree-recovery-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66,recovery_start.0:33,recovery_state_matches.0:33 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-2bpm-tree-signers --unwind 8bpm-upatch-member --unwind 30 LEN=0-18tpm-reader --unwind 1diff --git a/testing/proofs/lean4/Shirudo/TreeSync.lean b/testing/proofs/lean4/Shirudo/TreeSync.leanindex 88b524a6..2c62ddc1 100644--- a/testing/proofs/lean4/Shirudo/TreeSync.lean+++ b/testing/proofs/lean4/Shirudo/TreeSync.lean@@ -7,15 +7,18 @@ import Shirudo.Chain`bpm tree sync`, `cmd_bpm_tree_sync()` of builtin-bpm.c. It reads thenode's state, fetches a signed tree publication, refuses one that`tree_parse()`, `tree_publication_check()`, `tree_operation_validate()` or-`tree_publication_follows()` refuses, and runs `tree_recover_pending()`.-Then, for each operation past the cursor that its selector matches, it-writes `pending.json`, installs the upatch, extends the register and records-the `tree_op` event, appends a line to the tree eventlog, writes the state-with the new cursor and projection root and unlinks `pending.json`; one the-selector does not match moves the cursor. At the end it writes the state-with the publication's generation and manifest digest.--The model follows the C step by step: a node is its four files, a sync the+`tree_publication_follows()` refuses, cuts the outcomes record to the cursor,+runs `tree_recover_pending()` and writes the state with the publication's+generation, manifest digest and head. Then, for each operation past the+cursor that its selector matches, it writes `pending.json`, installs the+upatch, extends the register and records the `tree_op` event, appends a line+to the tree eventlog and one to the outcomes record, writes the state with+the new cursor and projection root and unlinks `pending.json`; one the+selector does not match gets its outcome line and moves the cursor. At the+end it writes the state again, for the cursor a run of unmatched operations+moved.++The model follows the C step by step: a node is its five files, a sync thelist of writes it makes, each atomic, and a crash or a refusal after some ofthem the writes before it. Root picks every input: any publication thenode's key signed, in any manifest a registry wraps it in, the selector's@@ -39,22 +42,31 @@ between appending a line and writing the state (`state_is_fold`), whichrecovery closes (`recover_settles`). Every applied operation is one of asigned publication of the node's tree (`applied_signed`), and the one everysuch publication has at its number when the signer never gives a number two-operations (`applied_consistent`).+operations (`applied_consistent`). The outcomes record has a line for every+operation from 1 to the cursor, in order (`outcomes_cover`), no line at or+below the cursor ever changes (`outcomes_fixed`), and the cursor never passes+the head of the recorded publication (`lastSeq_le_head`).The generation rests on the generation check of `Follows`, on `tree_parse()`-refusing a negative generation, as a first sync writes generation 0 before-its last write, and on a manifest digest naming one publication. The cursor+refusing a negative generation, and on a manifest digest naming one+publication. The cursorand the order rest on the loop's own cursor check and recovery's; that eachoperation is applied once rests on recovery's comparison of the replayedroot and on its look at this boot's records, with the hash collision-resistant. The cursor check and the parent check of `Follows` and the rest-of what `tree_parse()` and `tree_publication_check()` require are not needed-by any of these theorems. `Assumptions` states what the C cannot show.+resistant. The outcomes record rests on the order of the writes, a line+before the state that covers it, on the cut at the start of a sync, on+recovery writing the lines of the operations the stopped sync passed over,+and on `tree_publication_check()` numbering the operations without a gap;+the head on the state written at acceptance and on the cursor check of+`Follows`. The parent check of `Follows` is not needed by any of these+theorems. `Assumptions` states what the C cannot show.The model also assumes what review of the C shows: only sync writes thesefiles, which the seal ensures; a write is whole or absent, as`seal_write_file()` renames and `append_line()` drops a line it did not-finish; syncs run one at a time under the BPM lock; the unlink of+finish, and `tree_outcome_append()` appends the same way, with every reader+of the record skipping a last line without its newline; syncs run one at a+time under the BPM lock; the unlink of`pending.json`, whose result sync ignores, succeeds; and an extend with itseventlog record is one write, as a stop between them leaves the registerahead of the log. Installing or removing the upatch writes nothing the model@@ -95,14 +107,16 @@ structure Pub (T M I D : Type) whereheadSeq : Int/-- `struct tree_state`: `root` is `projection_root`, which sync writes into-`projection_root_tpm` too, and `manifest` is `none` for an empty-`manifest_digest`. -/+`projection_root_tpm` too, `manifest` is `none` for an empty+`manifest_digest`, and `headSeq` is `head_seq`, the head of the recorded+publication. `segment_base_seq` is 0 with `Checked` and is left out. -/structure State (T M D : Type) wheretreeId : Tgeneration : IntlastSeq : Introot : Dmanifest : Option M+ headSeq : Int/-- A line `tree_event_append()` adds to the tree eventlog. -/structure Line (D : Type) where@@ -110,25 +124,40 @@ structure Line (D : Type) wheredigest : Droot : D+/-- A line `tree_outcome_append()` adds to the outcomes record: the+operation's number, whether its selector matched, and the projection root+after it. `matched` is outcome 1 or 3, which the install's answer tells+apart and no write of the model depends on, and its absence outcome 2. The+line's history root is left out: it is a fold over the operations' digests+alone, as `Shirudo.Chain.history_ignores_outcomes` shows. -/+structure OLine (D : Type) where+ seq : Int+ matched : Bool+ root : D+/-- What sync reads and writes on the node: `state.json`, `pending.json`, the-tree eventlog, oldest line first, and the `tree_op` records of this boot's-eventlog, the ones `eventlog_tree_op_measured()` reads. `none` and `[]` are-files that do not exist. -/+tree eventlog, oldest line first, the `tree_op` records of this boot's+eventlog, the ones `eventlog_tree_op_measured()` reads, and the outcomes+record, oldest line first. `none` and `[]` are files that do not exist. -/structure Node (T M I D : Type) wherestate : Option (State T M D)pending : Option (Op I D)log : List (Line D)measured : List (Int × D)+ outcomes : List (OLine D)/-- The writes of a sync, each atomic: `tree_pending_write()`, the extendand eventlog record of `tree_measure_operation()`, `tree_event_append()`,-`tree_state_write()` and the unlink of `pending.json`. -/+`tree_outcome_append()`, `tree_state_write()`, the unlink of `pending.json`+and `tree_outcomes_resume()`, which keeps the first `k` lines. -/inductive Write (T M I D : Type) where| pending (o : Op I D)| measure (seq : Int) (d : D)| append (l : Line D)+ | outcome (l : OLine D)| state (s : State T M D)| unlink+ | truncate (k : Nat)variable {T M I D : Type}@@ -137,15 +166,23 @@ def Write.apply : Write T M I D → Node T M I D → Node T M I D| .pending o, n => { n with pending := some o }| .measure s d, n => { n with measured := n.measured ++ [(s, d)] }| .append l, n => { n with log := n.log ++ [l] }+ | .outcome l, n => { n with outcomes := n.outcomes ++ [l] }| .state s, n => { n with state := some s }| .unlink, n => { n with pending := none }+ | .truncate k, n => { n with outcomes := n.outcomes.take k }/-- The node after the writes `ws`, in order. -/def applyAll (ws : List (Write T M I D)) (n : Node T M I D) : Node T M I D :=ws.foldl (fun n w => w.apply n) n/-- The node before its first sync. -/-def Node.empty : Node T M I D := ⟨none, none, [], []⟩+def Node.empty : Node T M I D := ⟨none, none, [], [], []⟩++/-- The cursor the run starts from: the state's, 0 without one. -/+def cursor (n : Node T M I D) : Int :=+ match n.state with+ | some s => s.lastSeq+ | none => 0/-! ### The checks before anything is applied -/@@ -293,6 +330,26 @@ theorem along_append {P : Node T M I D → Prop}simp only [Along] at h ⊢exact ⟨h.1, h.2.1, ih h.2.2 h'⟩+theorem along_nil {P : Node T M I D → Prop}+ {R : Node T M I D → Node T M I D → Prop} {n : Node T M I D} (h : P n) :+ Along P R [] n := by+ simp only [Along]+ exact h++theorem along_cons {P : Node T M I D → Prop}+ {R : Node T M I D → Node T M I D → Prop} {w : Write T M I D}+ {ws : List (Write T M I D)} {n : Node T M I D} (h0 : P n)+ (hR : R n (w.apply n)) (h : Along P R ws (w.apply n)) :+ Along P R (w :: ws) n := by+ simp only [Along]+ exact ⟨h0, hR, h⟩++theorem along_one {P : Node T M I D → Prop}+ {R : Node T M I D → Node T M I D → Prop} {w : Write T M I D}+ {n : Node T M I D} (h0 : P n) (hR : R n (w.apply n)) (h1 : P (w.apply n)) :+ Along P R [w] n :=+ along_cons h0 hR (along_nil h1)+/-! ### The tree eventlog -/section replay@@ -411,16 +468,41 @@ theorem replay_ok {log : List (Line D)} (h : Replays H init log)end replay+/-! ### The lines of the outcomes record -/++/-- `tree_outcomes_passed()`: the lines of the operations between the cursor+`lo` and the pending operation's number `hi`, which the sync that stopped+passed over, each with the projection root it left where it was. -/+def passed (lo hi : Int) (root : D) : List (Op I D) → List (OLine D)+ | [] => []+ | o :: os =>+ if hi ≤ o.seq then []+ else if o.seq ≤ lo then passed lo hi root os+ else ⟨o.seq, false, root⟩ :: passed lo hi root os++/-- The lines `tree_recover_pending()` appends once the pending operation+`p` is applied, from the state `st` it starts from: those of the operations+passed over, then the operation's own. -/+def recLines (H : D → D → D) (pub : Pub T M I D) (st : State T M D)+ (p : Op I D) : List (OLine D) :=+ passed st.lastSeq p.seq st.root pub.ops ++ [⟨p.seq, true, H st.root p.digest⟩]++/-- How recovery completes an applied operation: its lines, the state and+the unlink of `pending.json`. -/+def complete (ls : List (OLine D)) (st : State T M D) : List (Write T M I D) :=+ ls.map Write.outcome ++ [.state st, .unlink]+section syncvariable [DecidableEq T] [DecidableEq M] [DecidableEq I] [DecidableEq D]variable (H : D → D → D) (init : D)/-- The state `cmd_bpm_tree_sync()` starts from when the node has none. -/-def fresh (t : T) : State T M D := ⟨t, 0, 0, init, none⟩+def fresh (t : T) : State T M D := ⟨t, 0, 0, init, none, 0⟩/-- `tree_recover_pending()`: the writes it makes and the state the loopgoes on from, or `none` for a refusal before it writes anything. Every-refusal after a write stops the run as a crash there does. -/+refusal after a write stops the run as a crash there does. An operation it+finds applied gets its outcome lines before the state that covers them. -/def recover (n : Node T M I D) (pub : Pub T M I D) (st : State T M D) :Option (List (Write T M I D) × State T M D) :=match n.pending with@@ -436,20 +518,22 @@ def recover (n : Node T M I D) (pub : Pub T M I D) (st : State T M D) :let st' := { st with root := next, lastSeq := o.seq }let unapplied :=if (o.seq, o.digest) ∈ n.measured then- some ([.append ⟨o.seq, o.digest, next⟩, .state st', .unlink], st')+ some (.append ⟨o.seq, o.digest, next⟩ ::+ complete (recLines H pub st p) st', st')else some ([], st)match replay H init n.log with| .missing => unapplied| .bad => none| .ok r =>- if r = next then some ([.state st', .unlink], st')+ if r = next then some (complete (recLines H pub st p) st', st')else if r = st.root then unappliedelse none/-- The loop of `cmd_bpm_tree_sync()` over the operations, with `sel` what`tree_selector_matches()` says of each: the writes and the state it endswith. An operation at or below the cursor is passed over, one the selector-does not match moves the cursor, and one it does is applied. -/+does not match gets its outcome line and moves the cursor in memory, and one+it does is applied, its outcome line written before its state. -/def loop (sel : Op I D → Bool) :State T M D → List (Op I D) → List (Write T M I D) × State T M D| st, [] => ([], st)@@ -459,22 +543,33 @@ def loop (sel : Op I D → Bool) :let st' := { st with root := H st.root o.digest, lastSeq := o.seq }let r := loop sel st' os([.pending o, .measure o.seq o.digest,- .append ⟨o.seq, o.digest, H st.root o.digest⟩, .state st',+ .append ⟨o.seq, o.digest, H st.root o.digest⟩,+ .outcome ⟨o.seq, true, H st.root o.digest⟩, .state st',.unlink] ++ r.1,r.2)- else loop sel { st with lastSeq := o.seq } os+ else+ let r := loop sel { st with lastSeq := o.seq } os+ ([.outcome ⟨o.seq, false, st.root⟩] ++ r.1, r.2)/-- One `bpm tree sync` of the publication `pub`, fetched with the manifest-digest `m`, run to its end: the writes it makes, in order. -/+digest `m`, run to its end: the writes it makes, in order. A publication it+accepts has the outcomes record cut to the cursor first, and is recorded+with its head once recovery is done and before the loop: `acc` is the state+`cmd_bpm_tree_sync()` writes at acceptance. The check that the record covers+the cursor is not a branch here: `outcomes_cover` shows that no node a+history of syncs leaves fails it. -/def run (n : Node T M I D) (pub : Pub T M I D) (m : M) (sel : Op I D → Bool) :List (Write T M I D) :=if Checked pub ∧ Follows pub n.state m then- match recover H init n pub (n.state.getD (fresh init pub.treeId)) with- | none => []- | some (ws, st) =>- let r := loop H sel st pub.ops- let last := { r.2 with generation := pub.generation, manifest := some m }- ws ++ r.1 ++ [.state last]+ .truncate (cursor n).toNat ::+ match recover H init n pub (n.state.getD (fresh init pub.treeId)) with+ | none => []+ | some (ws, st) =>+ let acc := { st with generation := pub.generation, manifest := some m,+ headSeq := pub.headSeq }+ let r := loop H sel acc pub.ops+ let last := { r.2 with generation := pub.generation, manifest := some m }+ ws ++ [.state acc] ++ r.1 ++ [.state last]else []/-- What can happen to the node between two moments: a sync of a@@ -500,12 +595,6 @@ end sync/-! ### What every reachable node keeps -/-/-- The cursor the run starts from: the state's, 0 without one. -/-def cursor (n : Node T M I D) : Int :=- match n.state with- | some s => s.lastSeq- | none => 0-/-- The `(seq, digest)` of each line, as a `tree_op` record holds them. -/def events (log : List (Line D)) : List (Int × D) :=log.map fun l => (l.seq, l.digest)@@ -557,6 +646,40 @@ theorem Mono.of_state {n n' : Node T M I D} (hs : n'.state = n.state)⟨hl, fun s h => ⟨s, hs.trans h, rfl, Int.le_refl _, Int.le_refl _,fun _ => Or.inr rfl⟩⟩+/-- Two nodes that differ in the outcomes record at most, which nothing+above reads. -/+structure Same (n n' : Node T M I D) : Prop where+ state : n'.state = n.state+ pending : n'.pending = n.pending+ log : n'.log = n.log+ measured : n'.measured = n.measured++theorem cursor_of_state {n n' : Node T M I D} (hs : n'.state = n.state) :+ cursor n' = cursor n := by+ unfold cursor+ rw [hs]++theorem Mono.of_same {n n' : Node T M I D} (h : Same n n') : Mono n n' :=+ Mono.of_state h.state ⟨[], by rw [h.log, List.append_nil]⟩++/-- Outcome lines change the outcomes record alone. -/+theorem same_outcomes : ∀ (ls : List (OLine D)) (n : Node T M I D),+ Same n (applyAll (ls.map Write.outcome) n)+ | [], _ => ⟨rfl, rfl, rfl, rfl⟩+ | l :: ls, n =>+ have h := same_outcomes ls ((Write.outcome l).apply n)+ ⟨h.state, h.pending, h.log, h.measured⟩++/-- Completing an operation leaves the tree eventlog and this boot's+records as they were. -/+theorem complete_core (ls : List (OLine D)) (s : State T M D)+ (n : Node T M I D) :+ (applyAll (complete ls s) n).log = n.log ∧+ (applyAll (complete ls s) n).measured = n.measured := by+ unfold complete+ rw [applyAll_append]+ exact ⟨(same_outcomes ls n).log, (same_outcomes ls n).measured⟩+section invvariable [DecidableEq D] (H : D → D → D) (init : D)@@ -644,6 +767,75 @@ theorem Inv.empty (Signed : Pub T M I D → M → Prop) :end inv+/-! ### The outcomes record changes nothing above -/++theorem rootAt_of_state {init : D} {n n' : Node T M I D}+ (hs : n'.state = n.state) : rootAt init n' = rootAt init n := by+ unfold rootAt+ rw [hs]++theorem Clean.of_same [DecidableEq D] {H : D → D → D} {init : D}+ {n n' : Node T M I D} (hs : Same n n') (h : Clean H init n) :+ Clean H init n' := by+ unfold Clean at h ⊢+ rw [rootAt_of_state hs.state, hs.log, cursor_of_state hs.state]+ exact h++theorem clean_eq [DecidableEq D] {H : D → D → D} {init : D}+ {n n' : Node T M I D} (hs : Same n n') :+ Clean H init n' = Clean H init n := by+ unfold Clean+ rw [rootAt_of_state hs.state, hs.log, cursor_of_state hs.state]++theorem Window.of_same [DecidableEq D] {H : D → D → D} {init : D}+ {n n' : Node T M I D} (hs : Same n n') (h : Window H init n) :+ Window H init n' := by+ unfold Window at h ⊢+ rw [clean_eq hs, hs.pending, hs.log, hs.measured, cursor_of_state hs.state,+ rootAt_of_state hs.state]+ exact h++theorem Inv.of_same [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} {n n' : Node T M I D} (hs : Same n n')+ (h : Inv H init Signed n) : Inv H init Signed n' where+ replays := by rw [hs.log]; exact h.replays+ cursor_nonneg := by rw [cursor_of_state hs.state]; exact h.cursor_nonneg+ bound := by rw [hs.state]; exact h.bound+ applied := by rw [hs.state, hs.log]; exact h.applied+ stateless := by rw [hs.state, hs.log, hs.pending]; exact h.stateless+ window := Window.of_same hs h.window++theorem LoopRel.of_same [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} {pub : Pub T M I D} {m : M}+ {n n' : Node T M I D} {st : State T M D}+ (h : LoopRel H init Signed pub m n st) (hs : Same n n') :+ LoopRel H init Signed pub m n' st where+ replays := by rw [hs.log]; exact h.replays+ cursor_nonneg := by rw [cursor_of_state hs.state]; exact h.cursor_nonneg+ bound := by rw [hs.state]; exact h.bound+ applied := by rw [hs.state, hs.log]; exact h.applied+ clean := Clean.of_same hs h.clean+ suffix := by rw [hs.log, hs.measured]; exact h.suffix+ root := by rw [rootAt_of_state hs.state]; exact h.root+ le := by rw [cursor_of_state hs.state]; exact h.le+ agree := by rw [hs.state]; exact h.agree+ nolog := by rw [hs.state, hs.log]; exact h.nolog+ tree := h.tree+ signed := h.signed+ gen := h.gen+ stBound := h.stBound++/-- Outcome lines, stopped after any of them. -/+theorem along_outcomes [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} :+ ∀ (ls : List (OLine D)) (n : Node T M I D), Inv H init Signed n →+ Along (Inv H init Signed) Mono (ls.map Write.outcome) n+ | [], _, hinv => along_nil hinv+ | l :: ls, n, hinv =>+ have hsm : Same n ((Write.outcome l).apply n) := ⟨rfl, rfl, rfl, rfl⟩+ along_cons hinv (Mono.of_same hsm)+ (along_outcomes ls ((Write.outcome l).apply n) (Inv.of_same hsm hinv))+/-! ### A sync keeps the invariant and goes forward -/section loop@@ -672,16 +864,18 @@ theorem commit {Signed : Pub T M I D → M → Prop}∃ p, Signed p m' ∧ p.generation = st.generation) :Along (Inv H init Signed) Mono[.state ⟨st.treeId, st.generation, o.seq, H st.root o.digest,- st.manifest⟩,+ st.manifest, st.headSeq⟩,.unlink] n ∧LoopRel H init Signed pub m(applyAll [.state ⟨st.treeId, st.generation, o.seq, H st.root o.digest,- st.manifest⟩, .unlink] n)- ⟨st.treeId, st.generation, o.seq, H st.root o.digest, st.manifest⟩ := by+ st.manifest, st.headSeq⟩, .unlink] n)+ ⟨st.treeId, st.generation, o.seq, H st.root o.digest, st.manifest,+ st.headSeq⟩ := bysimp only [Along, applyAll, List.foldl, Write.apply]have hcur0 := hinv.cursor_nonneghave hclean : ∀ q, Clean H init (⟨some ⟨st.treeId, st.generation, o.seq,- H st.root o.digest, st.manifest⟩, q, n.log, n.measured⟩ :+ H st.root o.digest, st.manifest, st.headSeq⟩, q, n.log, n.measured,+ n.outcomes⟩ :Node T M I D) := byintro qrefine ⟨?_, ?_⟩@@ -694,7 +888,8 @@ theorem commit {Signed : Pub T M I D → M → Prop}· have := hbelow l hl; omega· simp only [List.mem_singleton] at hl; subst hl; exact Int.le_refl _have hmono' : ∀ q, Mono n (⟨some ⟨st.treeId, st.generation, o.seq,- H st.root o.digest, st.manifest⟩, q, n.log, n.measured⟩ :+ H st.root o.digest, st.manifest, st.headSeq⟩, q, n.log, n.measured,+ n.outcomes⟩ :Node T M I D) := byintro qrefine ⟨⟨[], by simp⟩, fun s hs =>@@ -705,7 +900,8 @@ theorem commit {Signed : Pub T M I D → M → Prop}omega· exact Or.inr (hagree s hs).2.2.symmhave hinv' : ∀ q, Inv H init Signed (⟨some ⟨st.treeId, st.generation, o.seq,- H st.root o.digest, st.manifest⟩, q, n.log, n.measured⟩ :+ H st.root o.digest, st.manifest, st.headSeq⟩, q, n.log, n.measured,+ n.outcomes⟩ :Node T M I D) := byintro qrefine ⟨hinv.replays, by show 0 ≤ o.seq; omega, ?_, ?_, by simp,@@ -726,6 +922,81 @@ theorem commit {Signed : Pub T M I D → M → Prop}simp only [Option.some.injEq] at hs; subst hs; exact ⟨rfl, rfl, rfl⟩,by simp, htree, hsigned, hgen, hstb⟩+/-- `commit` from a node that differs from the one its facts are stated of+in the outcomes record alone: the operation's outcome line goes in between+its tree eventlog line and its state. -/+theorem commit' {Signed : Pub T M I D → M → Prop}+ {pub : Pub T M I D} {m : M}+ {n0 n : Node T M I D} {st : State T M D} {o : Op I D} {L0 : List (Line D)}+ (hs : Same n0 n) (hinv : Inv H init Signed n0)+ (hlog : n0.log = L0 ++ [⟨o.seq, o.digest, H st.root o.digest⟩])+ (hroot : st.root = rootOf H init L0) (hbelow : ∀ l ∈ L0, l.seq ≤ st.lastSeq)+ (hgt : st.lastSeq < o.seq) (hsuf : Suffix n0.log n0.measured)+ (happ : ∀ l ∈ n0.log, ∃ p m, Signed p m ∧ p.treeId = st.treeId ∧+ ∃ o' ∈ p.ops, o'.seq = l.seq ∧ o'.digest = l.digest)+ (hle : cursor n0 ≤ st.lastSeq)+ (hagree : ∀ s, n0.state = some s →+ s.treeId = st.treeId ∧ s.generation = st.generation ∧+ s.manifest = st.manifest)+ (htree : st.treeId = pub.treeId) (hsigned : Signed pub m)+ (hgen : st.generation ≤ pub.generation ∧+ (pub.generation = st.generation →+ st.manifest = none ∨ st.manifest = some m))+ (hstb : ∀ m', st.manifest = some m' →+ ∃ p, Signed p m' ∧ p.generation = st.generation) :+ Along (Inv H init Signed) Mono+ [.state ⟨st.treeId, st.generation, o.seq, H st.root o.digest,+ st.manifest, st.headSeq⟩,+ .unlink] n ∧+ LoopRel H init Signed pub m+ (applyAll [.state ⟨st.treeId, st.generation, o.seq, H st.root o.digest,+ st.manifest, st.headSeq⟩, .unlink] n)+ ⟨st.treeId, st.generation, o.seq, H st.root o.digest, st.manifest,+ st.headSeq⟩ :=+ commit H init (Inv.of_same hs hinv) (hs.log.trans hlog) hroot hbelow hgt+ (by rw [hs.log, hs.measured]; exact hsuf)+ (by rw [hs.log]; exact happ)+ (by rw [cursor_of_state hs.state]; exact hle)+ (by rw [hs.state]; exact hagree)+ htree hsigned hgen hstb++/-- `commit` after the outcome lines `ls`: how recovery completes an+operation, stopped after any of its writes. -/+theorem complete_inv {Signed : Pub T M I D → M → Prop}+ {pub : Pub T M I D} {m : M}+ {n : Node T M I D} {st : State T M D} {o : Op I D} {L0 : List (Line D)}+ (ls : List (OLine D)) (hinv : Inv H init Signed n)+ (hlog : n.log = L0 ++ [⟨o.seq, o.digest, H st.root o.digest⟩])+ (hroot : st.root = rootOf H init L0) (hbelow : ∀ l ∈ L0, l.seq ≤ st.lastSeq)+ (hgt : st.lastSeq < o.seq) (hsuf : Suffix n.log n.measured)+ (happ : ∀ l ∈ n.log, ∃ p m, Signed p m ∧ p.treeId = st.treeId ∧+ ∃ o' ∈ p.ops, o'.seq = l.seq ∧ o'.digest = l.digest)+ (hle : cursor n ≤ st.lastSeq)+ (hagree : ∀ s, n.state = some s →+ s.treeId = st.treeId ∧ s.generation = st.generation ∧+ s.manifest = st.manifest)+ (htree : st.treeId = pub.treeId) (hsigned : Signed pub m)+ (hgen : st.generation ≤ pub.generation ∧+ (pub.generation = st.generation →+ st.manifest = none ∨ st.manifest = some m))+ (hstb : ∀ m', st.manifest = some m' →+ ∃ p, Signed p m' ∧ p.generation = st.generation) :+ Along (Inv H init Signed) Mono+ (complete ls ⟨st.treeId, st.generation, o.seq, H st.root o.digest,+ st.manifest, st.headSeq⟩) n ∧+ LoopRel H init Signed pub m+ (applyAll (complete ls ⟨st.treeId, st.generation, o.seq,+ H st.root o.digest, st.manifest, st.headSeq⟩) n)+ ⟨st.treeId, st.generation, o.seq, H st.root o.digest, st.manifest,+ st.headSeq⟩ := by+ have hlo := along_outcomes (Signed := Signed) ls n hinv+ obtain ⟨hca, hcr⟩ := commit' H init (pub := pub) (same_outcomes ls n) hinv+ hlog hroot hbelow hgt hsuf happ hle hagree htree hsigned hgen hstb+ unfold complete+ refine ⟨along_append hlo hca, ?_⟩+ rw [applyAll_append]+ exact hcr+/-- One operation the loop applies, stopped after any of its writes. -/theorem loop_apply {Signed : Pub T M I D → M → Prop}{pub : Pub T M I D} {m : M}@@ -735,11 +1006,13 @@ theorem loop_apply {Signed : Pub T M I D → M → Prop}Along (Inv H init Signed) Mono[.pending o, .measure o.seq o.digest,.append ⟨o.seq, o.digest, H st.root o.digest⟩,+ .outcome ⟨o.seq, true, H st.root o.digest⟩,.state { st with root := H st.root o.digest, lastSeq := o.seq },.unlink] n ∧LoopRel H init Signed pub m(applyAll [.pending o, .measure o.seq o.digest,.append ⟨o.seq, o.digest, H st.root o.digest⟩,+ .outcome ⟨o.seq, true, H st.root o.digest⟩,.state { st with root := H st.root o.digest, lastSeq := o.seq },.unlink] n){ st with root := H st.root o.digest, lastSeq := o.seq } := by@@ -776,17 +1049,18 @@ theorem loop_apply {Signed : Pub T M I D → M → Prop}⟨hrep, hcur0, hbound, happ, fun hs => by simp [hnolog hs],Or.inl ⟨⟨hroot, hbelow⟩, L1, L2, hlog, hmeas⟩⟩have hinv1 :- Inv H init Signed (⟨n.state, some o, n.log, n.measured⟩ : Node T M I D) :=+ Inv H init Signed+ (⟨n.state, some o, n.log, n.measured, n.outcomes⟩ : Node T M I D) :=⟨hrep, hcur0, hbound, happ, fun hs => by simp [hnolog hs],Or.inl ⟨⟨hroot, hbelow⟩, L1, L2, hlog, hmeas⟩⟩have hinv2 : Inv H init Signed (⟨n.state, some o, n.log,- n.measured ++ [(o.seq, o.digest)]⟩ : Node T M I D) :=+ n.measured ++ [(o.seq, o.digest)], n.outcomes⟩ : Node T M I D) :=⟨hrep, hcur0, hbound, happ, fun hs => by simp [hnolog hs],Or.inr (Or.inl ⟨o, rfl, hlt, ⟨hroot, hbelow⟩, L1, L2, hlog,by rw [hmeas]⟩)⟩have hinv3 : Inv H init Signed (⟨n.state, some o,n.log ++ [⟨o.seq, o.digest, H st.root o.digest⟩],- n.measured ++ [(o.seq, o.digest)]⟩ : Node T M I D) := by+ n.measured ++ [(o.seq, o.digest)], n.outcomes⟩ : Node T M I D) := byrefine ⟨hrep3, hcur0, hbound, fun s hs l hl => ?_, fun hs l hl => ?_,Or.inr (Or.inr ⟨o, n.log, rfl, hlt, by rw [hnext], hroot, hbelow, hsuf3⟩)⟩· obtain ⟨p, m', h1, h2, h3⟩ := happ' l hl@@ -795,16 +1069,25 @@ theorem loop_apply {Signed : Pub T M I D → M → Prop}simp only [List.nil_append, List.mem_singleton] at hlsubst hlexact ⟨o, rfl, rfl, rfl⟩- obtain ⟨hc, hr⟩ := commit H init (pub := pub) hinv3 rfl (hst.trans hroot)+ have hsm : Same (⟨n.state, some o,+ n.log ++ [⟨o.seq, o.digest, H st.root o.digest⟩],+ n.measured ++ [(o.seq, o.digest)], n.outcomes⟩ : Node T M I D)+ ⟨n.state, some o, n.log ++ [⟨o.seq, o.digest, H st.root o.digest⟩],+ n.measured ++ [(o.seq, o.digest)],+ n.outcomes ++ [⟨o.seq, true, H st.root o.digest⟩]⟩ :=+ ⟨rfl, rfl, rfl, rfl⟩+ obtain ⟨hc, hr⟩ := commit' H init (pub := pub) hsm hinv3 rfl+ (hst.trans hroot)(fun l hl => by have := hbelow l hl; omega) hgt hsuf3 happ' hle hagreehtree hsignedhgen hstbsimp only [Along, applyAll, List.foldl, Write.apply] at hc hr ⊢exact ⟨⟨hinvn, Mono.of_state rfl ⟨[], by simp⟩, hinv1,Mono.of_state rfl ⟨[], by simp⟩,- hinv2, Mono.of_state rfl ⟨_, rfl⟩, hc⟩, hr⟩+ hinv2, Mono.of_state rfl ⟨_, rfl⟩, hinv3, Mono.of_same hsm, hc⟩, hr⟩-/-- An operation the selector does not match moves the cursor in memory. -/+/-- An operation the selector does not match moves the cursor in memory;+its outcome line is nothing the relation reads. -/theorem LoopRel.skip {Signed : Pub T M I D → M → Prop}{pub : Pub T M I D} {m : M}{n : Node T M I D} {st : State T M D} {s : Int}@@ -835,18 +1118,27 @@ theorem loop_inv {Signed : Pub T M I D → M → Prop}refine ⟨along_append ha ha', ?_⟩rw [applyAll_append]exact hr'- · exact loop_inv sel os n _ hsub' (h.skip H init (by omega))+ · have hr1 : LoopRel H init Signed pub m+ ((Write.outcome ⟨o.seq, false, st.root⟩).apply n)+ { st with lastSeq := o.seq } :=+ (h.skip H init (by omega)).of_same ⟨rfl, rfl, rfl, rfl⟩+ obtain ⟨ha', hr'⟩ := loop_inv sel os _ _ hsub' hr1+ refine ⟨along_append+ (along_one h.inv (Mono.of_same ⟨rfl, rfl, rfl, rfl⟩) hr1.inv) ha', ?_⟩+ rw [applyAll_append]+ exact hr'-/-- The write that records the publication once the loop is done. -/+/-- A write that records the publication, with any head: the one at+acceptance and the one once the loop is done. -/theorem final_write {Signed : Pub T M I D → M → Prop}{pub : Pub T M I D} {m : M}- {n : Node T M I D} {st : State T M D}+ {n : Node T M I D} {st : State T M D} (hd : Int)(h : LoopRel H init Signed pub m n st) :Inv H init Signed ((Write.state ⟨st.treeId, pub.generation, st.lastSeq,st.root,- some m⟩).apply n) ∧+ some m, hd⟩).apply n) ∧Mono n ((Write.state ⟨st.treeId, pub.generation, st.lastSeq, st.root,- some m⟩).apply n) := by+ some m, hd⟩).apply n) := byobtain ⟨hrep, hcur0, -, happ, ⟨hroot, hbelow⟩, hsuf, hst, hle, hagree,hnolog, htree,hsigned, ⟨hgen, hgen'⟩, -⟩ := h@@ -888,8 +1180,62 @@ theorem final_write {Signed : Pub T M I D → M → Prop}· exact Or.inl h0· exact Or.inr h0.symm+/-- The write that records a publication at acceptance: the loop goes on+from the state it wrote. -/+theorem accept_write {Signed : Pub T M I D → M → Prop}+ {pub : Pub T M I D} {m : M}+ {n : Node T M I D} {st : State T M D} (hd : Int)+ (h : LoopRel H init Signed pub m n st) :+ Inv H init Signed ((Write.state ⟨st.treeId, pub.generation, st.lastSeq,+ st.root, some m, hd⟩).apply n) ∧+ Mono n ((Write.state ⟨st.treeId, pub.generation, st.lastSeq, st.root,+ some m, hd⟩).apply n) ∧+ LoopRel H init Signed pub m+ ((Write.state ⟨st.treeId, pub.generation, st.lastSeq, st.root,+ some m, hd⟩).apply n)+ ⟨st.treeId, pub.generation, st.lastSeq, st.root, some m, hd⟩ := by+ obtain ⟨hfi, hfm⟩ := final_write H init hd h+ refine ⟨hfi, hfm, ?_⟩+ obtain ⟨hrep, hcur0, -, -, ⟨hroot, hbelow⟩, hsuf, hst, hle, -, -, htree,+ hsigned, -, -⟩ := h+ simp only [Write.apply] at hfi ⊢+ exact ⟨hrep, by show 0 ≤ st.lastSeq; omega, hfi.bound, hfi.applied,+ ⟨by show st.root = _; rw [hst, hroot],+ fun l hl => by show l.seq ≤ st.lastSeq; have := hbelow l hl; omega⟩,+ hsuf, rfl, Int.le_refl _,+ fun s hs => by+ simp only [Option.some.injEq] at hs; subst hs; exact ⟨rfl, rfl, rfl⟩,+ by simp, htree, hsigned, ⟨Int.le_refl _, fun _ => Or.inr rfl⟩,+ fun m' hm => by+ simp only [Option.some.injEq] at hm+ subst hm+ exact ⟨pub, hsigned, rfl⟩⟩+end loop+/-- Recovery reads nothing of the outcomes record. -/+theorem recover_same [DecidableEq I] [DecidableEq D] {H : D → D → D} {init : D}+ {n n' : Node T M I D} (hs : Same n n') (pub : Pub T M I D)+ (st : State T M D) :+ recover H init n' pub st = recover H init n pub st := by+ unfold recover+ rw [hs.pending, hs.measured, hs.log]++/-- Recovery only goes on with a pending operation the publication has. -/+theorem recover_found [DecidableEq I] [DecidableEq D] {H : D → D → D} {init : D}+ {n : Node T M I D} {pub : Pub T M I D} {st0 st : State T M D}+ {ws : List (Write T M I D)} {p : Op I D}+ (hrec : recover H init n pub st0 = some (ws, st))+ (hp : n.pending = some p) : ∃ o ∈ pub.ops, o.seq = p.seq := by+ unfold recover at hrec+ simp only [hp] at hrec+ split at hrec+ · simp at hrec+ rename_i o hf+ have hos := List.find?_some hf+ simp only [decide_eq_true_eq] at hos+ exact ⟨o, List.mem_of_find?_eq_some hf, hos.1⟩+/-! ### Recovery and a whole run -/section run@@ -973,25 +1319,27 @@ theorem LoopRel.start {Signed : Pub T M I D → M → Prop}/-- What `tree_recover_pending()` writes, by where the run before itstopped: nothing without a pending operation; the unlink alone when thecursor is at or past it; nothing, leaving the cursor below it, when it is-neither measured nor appended; its line, the state and the unlink when it-is measured and not appended; and the state and the unlink when it is-appended. -/-def RecoverSpec (n : Node T M I D) (ws : List (Write T M I D))- (st : State T M D) : Prop :=+neither measured nor appended; its line, then its outcome lines, the state+and the unlink when it is measured and not appended; and the outcome lines,+the state and the unlink when it is appended. `lines` gives the outcome+lines of a pending operation, and a state recovery writes keeps the head+the node recorded. -/+def RecoverSpec (n : Node T M I D) (lines : Op I D → List (OLine D))+ (ws : List (Write T M I D)) (st : State T M D) : Prop :=match n.pending with- | none => ws = []+ | none => ws = [] ∧ st.lastSeq = cursor n| some p =>- (p.seq ≤ cursor n ∧ ws = [.unlink]) ∨+ (p.seq ≤ cursor n ∧ ws = [.unlink] ∧ st.lastSeq = cursor n) ∨(cursor n < p.seq ∧ (p.seq, p.digest) ∉ n.measured ∧(p.seq, p.digest) ∉ events n.log ∧ws = [] ∧ st.lastSeq = cursor n) ∨(cursor n < p.seq ∧ (p.seq, p.digest) ∈ n.measured ∧(p.seq, p.digest) ∉ events n.log ∧- (∃ r, ws = [.append ⟨p.seq, p.digest, r⟩, .state st, .unlink]) ∧- st.lastSeq = p.seq) ∨+ (∃ r, ws = .append ⟨p.seq, p.digest, r⟩ :: complete (lines p) st) ∧+ st.lastSeq = p.seq ∧ ∀ s, n.state = some s → st.headSeq = s.headSeq) ∨(cursor n < p.seq ∧ (p.seq, p.digest) ∈ events n.log ∧- ws = [.state st, .unlink] ∧- st.lastSeq = p.seq)+ ws = complete (lines p) st ∧+ st.lastSeq = p.seq ∧ ∀ s, n.state = some s → st.headSeq = s.headSeq)/-- `tree_recover_pending()`, stopped after any of its writes: every nodeit leaves keeps the invariant and goes forward, the loop goes on from a@@ -1006,7 +1354,9 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}(hrec : recover H init n pub (n.state.getD (fresh init pub.treeId)) =some (ws, st)) :Along (Inv H init Signed) Mono ws n ∧- LoopRel H init Signed pub m (applyAll ws n) st ∧ RecoverSpec n ws st := by+ LoopRel H init Signed pub m (applyAll ws n) st ∧+ RecoverSpec n (recLines H pub (n.state.getD (fresh init pub.treeId)))+ ws st := byobtain ⟨hst0r, hst0c, hagree, htree, hgen, hstb⟩ :=start_facts H init hbind hinv hchk hfol hsighave hgo : Clean H init n → Suffix n.log n.measured →@@ -1032,7 +1382,9 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}· exact h· simp [hp] at hp'· simp [hp] at hp'- exact ⟨hinv, hgo hw.1 hw.2, by simp [RecoverSpec, hp]⟩+ refine ⟨hinv, hgo hw.1 hw.2, ?_⟩+ simp only [RecoverSpec, hp]+ exact ⟨by trivial, hst0c⟩| some p =>simp only [hp] at hrecsplit at hrec@@ -1059,16 +1411,18 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}· rw [hp, Option.some.injEq] at hp'; subst hp'; omega· rw [hp, Option.some.injEq] at hp'; subst hp'; omegahave hinv' : Inv H init Signed- (⟨n.state, none, n.log, n.measured⟩ : Node T M I D) :=+ (⟨n.state, none, n.log, n.measured, n.outcomes⟩ : Node T M I D) :=⟨hinv.replays, hinv.cursor_nonneg, hinv.bound, hinv.applied,fun hs => by simp [nolog_of_clean H init hinv hw.1 hs], Or.inl hw⟩have hspec :- RecoverSpec n [.unlink] (n.state.getD (fresh init pub.treeId)) := by+ RecoverSpec n (recLines H pub (n.state.getD (fresh init pub.treeId)))+ [.unlink] (n.state.getD (fresh init pub.treeId)) := bysimp only [RecoverSpec, hp]- exact Or.inl ⟨by omega, trivial⟩+ exact Or.inl ⟨by omega, trivial, hst0c⟩simp only [Along, applyAll, List.foldl, Write.apply]exact ⟨⟨hinv, Mono.of_state rfl ⟨[], by simp⟩, hinv'⟩,- LoopRel.start H init (n := ⟨n.state, none, n.log, n.measured⟩) hbind+ LoopRel.start H init+ (n := ⟨n.state, none, n.log, n.measured, n.outcomes⟩) hbindhinv' hw.1 hw.2hchk hfol hsig, hspec⟩rename_i hgt@@ -1138,7 +1492,7 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}have hinv1 : Inv H init Signed (⟨n.state, n.pending,n.log ++ [⟨o.seq, o.digest,H (n.state.getD (fresh init pub.treeId)).root o.digest⟩],- n.measured⟩ :+ n.measured, n.outcomes⟩ :Node T M I D) := byrefine ⟨hrep1, hinv.cursor_nonneg, hinv.bound, fun s hs l hl => ?_,fun hs l hl => ?_, Or.inr (Or.inr ⟨o, n.log, hp, hlt,@@ -1159,7 +1513,9 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}simp only [Option.some.injEq, Prod.mk.injEq] at hrecobtain ⟨rfl, rfl⟩ := hrecobtain ⟨hca, hcr⟩ :=- commit H init (pub := pub) (L0 := n.log) hinv1 rfl hroot0+ complete_inv H init (pub := pub) (L0 := n.log)+ (recLines H pub (n.state.getD (fresh init pub.treeId)) o) hinv1 rfl+ hroot0(fun l hl => by have := hc.2 l hl; omega) (by omega)⟨L1, L2 ++ [_], by rw [hlog, List.append_assoc],by rw [hmeas]; simp [events]⟩@@ -1167,7 +1523,8 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}refine ⟨⟨hinv, Mono.of_state rfl ⟨_, rfl⟩, hca⟩, hcr, ?_⟩simp only [RecoverSpec, hp]exact Or.inr (Or.inr (Or.inl- ⟨hlt, hm, hnotin n.log hc.2, ⟨_, rfl⟩, trivial⟩))+ ⟨hlt, hm, hnotin n.log hc.2, ⟨_, rfl⟩, trivial,+ fun s hs => by simp [hs]⟩))· -- Its line appended too: commit.rw [hp, Option.some.injEq] at hp'subst hp'@@ -1192,14 +1549,16 @@ theorem recover_inv {Signed : Pub T M I D → M → Prop}exact ⟨pub, m, hsig, htree.symm, _, ho, h1.symm, h2.symm⟩· obtain ⟨q, m', h1, h2, h3⟩ := hinv.applied s hs l hlexact ⟨q, m', h1, h2.trans (hagree s hs).1, h3⟩- obtain ⟨hca, hcr⟩ := commit H init (pub := pub) (L0 := L0) hinv+ obtain ⟨hca, hcr⟩ := complete_inv H init (pub := pub) (L0 := L0)+ (recLines H pub (n.state.getD (fresh init pub.treeId)) o) hinv(by rw [hlog, hroot0]) hroot0(fun l hl => by have := hbelow l hl; omega) (by omega) hsuf happ0(Int.le_of_eq hst0c.symm) hagree htree hsig hgen hstbrefine ⟨hca, hcr, ?_⟩simp only [RecoverSpec, hp]exact Or.inr (Or.inr (Or.inr- ⟨hlt, by rw [hlog]; simp [events], trivial, trivial⟩))+ ⟨hlt, by rw [hlog]; simp [events], trivial, trivial,+ fun s hs => by simp [hs]⟩))/-- What the theorems assume and the C cannot show. A manifest digestnames one publication: it is the SHA-256 of the manifest, and@@ -1224,17 +1583,25 @@ theorem run_inv {Signed : Pub T M I D → M → Prop}split· rename_i hcobtain ⟨hchk, hfol⟩ := hc+ have hsm : Same n ((Write.truncate (cursor n).toNat).apply n) :=+ ⟨rfl, rfl, rfl, rfl⟩+ have hinv0 := Inv.of_same hsm hinv+ refine along_cons hinv (Mono.of_same hsm) ?_split- · exact hinv+ · exact along_nil hinv0· rename_i ws st hrecobtain ⟨hw, hr, -⟩ := recover_inv H init ha.binds ha.hash_inj- ha.hash_init hinv hchk- hfol hsig hrec- obtain ⟨hl, hr'⟩ := loop_inv H init sel pub.ops _ _ (fun _ ho => ho) hr- refine along_append (along_append hw hl) ?_- rw [applyAll_append]- obtain ⟨hfi, hfm⟩ := final_write H init hr'- exact ⟨hr'.inv, hfm, hfi⟩+ ha.hash_init hinv0 hchk+ hfol hsig ((recover_same hsm pub _).trans hrec)+ obtain ⟨hai, ham, hr1⟩ := accept_write H init pub.headSeq hr+ obtain ⟨hl, hr'⟩ := loop_inv H init sel pub.ops _ _ (fun _ ho => ho) hr1+ refine along_append (along_append+ (along_append hw (along_one hr.inv ham hai)) ?_) ?_+ · rw [applyAll_append]+ exact hl+ · rw [applyAll_append, applyAll_append]+ exact along_one hr'.inv (final_write H init _ hr').2+ (final_write H init _ hr').1· exact hinv/-- One step keeps the invariant and goes forward. -/@@ -1524,20 +1891,29 @@ theorem recover_pending {Signed : Pub T M I D → M → Prop}exact List.mem_append_right _ hesimp only [RecoverSpec, hp] at hspecrcases hspec with ⟨hle, -⟩ | ⟨-, hnm, hnl, rfl, hst⟩ |- ⟨-, hm, hnl, ⟨r, rfl⟩, -⟩ |- ⟨-, hl, rfl, -⟩+ ⟨-, hm, hnl, ⟨r, hws⟩, -⟩ |+ ⟨-, hl, hws, -⟩· omega· exact ⟨⟨[], by simp [applyAll], by simp⟩,⟨fun h => Or.inr h, fun h => h.elim (fun h' => absurd h' hnm) id⟩,fun _ => by omega, hkept⟩- · have hin :- (p.seq, p.digest) ∈ events (n.log ++ [⟨p.seq, p.digest, r⟩]) := by+ · have hlg : (applyAll ws n).log = n.log ++ [⟨p.seq, p.digest, r⟩] := by+ rw [hws, applyAll_cons]+ exact (complete_core _ _ _).1+ have hin : (p.seq, p.digest) ∈ events (applyAll ws n).log := by+ rw [hlg]simp [events]- exact ⟨⟨_, rfl, by simp⟩, ⟨fun _ => Or.inl hm, fun _ => hin⟩,+ exact ⟨⟨_, hlg, by simp⟩, ⟨fun _ => Or.inl hm, fun _ => hin⟩,+ fun h => absurd hin h, hkept⟩+ · have hlg : (applyAll ws n).log = n.log := by+ rw [hws]+ exact (complete_core _ _ _).1+ have hin : (p.seq, p.digest) ∈ events (applyAll ws n).log := by+ rw [hlg]+ exact hl+ exact ⟨⟨[], by rw [hlg, List.append_nil], by simp⟩,+ ⟨fun h => by rw [hlg] at h; exact Or.inr h, fun _ => hin⟩,fun h => absurd hin h, hkept⟩- · exact ⟨⟨[], by simp [applyAll, Write.apply], by simp⟩,- ⟨fun h => Or.inr h, fun _ => hl⟩,- fun h => absurd hl h, hkept⟩/-- After recovery the state is the fold of the tree eventlog, the cursorat or past all of it, and every operation this boot measured in it: the@@ -1623,4 +1999,752 @@ theorem applied_consistent {Signed : Pub T M I D → M → Prop}end run+/-! ### The outcomes record -/++/-- The sequence numbers 1 to `k`, in order. -/+def upto : Nat → List Int+ | 0 => []+ | k + 1 => upto k ++ [(k : Int) + 1]++theorem upto_length : ∀ k : Nat, (upto k).length = k+ | 0 => rfl+ | k + 1 => by+ show (upto k ++ [(k : Int) + 1]).length = k + 1+ rw [List.length_append, upto_length k, List.length_singleton]++theorem take_length_append {α : Type} :+ ∀ (xs ys : List α), (xs ++ ys).take xs.length = xs+ | [], _ => rfl+ | x :: xs, ys => congrArg (x :: ·) (take_length_append xs ys)++theorem take_append_le {α : Type} :+ ∀ (xs ys : List α) (k : Nat), k ≤ xs.length →+ (xs ++ ys).take k = xs.take k+ | _, _, 0, _ => rfl+ | [], _, _ + 1, h => absurd h (Nat.not_succ_le_zero _)+ | x :: xs, ys, k + 1, h =>+ congrArg (x :: ·) (take_append_le xs ys k (Nat.le_of_succ_le_succ h))++theorem take_take_le {α : Type} :+ ∀ (xs : List α) (k t : Nat), k ≤ t → (xs.take t).take k = xs.take k+ | _, 0, _, _ => rfl+ | [], _ + 1, t, _ => by cases t <;> rfl+ | _ :: _, _ + 1, 0, h => absurd h (Nat.not_succ_le_zero _)+ | x :: xs, k + 1, t + 1, h =>+ congrArg (x :: ·) (take_take_le xs k t (Nat.le_of_succ_le_succ h))++/-- The operations are numbered from `a + 1` on without a gap. -/+def Consec : Int → List (Op I D) → Prop+ | _, [] => True+ | a, o :: os => o.seq = a + 1 ∧ Consec (a + 1) os++theorem consec_of_range : ∀ (os : List (Op I D)) (a : Int),+ os.map (·.seq) =+ (List.range os.length).map (fun i : Nat => a + 1 + (i : Int)) →+ Consec a os+ | [], _, _ => trivial+ | o :: os, a, h => by+ rw [List.length_cons, List.range_succ_eq_map, List.map_cons, List.map_cons,+ List.map_map] at h+ obtain ⟨h1, h2⟩ := List.cons.inj h+ show o.seq = a + 1 ∧ Consec (a + 1) os+ refine ⟨by simpa using h1, consec_of_range os (a + 1) ?_⟩+ rw [h2]+ apply List.map_congr_left+ intro i _+ show a + 1 + ((i + 1 : Nat) : Int) = a + 1 + 1 + (i : Int)+ omega++/-- What `Checked` says of a publication's numbers, as the loops read+them. -/+theorem consec_of_checked {pub : Pub T M I D} (h : Checked pub) :+ Consec 0 pub.ops ∧ (pub.ops.length : Int) = pub.headSeq := by+ obtain ⟨-, hb, hh, hm⟩ := h+ rw [hb] at hm hh+ exact ⟨consec_of_range pub.ops 0 hm, by omega⟩++theorem consec_mem {o : Op I D} : ∀ (os : List (Op I D)) (a : Int),+ Consec a os → o ∈ os → a < o.seq ∧ o.seq ≤ a + (os.length : Int)+ | [], _, _, h => by cases h+ | x :: xs, a, hc, h => by+ simp only [Consec] at hc+ obtain ⟨hx, hc'⟩ := hc+ simp only [List.length_cons]+ rcases List.mem_cons.1 h with rfl | h'+ · omega+ · have := consec_mem xs (a + 1) hc' h'+ omega++/-- The record holds the lines of 1 to `k`, in order, and no other. -/+def Exact (n : Node T M I D) (k : Int) : Prop :=+ ∃ c : Nat, (c : Int) = k ∧ n.outcomes.map (·.seq) = upto c++/-- The outcomes record covers the cursor: it starts with a line for each+operation from 1 to the cursor, in order. What follows them is what a sync+that stopped left behind. -/+def Covers (n : Node T M I D) : Prop :=+ ∃ (c : Nat) (pre rest : List (OLine D)),+ (c : Int) = cursor n ∧ n.outcomes = pre ++ rest ∧ pre.map (·.seq) = upto c++/-- What every node a sync can leave holds of the outcomes record and of+the head: the record covers the cursor, the cursor is at or below the head+of the recorded publication, and so is a pending operation, which is only+there with a state. -/+structure OInv (n : Node T M I D) : Prop where+ covers : Covers n+ head : ∀ s, n.state = some s → s.lastSeq ≤ s.headSeq+ pend : ∀ p, n.pending = some p → ∃ s, n.state = some s ∧ p.seq ≤ s.headSeq++/-- From `n` to `n'` the cursor did not go back and no line at or below the+cursor of `n` changed. -/+def OMono (n n' : Node T M I D) : Prop :=+ cursor n ≤ cursor n' ∧+ ∀ k : Nat, (k : Int) ≤ cursor n → n'.outcomes.take k = n.outcomes.take k++theorem OMono.refl (n : Node T M I D) : OMono n n :=+ ⟨Int.le_refl _, fun _ _ => rfl⟩++theorem OMono.trans {a b c : Node T M I D} (h1 : OMono a b) (h2 : OMono b c) :+ OMono a c :=+ ⟨Int.le_trans h1.1 h2.1,+ fun k hk => (h2.2 k (Int.le_trans hk h1.1)).trans (h1.2 k hk)⟩++theorem OMono.inert {n n' : Node T M I D} (ho : n'.outcomes = n.outcomes)+ (hs : n'.state = n.state) : OMono n n' :=+ ⟨Int.le_of_eq (cursor_of_state hs).symm, fun _ _ => by rw [ho]⟩++theorem OMono.append {n : Node T M I D} {l : OLine D}+ (hlen : ∀ k : Nat, (k : Int) ≤ cursor n → k ≤ n.outcomes.length) :+ OMono n ((Write.outcome l).apply n) :=+ ⟨Int.le_refl _, fun k hk => take_append_le n.outcomes [l] k (hlen k hk)⟩++theorem Covers.of_eq {n n' : Node T M I D} (ho : n'.outcomes = n.outcomes)+ (hc : cursor n' = cursor n) (h : Covers n) : Covers n' := by+ unfold Covers at h ⊢+ obtain ⟨c, pre, rest, h1, h2, h3⟩ := h+ exact ⟨c, pre, rest, h1.trans hc.symm, ho.trans h2, h3⟩++theorem Covers.append {n : Node T M I D} {l : OLine D} (h : Covers n) :+ Covers ((Write.outcome l).apply n) := by+ unfold Covers at h ⊢+ obtain ⟨c, pre, rest, h1, h2, h3⟩ := h+ refine ⟨c, pre, rest ++ [l], h1, ?_, h3⟩+ show n.outcomes ++ [l] = pre ++ (rest ++ [l])+ rw [h2, List.append_assoc]++theorem OInv.inert {n n' : Node T M I D} (h : OInv n)+ (ho : n'.outcomes = n.outcomes) (hs : n'.state = n.state)+ (hp : ∀ p, n'.pending = some p →+ ∃ s, n'.state = some s ∧ p.seq ≤ s.headSeq) : OInv n' :=+ ⟨Covers.of_eq ho (cursor_of_state hs) h.covers,+ by rw [hs]; exact h.head, hp⟩++theorem OInv.empty : OInv (Node.empty : Node T M I D) :=+ ⟨⟨0, [], [], rfl, rfl, rfl⟩,+ fun s hs => absurd (show (none : Option (State T M D)) = some s from hs)+ (by simp),+ fun p hp => absurd (show (none : Option (Op I D)) = some p from hp)+ (by simp)⟩++theorem exact_len {n : Node T M I D} {k : Int} (h : Exact n k) :+ ∀ j : Nat, (j : Int) ≤ k → j ≤ n.outcomes.length := by+ obtain ⟨c, hc, he⟩ := h+ intro j hj+ have hl := congrArg List.length he+ rw [List.length_map, upto_length] at hl+ omega++theorem exact_append {n : Node T M I D} {k : Int} {l : OLine D}+ (h : Exact n k) (hl : l.seq = k + 1) :+ Exact ((Write.outcome l).apply n) l.seq := by+ obtain ⟨c, hc, he⟩ := h+ have hs : l.seq = (c : Int) + 1 := by omega+ have e1 : (n.outcomes ++ [l]).map (·.seq) =+ n.outcomes.map (·.seq) ++ [l.seq] := by simp+ refine ⟨c + 1, by omega, ?_⟩+ show (n.outcomes ++ [l]).map (·.seq) = upto c ++ [(c : Int) + 1]+ rw [e1, he, hs]++theorem exact_covers {n : Node T M I D} {k : Int} (h : Exact n k)+ (hk : cursor n = k) : Covers n := by+ obtain ⟨c, hc, he⟩ := h+ exact ⟨c, n.outcomes, [], hc.trans hk.symm, by simp, he⟩++/-- Outcome lines after a record that reaches the cursor, stopped after+any of them. -/+theorem along_olines : ∀ (ls : List (OLine D)) (n : Node T M I D), OInv n →+ (∀ k : Nat, (k : Int) ≤ cursor n → k ≤ n.outcomes.length) →+ Along OInv OMono (ls.map Write.outcome) n ∧+ OInv (applyAll (ls.map Write.outcome) n) ∧+ (applyAll (ls.map Write.outcome) n).outcomes = n.outcomes ++ ls+ | [], n, ho, _ => ⟨along_nil ho, ho, (by simp : n.outcomes = n.outcomes ++ [])⟩+ | l :: ls, n, ho, hlen => by+ have h1 : OInv ((Write.outcome l).apply n) :=+ ⟨Covers.append ho.covers, ho.head, ho.pend⟩+ obtain ⟨ha, hoe, he⟩ := along_olines ls ((Write.outcome l).apply n) h1+ (fun k hk => by+ have := hlen k hk+ show k ≤ (n.outcomes ++ [l]).length+ rw [List.length_append]+ omega)+ have e2 : n.outcomes ++ [l] ++ ls = n.outcomes ++ l :: ls := by simp+ exact ⟨along_cons ho (OMono.append hlen) ha, hoe, he.trans e2⟩++/-- The lines of the operations recovery finds passed over continue a+record of 1 to `c` up to the number before the pending operation's. -/+theorem passed_ext (lo hi : Int) (root : D) :+ ∀ (os : List (Op I D)) (a : Int) (c : Nat), Consec a os → lo ≤ c →+ a ≤ c → ((c : Int) = a ∨ (c : Int) = lo) → (c : Int) < hi →+ hi ≤ a + (os.length : Int) + 1 →+ ∃ c' : Nat, (c' : Int) = hi - 1 ∧+ upto c ++ (passed lo hi root os).map (·.seq) = upto c'+ | [], _, c, _, _, _, _, _, hhi =>+ ⟨c, by simp only [List.length_nil] at hhi; omega,+ (by simp [passed] : upto c ++ (passed lo hi root []).map (·.seq) = upto c)⟩+ | o :: os, a, c, hcs, hlo, hac, hca, hlt, hhi => by+ simp only [Consec] at hcs+ obtain ⟨hoa, hcs'⟩ := hcs+ simp only [List.length_cons] at hhi+ by_cases h1 : hi ≤ o.seq+ · have hp : passed lo hi root (o :: os) = [] := by+ simp only [passed, ite_eq_left h1]+ refine ⟨c, by omega, ?_⟩+ rw [hp]+ simp+ · by_cases h2 : o.seq ≤ lo+ · have hp : passed lo hi root (o :: os) = passed lo hi root os := by+ simp only [passed, ite_eq_right h1, ite_eq_left h2]+ rw [hp]+ exact passed_ext lo hi root os (a + 1) c hcs' hlo (by omega)+ (Or.inr (by omega)) hlt (by omega)+ · have hp : passed lo hi root (o :: os) =+ ⟨o.seq, false, root⟩ :: passed lo hi root os := by+ simp only [passed, ite_eq_right h1, ite_eq_right h2]+ obtain ⟨c', hc', he⟩ := passed_ext lo hi root os (a + 1) (c + 1) hcs'+ (by omega) (by omega) (Or.inl (by omega)) (by omega) (by omega)+ have hseq : o.seq = (c : Int) + 1 := by omega+ refine ⟨c', hc', ?_⟩+ rw [hp, ← he]+ have e1 : upto c ++ List.map (·.seq)+ ((⟨o.seq, false, root⟩ : OLine D) :: passed lo hi root os) =+ upto c ++ [o.seq] ++ List.map (·.seq) (passed lo hi root os) := by+ simp+ have e2 : upto c ++ [o.seq] = upto (c + 1) :=+ congrArg (fun x => upto c ++ [x]) hseq+ exact e1.trans (congrArg (· ++ List.map (·.seq) (passed lo hi root os)) e2)++/-- Between two operations of the loop, as far as the outcomes record and+the head go: the record holds exactly the lines up to the cursor the run+holds, which is at or below the head of the publication, and the state on+the node records that head. -/+structure ORel (pub : Pub T M I D) (n : Node T M I D) (st : State T M D) :+ Prop where+ lines : Exact n st.lastSeq+ le : cursor n ≤ st.lastSeq+ bound : st.lastSeq ≤ pub.headSeq+ headEq : st.headSeq = pub.headSeq+ disk : ∃ s, n.state = some s ∧ s.headSeq = pub.headSeq+ oinv : OInv n++/-- One operation the loop applies, stopped after any of its writes. -/+theorem oloop_apply {pub : Pub T M I D} {n : Node T M I D} {st : State T M D}+ {o : Op I D} (r : D) (h : ORel pub n st) (hseq : o.seq = st.lastSeq + 1)+ (hle : o.seq ≤ pub.headSeq) :+ Along OInv OMono+ [.pending o, .measure o.seq o.digest, .append ⟨o.seq, o.digest, r⟩,+ .outcome ⟨o.seq, true, r⟩,+ .state { st with root := r, lastSeq := o.seq }, .unlink] n ∧+ ORel pub+ (applyAll [.pending o, .measure o.seq o.digest,+ .append ⟨o.seq, o.digest, r⟩, .outcome ⟨o.seq, true, r⟩,+ .state { st with root := r, lastSeq := o.seq }, .unlink] n)+ { st with root := r, lastSeq := o.seq } := by+ obtain ⟨hex, hcl, -, hhe, ⟨s0, hs0, hs0h⟩, hoi⟩ := h+ have h1 : OInv ((Write.pending o).apply n) :=+ hoi.inert rfl rfl (fun p hp => ⟨s0, hs0, by+ have hpo : o = p := Option.some.inj hp+ rw [← hpo]+ omega⟩)+ have h2 : OInv ((Write.measure o.seq o.digest).apply ((Write.pending o).apply n)) :=+ h1.inert rfl rfl h1.pend+ have h3 : OInv ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n))) :=+ h2.inert rfl rfl h2.pend+ have h4 : OInv ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))) :=+ ⟨Covers.append h3.covers, h3.head, h3.pend⟩+ have hx4 : Exact ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))) o.seq :=+ exact_append (n := ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))) (l := ⟨o.seq, true, r⟩) hex hseq+ have h5 : OInv ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n))))) :=+ ⟨exact_covers (n := ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))))) hx4 rfl,+ fun s hs => by+ have e : ({ st with root := r, lastSeq := o.seq } : State T M D) = s :=+ Option.some.inj hs+ rw [← e]+ show o.seq ≤ st.headSeq+ omega,+ fun p hp => ⟨{ st with root := r, lastSeq := o.seq }, rfl, by+ have hpo : o = p := Option.some.inj hp+ rw [← hpo]+ show o.seq ≤ st.headSeq+ omega⟩⟩+ have h6 : OInv (Write.unlink.apply+ ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))))) :=+ ⟨Covers.of_eq (n := ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))))) rfl rfl h5.covers, h5.head,+ fun p hp => absurd (show (none : Option (Op I D)) = some p from hp)+ (by simp)⟩+ have m1 : OMono n ((Write.pending o).apply n) := OMono.inert rfl rfl+ have m2 : OMono ((Write.pending o).apply n) ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)) := OMono.inert rfl rfl+ have m3 : OMono ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)) ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n))) := OMono.inert rfl rfl+ have m4 : OMono ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n))) ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))) :=+ OMono.append (fun k hk => exact_len hex k (Int.le_trans hk hcl))+ have m5 : OMono ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))) ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n))))) :=+ ⟨by show cursor n ≤ o.seq; omega, fun _ _ => rfl⟩+ have m6 : OMono ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n))))) (Write.unlink.apply+ ((Write.state { st with root := r, lastSeq := o.seq }).apply+ ((Write.outcome ⟨o.seq, true, r⟩).apply+ ((Write.append ⟨o.seq, o.digest, r⟩).apply+ ((Write.measure o.seq o.digest).apply+ ((Write.pending o).apply n)))))) := OMono.inert rfl rfl+ exact ⟨along_cons hoi m1 (along_cons h1 m2 (along_cons h2 m3+ (along_cons h3 m4 (along_cons h4 m5 (along_cons h5 m6 (along_nil h6)))))),+ ⟨hx4, Int.le_refl _, hle, hhe,+ ⟨{ st with root := r, lastSeq := o.seq }, rfl, hhe⟩, h6⟩⟩++/-- An operation the selector does not match: its line, and the cursor+moved in memory. -/+theorem oloop_skip {pub : Pub T M I D} {n : Node T M I D} {st : State T M D}+ {o : Op I D} (r : D) (h : ORel pub n st) (hseq : o.seq = st.lastSeq + 1)+ (hle : o.seq ≤ pub.headSeq) :+ Along OInv OMono [.outcome ⟨o.seq, false, r⟩] n ∧+ ORel pub ((Write.outcome ⟨o.seq, false, r⟩).apply n)+ { st with lastSeq := o.seq } := by+ obtain ⟨hex, hcl, -, hhe, hd, hoi⟩ := h+ have h1 : OInv ((Write.outcome ⟨o.seq, false, r⟩).apply n) :=+ ⟨Covers.append hoi.covers, hoi.head, hoi.pend⟩+ exact ⟨along_one hoi+ (OMono.append (fun k hk => exact_len hex k (Int.le_trans hk hcl))) h1,+ ⟨exact_append (l := ⟨o.seq, false, r⟩) hex hseq,+ by show cursor n ≤ o.seq; omega, hle, hhe, hd, h1⟩⟩++/-- The loop, stopped after any of its writes: every operation past the+cursor is the next one, so each line continues the record. -/+theorem oloop_inv {H : D → D → D} {pub : Pub T M I D} (sel : Op I D → Bool) :+ ∀ (os : List (Op I D)) (n : Node T M I D) (st : State T M D) (a : Int),+ Consec a os → a ≤ st.lastSeq → a + (os.length : Int) ≤ pub.headSeq →+ ORel pub n st →+ Along OInv OMono (loop H sel st os).1 n ∧+ ORel pub (applyAll (loop H sel st os).1 n) (loop H sel st os).2+ | [], _, _, _, _, _, _, h => ⟨h.oinv, h⟩+ | o :: os, n, st, a, hcs, hal, hb, h => by+ simp only [Consec] at hcs+ obtain ⟨hoa, hcs'⟩ := hcs+ simp only [List.length_cons] at hb+ simp only [loop]+ split+ · exact oloop_inv sel os n st (a + 1) hcs' (by omega) (by omega) h+ · rename_i hgt+ have hseq : o.seq = st.lastSeq + 1 := by omega+ split+ · obtain ⟨ha, hr⟩ := oloop_apply (H st.root o.digest) h hseq (by omega)+ obtain ⟨ha', hr'⟩ := oloop_inv sel os _ _ (a + 1) hcs'+ (by show a + 1 ≤ o.seq; omega) (by omega) hr+ refine ⟨along_append ha ha', ?_⟩+ rw [applyAll_append]+ exact hr'+ · obtain ⟨ha, hr⟩ := oloop_skip st.root h hseq (by omega)+ obtain ⟨ha', hr'⟩ := oloop_inv sel os _ _ (a + 1) hcs'+ (by show a + 1 ≤ o.seq; omega) (by omega) hr+ refine ⟨along_append ha ha', ?_⟩+ rw [applyAll_append]+ exact hr'++/-- A write of the state the loop holds, with any generation and manifest:+the one once the loop is done. -/+theorem ofinal {pub : Pub T M I D} {n : Node T M I D} {st : State T M D}+ (g : Int) (mf : Option M) (h : ORel pub n st) :+ OInv ((Write.state ⟨st.treeId, g, st.lastSeq, st.root, mf,+ st.headSeq⟩).apply n) ∧+ OMono n ((Write.state ⟨st.treeId, g, st.lastSeq, st.root, mf,+ st.headSeq⟩).apply n) := by+ obtain ⟨hex, hcl, hb, hhe, ⟨s0, hs0, hs0h⟩, hoi⟩ := h+ refine ⟨⟨exact_covers (n := (Write.state ⟨st.treeId, g, st.lastSeq, st.root,+ mf, st.headSeq⟩).apply n) hex rfl, fun s hs => ?_, fun p hp => ?_⟩,+ ⟨hcl, fun _ _ => rfl⟩⟩+ · have e : (⟨st.treeId, g, st.lastSeq, st.root, mf, st.headSeq⟩ :+ State T M D) = s := Option.some.inj hs+ rw [← e]+ show st.lastSeq ≤ st.headSeq+ omega+ · obtain ⟨s1, hs1, hps⟩ := hoi.pend p hp+ have e : s1 = s0 := Option.some.inj (hs1.symm.trans hs0)+ rw [e] at hps+ exact ⟨⟨st.treeId, g, st.lastSeq, st.root, mf, st.headSeq⟩, rfl, by+ show p.seq ≤ st.headSeq+ omega⟩++/-- Recovery completing an applied operation, as far as the outcomes+record and the head go, stopped after any of its writes: the lines continue+the record to the operation's number before the state that covers them. -/+theorem ocomplete_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}+ {st0 st : State T M D} {p : Op I D} (hx : Exact n (cursor n)) (ho : OInv n)+ (hcs : Consec 0 pub.ops) (hlen : (pub.ops.length : Int) = pub.headSeq)+ (hst0 : st0.lastSeq = cursor n) (hlt : cursor n < p.seq)+ (hph : p.seq ≤ pub.headSeq) (hl : st.lastSeq = p.seq)+ (hh : ∀ s, n.state = some s → st.headSeq = s.headSeq)+ (hpn : n.pending = some p) :+ Along OInv OMono (complete (recLines H pub st0 p) st) n ∧+ Exact (applyAll (complete (recLines H pub st0 p) st) n) st.lastSeq ∧+ cursor (applyAll (complete (recLines H pub st0 p) st) n) ≤ st.lastSeq ∧+ OInv (applyAll (complete (recLines H pub st0 p) st) n) ∧+ ∀ q, (applyAll (complete (recLines H pub st0 p) st) n).pending = some q →+ q.seq ≤ pub.headSeq := by+ have hlenx := exact_len hx+ obtain ⟨c, hc, he⟩ := hx+ obtain ⟨s1, hs1, hps⟩ := ho.pend p hpn+ have hhs := hh s1 hs1+ obtain ⟨c', hc', hext⟩ := passed_ext st0.lastSeq p.seq st0.root pub.ops 0 c+ hcs (by omega) (by omega) (Or.inr (by omega)) (by omega) (by omega)+ obtain ⟨hal, hoL, heq⟩ := along_olines+ (passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]) n ho hlenx+ have hsame := same_outcomes+ (passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]) n+ have hcL : cursor (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n) = cursor n :=+ cursor_of_state hsame.state+ have hxL : Exact (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n)+ st.lastSeq := by+ have e3 : (n.outcomes ++ (passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)])).map (·.seq) =+ n.outcomes.map (·.seq) +++ (passed st0.lastSeq p.seq st0.root pub.ops).map (·.seq) +++ [p.seq] := by+ simp+ have hs : p.seq = (c' : Int) + 1 := by omega+ unfold Exact+ refine ⟨c' + 1, by omega, ?_⟩+ rw [heq, e3, he, hext]+ show upto c' ++ [p.seq] = upto c' ++ [(c' : Int) + 1]+ rw [hs]+ have hS : OInv ((Write.state st).apply+ (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n)) :=+ ⟨exact_covers (n := (Write.state st).apply+ (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n)) hxL rfl,+ fun s hs => by+ have e : st = s := Option.some.inj hs+ rw [← e]+ omega,+ fun q hq => ⟨st, rfl, by+ have e : p = q :=+ Option.some.inj (hpn.symm.trans (hsame.pending.symm.trans hq))+ rw [← e]+ omega⟩⟩+ have mS : OMono+ (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n)+ ((Write.state st).apply+ (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n)) :=+ ⟨by+ show cursor (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n) ≤+ st.lastSeq+ omega, fun _ _ => rfl⟩+ have hU : OInv (Write.unlink.apply ((Write.state st).apply+ (applyAll ((passed st0.lastSeq p.seq st0.root pub.ops +++ [(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]).map Write.outcome) n))) :=+ ⟨Covers.of_eq rfl rfl hS.covers, hS.head,+ fun q hq => absurd (show (none : Option (Op I D)) = some q from hq)+ (by simp)⟩+ unfold complete recLines+ rw [applyAll_append]+ exact ⟨along_append hal+ (along_cons hoL mS (along_cons hS (OMono.inert rfl rfl) (along_nil hU))),+ hxL, Int.le_refl _, hU,+ fun q hq => absurd (show (none : Option (Op I D)) = some q from hq)+ (by simp)⟩++/-- `tree_recover_pending()`, as far as the outcomes record and the head+go, stopped after any of its writes, from a record cut to the cursor. The+loop goes on from a record that holds exactly the lines up to its cursor,+and an operation still pending is one of the publication. -/+theorem orecover_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}+ {st0 st : State T M D} {ws : List (Write T M I D)}+ (hx : Exact n (cursor n)) (ho : OInv n) (hcs : Consec 0 pub.ops)+ (hlen : (pub.ops.length : Int) = pub.headSeq)+ (hst0 : st0.lastSeq = cursor n) (hcur : cursor n ≤ pub.headSeq)+ (hfound : ∀ p, n.pending = some p → ∃ o ∈ pub.ops, o.seq = p.seq)+ (hspec : RecoverSpec n (recLines H pub st0) ws st) :+ Along OInv OMono ws n ∧ Exact (applyAll ws n) st.lastSeq ∧+ cursor (applyAll ws n) ≤ st.lastSeq ∧ st.lastSeq ≤ pub.headSeq ∧+ OInv (applyAll ws n) ∧+ ∀ q, (applyAll ws n).pending = some q → q.seq ≤ pub.headSeq := by+ cases hp : n.pending with+ | none =>+ simp only [RecoverSpec, hp] at hspec+ obtain ⟨rfl, hl⟩ := hspec+ exact ⟨along_nil ho, by rw [hl]; exact hx, Int.le_of_eq hl.symm,+ by omega, ho, fun q hq => absurd (hp.symm.trans hq) (by simp)⟩+ | some p =>+ simp only [RecoverSpec, hp] at hspec+ obtain ⟨o, hom, hop⟩ := hfound p hp+ have hoh := (consec_mem pub.ops 0 hcs hom).2+ have hph : p.seq ≤ pub.headSeq := by omega+ rcases hspec with ⟨-, rfl, hl⟩ | ⟨-, -, -, rfl, hl⟩ |+ ⟨hlt, -, -, ⟨r, rfl⟩, hl, hh⟩ | ⟨hlt, -, rfl, hl, hh⟩+ · have h1 : OInv ((Write.unlink : Write T M I D).apply n) :=+ ⟨Covers.of_eq rfl rfl ho.covers, ho.head,+ fun q hq => absurd (show (none : Option (Op I D)) = some q from hq)+ (by simp)⟩+ exact ⟨along_one ho (OMono.inert rfl rfl) h1, by rw [hl]; exact hx,+ Int.le_of_eq hl.symm, by omega, h1,+ fun q hq => absurd (show (none : Option (Op I D)) = some q from hq)+ (by simp)⟩+ · exact ⟨along_nil ho, by rw [hl]; exact hx, Int.le_of_eq hl.symm,+ by omega, ho, fun q hq => by+ have e : p = q := Option.some.inj (hp.symm.trans hq)+ rw [← e]+ exact hph⟩+ · have h1 : OInv ((Write.append ⟨p.seq, p.digest, r⟩ :+ Write T M I D).apply n) :=+ ho.inert rfl rfl ho.pend+ obtain ⟨ha, hxe, hcu, hoi, hpe⟩ := ocomplete_inv (H := H) (pub := pub)+ (n := (Write.append ⟨p.seq, p.digest, r⟩ : Write T M I D).apply n)+ (st0 := st0) (st := st) hx h1 hcs hlen hst0 hlt hph hl hh hp+ exact ⟨along_cons ho (OMono.inert rfl rfl) ha, hxe, hcu, by omega, hoi,+ hpe⟩+ · obtain ⟨ha, hxe, hcu, hoi, hpe⟩ := ocomplete_inv (H := H) (pub := pub)+ (st0 := st0) (st := st) hx ho hcs hlen hst0 hlt hph hl hh hp+ exact ⟨ha, hxe, hcu, by omega, hoi, hpe⟩++/-- A whole sync, as far as the outcomes record and the head go, stopped+after any of its writes. -/+theorem orun_inv [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n : Node T M I D} {pub : Pub T M I D} {m : M} (sel : Op I D → Bool)+ (hinv : Inv H init Signed n) (ho : OInv n) (hsig : Signed pub m) :+ Along OInv OMono (run H init n pub m sel) n := by+ unfold run+ split+ · rename_i hc+ obtain ⟨hchk, hfol⟩ := hc+ obtain ⟨hcs, hlen⟩ := consec_of_checked hchk+ have hsm : Same n ((Write.truncate (cursor n).toNat).apply n) :=+ ⟨rfl, rfl, rfl, rfl⟩+ have hinv0 := Inv.of_same hsm hinv+ have hcur : cursor n ≤ pub.headSeq := by+ cases hs : n.state with+ | none =>+ have h0 : cursor n = 0 := by simp [cursor, hs]+ omega+ | some s =>+ have hf := hfol+ simp only [hs, Follows] at hf+ have h5 := hf.2.2.2.2+ have h0 : cursor n = s.lastSeq := by simp [cursor, hs]+ omega+ obtain ⟨c, pre, rest, hc, hpre, hmap⟩ := ho.covers+ have ht : (cursor n).toNat = c := by+ have h2 : ((c : Int)).toNat = c := rfl+ rw [hc] at h2+ exact h2+ have hpl : pre.length = c := by+ have h3 := congrArg List.length hmap+ rw [List.length_map, upto_length] at h3+ exact h3+ have htk : n.outcomes.take (cursor n).toNat = pre := by+ rw [ht, hpre, ← hpl]+ exact take_length_append pre rest+ have hx0 : Exact ((Write.truncate (cursor n).toNat).apply n) (cursor n) := by+ refine ⟨c, hc, ?_⟩+ show (n.outcomes.take (cursor n).toNat).map (·.seq) = upto c+ rw [htk]+ exact hmap+ have ho0 : OInv ((Write.truncate (cursor n).toNat).apply n) :=+ ⟨exact_covers (n := (Write.truncate (cursor n).toNat).apply n) hx0 rfl,+ ho.head, ho.pend⟩+ have hm0 : OMono n ((Write.truncate (cursor n).toNat).apply n) :=+ ⟨Int.le_refl _, fun k hk =>+ take_take_le n.outcomes k (cursor n).toNat (by rw [ht]; omega)⟩+ refine along_cons ho hm0 ?_+ split+ · exact along_nil ho0+ · rename_i ws st hrec+ have hrec0 := (recover_same hsm pub _).trans hrec+ obtain ⟨-, -, hspec⟩ := recover_inv H init ha.binds ha.hash_inj+ ha.hash_init hinv0 hchk hfol hsig hrec0+ have hst0 := (start_facts H init ha.binds hinv0 hchk hfol hsig).2.1+ obtain ⟨haw, hxw, hcw, hbw, how, hpw⟩ := orecover_inv hx0 ho0 hcs hlen hst0+ hcur (fun p hp => recover_found hrec0 hp) hspec+ have hnn : 0 ≤ st.lastSeq := by+ obtain ⟨cw, hcw', -⟩ := hxw+ omega+ have hoA : OInv ((Write.state ⟨st.treeId, pub.generation, st.lastSeq,+ st.root, some m, pub.headSeq⟩).apply+ (applyAll ws ((Write.truncate (cursor n).toNat).apply n))) :=+ ⟨exact_covers (n := (Write.state ⟨st.treeId, pub.generation,+ st.lastSeq, st.root, some m, pub.headSeq⟩).apply+ (applyAll ws ((Write.truncate (cursor n).toNat).apply n))) hxw rfl,+ fun s hs => by+ have e : (⟨st.treeId, pub.generation, st.lastSeq, st.root, some m,+ pub.headSeq⟩ : State T M D) = s := Option.some.inj hs+ rw [← e]+ exact hbw,+ fun p hp => ⟨⟨st.treeId, pub.generation, st.lastSeq, st.root, some m,+ pub.headSeq⟩, rfl, hpw p hp⟩⟩+ have hmA : OMono (applyAll ws ((Write.truncate (cursor n).toNat).apply n))+ ((Write.state ⟨st.treeId, pub.generation, st.lastSeq, st.root, some m,+ pub.headSeq⟩).apply+ (applyAll ws ((Write.truncate (cursor n).toNat).apply n))) :=+ ⟨hcw, fun _ _ => rfl⟩+ have hrA : ORel pub ((Write.state ⟨st.treeId, pub.generation, st.lastSeq,+ st.root, some m, pub.headSeq⟩).apply+ (applyAll ws ((Write.truncate (cursor n).toNat).apply n)))+ ⟨st.treeId, pub.generation, st.lastSeq, st.root, some m,+ pub.headSeq⟩ :=+ ⟨hxw, Int.le_refl _, hbw, rfl,+ ⟨⟨st.treeId, pub.generation, st.lastSeq, st.root, some m,+ pub.headSeq⟩, rfl, rfl⟩, hoA⟩+ obtain ⟨hl, hr'⟩ := oloop_inv (H := H) sel pub.ops _+ ⟨st.treeId, pub.generation, st.lastSeq, st.root, some m, pub.headSeq⟩+ 0 hcs hnn (by omega) hrA+ refine along_append (along_append+ (along_append haw (along_one how hmA hoA)) ?_) ?_+ · rw [applyAll_append]+ exact hl+ · rw [applyAll_append, applyAll_append]+ exact along_one hr'.oinv (ofinal pub.generation (some m) hr').2+ (ofinal pub.generation (some m) hr').1+ · exact ho++/-- One step keeps what holds of the outcomes record and the head. -/+theorem ostep_inv [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n n' : Node T M I D} (hinv : Inv H init Signed n) (ho : OInv n)+ (h : Step H init Signed n n') : OInv n' ∧ OMono n n' := by+ cases h with+ | sync sel k hsig =>+ have h := orun_inv ha sel hinv ho hsig+ exact ⟨along_take h k,+ along_between OMono.refl (fun _ _ _ => OMono.trans) h 0 k+ (Nat.zero_le _)⟩+ | reboot =>+ exact ⟨⟨Covers.of_eq rfl rfl ho.covers, ho.head, ho.pend⟩,+ OMono.inert rfl rfl⟩++theorem osteps_inv [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n n' : Node T M I D} (hinv : Inv H init Signed n) (ho : OInv n)+ (h : Steps H init Signed n n') : OInv n' ∧ OMono n n' := by+ induction h with+ | refl => exact ⟨ho, OMono.refl _⟩+ | tail hst hs ih =>+ obtain ⟨hi, hm⟩ := ih+ obtain ⟨hi', hm'⟩ :=+ ostep_inv ha (steps_inv H init ha hinv hst).1 hi hs+ exact ⟨hi', OMono.trans hm hm'⟩++theorem reach_oinv [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n : Node T M I D} (h : Reach H init Signed n) : OInv n :=+ (osteps_inv ha (Inv.empty H init Signed) OInv.empty h).1++theorem later_omono [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n n' : Node T M I D} (hr : Reach H init Signed n)+ (h : Later H init Signed n n') : OMono n n' := by+ induction h with+ | steps hs =>+ exact (osteps_inv ha (reach_inv H init ha hr) (reach_oinv ha hr) hs).2+ | within sel h0 hsig hij =>+ exact along_between OMono.refl (fun _ _ _ => OMono.trans)+ (orun_inv ha sel (reach_inv H init ha h0) (reach_oinv ha h0) hsig) _ _ hij+ | trans h1 _ ih1 ih2 =>+ exact OMono.trans (ih1 hr) (ih2 (later_reach H init hr h1))++/-- The outcomes record has a line for every operation from 1 to the+cursor, in order, on every node a sequence of syncs, crashes and reboots+leaves: a sync never finds a state its record does not cover. -/+theorem outcomes_cover [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n : Node T M I D} (hr : Reach H init Signed n) :+ ∃ (c : Nat) (pre rest : List (OLine D)), (c : Int) = cursor n ∧+ n.outcomes = pre ++ rest ∧ pre.map (·.seq) = upto c :=+ (reach_oinv ha hr).covers++/-- No line at or below the cursor ever changes: the first lines of the+record, as many as the cursor says, are the same at every later point of+the node's history. -/+theorem outcomes_fixed [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n n' : Node T M I D} (hr : Reach H init Signed n)+ (hs : Later H init Signed n n') {k : Nat} (hk : (k : Int) ≤ cursor n) :+ n'.outcomes.take k = n.outcomes.take k :=+ (later_omono ha hr hs).2 k hk++/-- The cursor never passes the head of the publication the state+records. -/+theorem lastSeq_le_head [DecidableEq T] [DecidableEq M] [DecidableEq I]+ [DecidableEq D] {H : D → D → D} {init : D}+ {Signed : Pub T M I D → M → Prop} (ha : Assumptions H init Signed)+ {n : Node T M I D} (hr : Reach H init Signed n) {s : State T M D}+ (hst : n.state = some s) : s.lastSeq ≤ s.headSeq :=+ (reach_oinv ha hr).head s hst+end Shirudo.TreeSyncdiff --git a/testing/vm/build-bundle.sh b/testing/vm/build-bundle.shindex 5181b63e..53647b45 100755--- a/testing/vm/build-bundle.sh+++ b/testing/vm/build-bundle.sh@@ -448,7 +448,7 @@ build_tree_test_registry()local payloads="$FIXTURE_WORK/tree-payload"local reference- # One append-only tree that t7101 to t7104 walk in order:+ # One append-only tree that t7101 to t7106 walk in order:# the tree state a target writes is sealed, so no test can start# over, and each generation extends the one before it.python3 - "$registry_dir" \@@ -456,7 +456,10 @@ build_tree_test_registry()"$TMP_DIR/fixtures/shirudo-test-tree-skip.upatch" \"$TMP_DIR/fixtures/shirudo-test-tree-match.unload.upatch" \"$payloads" "$tree_match_payload" "$tree_skip_payload" \- "$tree_match_unload_payload" "$TEST_VM_ARCH" <<'PY'+ "$tree_match_unload_payload" "$TEST_VM_ARCH" \+ "$TMP_DIR/fixtures/shirudo-test-tree-skip.unload.upatch" \+ "$TMP_DIR/fixtures/shirudo-test-uprobe-multi.upatch" \+ "$tree_skip_unload_payload" "$uprobe_payload" <<'PY'import hashlibimport jsonimport pathlib@@ -465,6 +468,8 @@ import sysregistry, match_path, skip_path, match_unload_path, payloads = \map(pathlib.Path, sys.argv[1:6])match_payload, skip_payload, match_unload_payload, node_arch = sys.argv[6:10]+skip_unload_path, absent_path = map(pathlib.Path, sys.argv[10:12])+skip_unload_payload, absent_payload = sys.argv[12:14]def digest(body):@@ -527,6 +532,12 @@ match_unload_artifact = artifact("shirudo/tree-match-unload",match_unload_path,"shirudo-test-tree-match.unload.upatch",match_unload_payload)+skip_unload_artifact = artifact("shirudo/tree-skip-unload", skip_unload_path,+ "shirudo-test-tree-skip.unload.upatch",+ skip_unload_payload)+# Its uprobe target is a file the bpm family's VM does not have.+absent_artifact = artifact("shirudo/tree-absent", absent_path,+ "shirudo-test-uprobe-multi.upatch", absent_payload)this_node = {"architecture": [node_arch], "labels": {"env": ["tree-test"]}}other_node = {"architecture": [node_arch],@@ -544,11 +555,20 @@ operations = [match_unload_artifact, op="delete"),# t7105 loads this upatch by hand first.operation(7, "shirudo-test-tree-match", this_node, match_artifact),+ # t7106: an outcome of each kind, an operation after one without a+ # match for the sync it stops, and an artifact no test fetched yet.+ operation(8, "shirudo-test-tree-match", this_node, match_artifact),+ operation(9, "shirudo-test-tree-skip", other_node, skip_artifact),+ operation(10, "shirudo-test-uprobe-multi", this_node, absent_artifact),+ operation(11, "shirudo-test-tree-match", other_node, match_artifact),+ operation(12, "shirudo-test-tree-skip", this_node, skip_artifact),+ operation(13, "shirudo-test-tree-skip", this_node, skip_unload_artifact,+ op="delete"),]-references = ("stable", "updated", "deleted", "restored", "kconfig",- "reloaded")-for generation, reference in enumerate(references, start=1):- head = generation + 1+heads = {"stable": 2, "updated": 3, "deleted": 4, "restored": 5,+ "kconfig": 6, "reloaded": 7, "outcomes": 10, "stopped": 12,+ "fetched": 13}+for generation, (reference, head) in enumerate(heads.items(), start=1):publication = {"schema": 1,"tree_id": "shirudo-test-tree",@@ -562,7 +582,8 @@ for generation, reference in enumerate(references, start=1):.encode())PY- for reference in stable updated deleted restored kconfig reloaded; do+ for reference in stable updated deleted restored kconfig reloaded \+ outcomes stopped fetched; doopenssl cms -sign -binary -md sha512 \-in "$payloads-$reference.json" \-signer "$FIXTURE_WORK/trusted/cert.der" \@@ -591,7 +612,7 @@ def write(path, body):for reference in ("stable", "updated", "deleted", "restored", "kconfig",- "reloaded"):+ "reloaded", "outcomes", "stopped", "fetched"):stem = payloads.name + "-" + referencepayload = payloads.with_name(stem + ".json").read_bytes()signature = payloads.with_name(stem + ".sig").read_bytes()@@ -867,6 +888,9 @@ wait_fixture_jobstree_match_unload_payload="$($REPO_ROOT/shirudo upatch info \"$TMP_DIR/fixtures/shirudo-test-tree-match.unload.upatch" --json |python3 -c 'import json,sys; print(json.load(sys.stdin)["payload_sha256"])')"+tree_skip_unload_payload="$($REPO_ROOT/shirudo upatch info \+ "$TMP_DIR/fixtures/shirudo-test-tree-skip.unload.upatch" --json |+ python3 -c 'import json,sys; print(json.load(sys.stdin)["payload_sha256"])')"build_tree_test_registrymv /tmp/shirudo-test-uprobe-target \diff --git a/testing/vm/image-fixtures.sh b/testing/vm/image-fixtures.shindex 15a33a5f..2175719c 100755--- a/testing/vm/image-fixtures.sh+++ b/testing/vm/image-fixtures.sh@@ -72,7 +72,8 @@ donefor name in config-boot-keys config-live-new-key config-live-revoke-a config-a config-b config-bad config-revoke \config-tree-stable config-tree-updated config-tree-deleted config-tree-restored \- config-tree-kconfig config-tree-reloaded \+ config-tree-kconfig config-tree-reloaded config-tree-outcomes \+ config-tree-stopped config-tree-fetched \config-otel config-jsonl config-jsonl-bad config-interrupted config-end2end \config-local-stack config-builtin config-untrusted; do[ "$name" != config-builtin ] || [ -n "$builtin_key" ] || continue