Compare commits

...
31 Commits
Author SHA1 Message Date
DeFiDude 8bad5e2f1f ci: include final BLE disconnect ownership correction 2026-10-08 23:17:54 -06:00
DeFiDude a40fda5ccf ci: qualify against finalized Rust 1.89 protocol candidate 2026-10-08 23:11:08 -06:00
DeFiDude e38d30e02a build: raise LXMF host minimum to Rust 1.89 2026-10-08 22:59:46 -06:00
DeFiDude 284d56fee3 build: qualify delivery against corrected toolchain-compatible core 2026-10-08 16:21:43 -06:00
DeFiDude df3a500c4f docs: organize pending delivery and compatibility changes 2026-09-25 00:24:56 -06:00
DeFiDude 8a22f7e951 api: record pending Direct compression hook 2026-09-24 17:56:29 -06:00
DeFiDude 98aa927e1d delivery: refresh pending Direct compression policy 2026-09-24 17:51:21 -06:00
DeFiDude 7caacbb382 delivery: weight split Resource progress by payload bytes 2026-09-24 13:23:10 -06:00
DeFiDude f959b200d8 delivery: keep active Resource links alive 2026-09-24 12:44:55 -06:00
DeFiDude 49a1f2a182 api: record event-driven delivery readiness contract 2026-09-24 10:21:59 -06:00
DeFiDude a48ee9c6a3 delivery: wake link transfers on input and local receipts 2026-09-24 10:20:13 -06:00
DeFiDude 4a0abec3b4 lxmd: preserve binary peer hashes in control requests 2026-09-20 00:47:32 -06:00
DeFiDude 534abbb95b build: align API fixture lock and qualified core metadata 2026-09-17 14:43:35 -06:00
DeFiDude 86d5e10230 build: pin corrected Windows socket dependency 2026-09-17 14:21:55 -06:00
DeFiDude 09948bf81c ci: pin bounded RPC fixture checkpoint 2026-09-17 13:51:01 -06:00
DeFiDude 7a851cc204 ci: qualify final core shutdown-test checkpoint 2026-09-17 12:41:36 -06:00
DeFiDude 85e725a064 build: adopt the bounded Reticulum 1.3 dependency line 2026-09-10 12:05:59 -06:00
DeFiDude 0a34047342 propagation: preserve legacy opaque blobs across reload 2026-09-09 00:52:43 -06:00
DeFiDude bb628ba8ef delivery: reject idle cancellation owners and cover Link reuse 2026-09-08 21:50:21 -06:00
DeFiDude fd69ab4fbc api: record reviewed delivery coordination additions 2026-09-08 20:03:36 -06:00
DeFiDude 8db95825c5 daemon: preserve ordered delivery receipts and exact cleanup 2026-09-08 20:00:35 -06:00
DeFiDude 7cf129f76c delivery: retain bounded protocol and cancellation ownership 2026-09-08 20:00:35 -06:00
DeFiDude d7da7f34aa ci: qualify LXMF against the current protocol source graph 2026-09-05 22:48:21 -06:00
DeFiDude e609864d88 build: synchronize existing runtime zeroize dependency in lockfile 2026-09-05 19:29:00 -06:00
DeFiDude e210e0c244 lxmd: exit cleanly during early shutdown 2026-08-26 20:55:38 -06:00
DeFiDude fc1c99d3ff docs: promote RNS 1.4.2 release baseline 2026-08-26 20:48:14 -06:00
DeFiDude e49a8b3d88 api: review link timing additions 2026-08-21 03:03:52 -06:00
DeFiDude 2ab8fdf22b link: align establishment timing with first hop 2026-08-21 00:31:18 -06:00
DeFiDude eac0feaced router: add owned persistence snapshots 2026-08-20 17:56:21 -06:00
DeFiDude a446ee21b6 release: keep maintainer policy internal 2026-08-17 17:08:36 -06:00
DeFiDude b2aab6940d api: organize compatibility evidence 2026-08-17 16:48:42 -06:00
36 changed files with 5177 additions and 1321 deletions

No files matched your search

+4 -4
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: dc6bc4ee82daf66b3b40386f9777dbe62b08fec2
RSLXMF_RSRETICULUM_COMMIT: 0f8731bb5b13e7f60e2d4bb38022480210009690
jobs:
api-compat:
@@ -47,7 +47,7 @@ jobs:
run: python3 tools/check-api-compatibility.py
working-directory: rsLXMF
- name: Check canonical and legacy external consumer
run: cargo check --manifest-path api-fixtures/Cargo.toml --locked
run: cargo check --manifest-path api/fixtures/Cargo.toml --locked
working-directory: rsLXMF
test:
@@ -119,7 +119,7 @@ jobs:
working-directory: rsLXMF
msrv:
name: Rust 1.87 MSRV
name: Rust 1.89 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
@@ -133,7 +133,7 @@ jobs:
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.87.0
toolchain: 1.89.0
components: clippy
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
+5 -5
View File
@@ -17,8 +17,8 @@ env:
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsLXMF
LXMF_BINS: lxmd-rs
RSLXMF_RSRETICULUM_VERSION: 1.2.0
RSLXMF_RSRETICULUM_COMMIT: dc6bc4ee82daf66b3b40386f9777dbe62b08fec2
RSLXMF_RSRETICULUM_VERSION: 1.3.0
RSLXMF_RSRETICULUM_COMMIT: 5edb8f22f5d8e6b2bd7392dc06e255ead96576fb
jobs:
verify:
@@ -38,7 +38,7 @@ jobs:
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.87.0
toolchain: 1.89.0
- name: Verify release source and dependency
working-directory: rsLXMF
run: python3 scripts/ci/check_source_release_contract.py --release-tag "${RELEASE_TAG}"
@@ -75,7 +75,7 @@ jobs:
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.87.0
toolchain: 1.89.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
@@ -98,7 +98,7 @@ jobs:
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
fi
done
cp README.md LICENSE CHANGELOG.md RELEASING.md "dist/${PACKAGE_ROOT}/"
cp README.md LICENSE CHANGELOG.md "dist/${PACKAGE_ROOT}/"
- name: Create tar archive
if: runner.os != 'Windows'
shell: bash
+3 -1
View File
@@ -1,5 +1,7 @@
/target/
/api-fixtures/target/
/api/fixtures/target/
*.swp
.DS_Store
__pycache__/
*.pyc
proptest-regressions/
-56
View File
@@ -1,56 +0,0 @@
# API stability
rsLXMF is currently source-distributed with `publish = false`. The current
Rust module tree is useful to source consumers, but only part of it is an
intentional long-term library boundary.
`api-stability.json` classifies every library package and pins the exact
pre-boundary commit. `api-baseline/*.txt` contains the complete explicit public
surface observed by pinned `cargo-public-api` and rustdoc versions. CI rejects
unreviewed drift. These snapshots are compatibility evidence, not a promise
that every listed state-machine field or helper will remain public forever.
`lxmf-core` is **candidate stable** as a package. Its message, presentation,
ticket, routing, propagation, sync, and public delivery concepts are intended
consumer capabilities. Its current modules also expose handler plumbing,
persistence representations, admission machinery, Link-delivery state, and
other orchestration details that remain provisional until the API-boundary
checkpoint. `lxmf-tools` is **tool internal** and exists to support `lxmd-rs`;
it is not a library compatibility commitment.
[`lxmf_core::message_api`](MESSAGE_API.md) is the canonical candidate message
path. It re-exports existing identities without adaptation, and the original
module paths remain supported. Router, delivery, propagation, handler, and
persistence ownership are not promoted by this narrow facade.
No visibility, signature, serialization, wire, persistence, or runtime change
is made by establishing this baseline. Any later boundary reduction must first
show the public API diff, migrate Ratspeak and other first-party users, preserve
the supported facade, and make an explicit version/changelog decision.
The canonical snapshot uses all features on `aarch64-apple-darwin` and omits
auto-derived, auto-trait, and blanket implementations. Other target overlays
remain covered by existing build and interop gates rather than this first
host API snapshot.
```sh
cargo install cargo-public-api --version 0.52.0 --locked
rustup toolchain install nightly-2026-08-01 --profile minimal
python3 tools/check-api-baseline.py
python3 tools/check-api-manifest.py
python3 tools/check-api-compatibility.py
cargo check --manifest-path api-fixtures/Cargo.toml --locked
```
The immutable floor and current captured snapshot source are separate
identities in `api-stability.json`. A capture names its clean basis commit and
reviewed change record; CI renders the current tree and requires a byte-exact
snapshot, avoiding an impossible self-referential commit identifier. The
manifest contract covers features,
targets, MSRV, and non-development dependencies that one Apple/all-feature API
view cannot prove. The compatibility check currently rejects every removal
from the Wave C floor; it complements rather than replaces feature, platform,
wire, persistence, and interoperability evidence.
Run with `--update` only after reviewing and recording the compatibility
impact; refreshing a snapshot is never a substitute for that review.
+19
View File
@@ -2,6 +2,25 @@
## Unreleased
### Added
- Added delivery readiness hooks so applications can react promptly to incoming Link traffic and local send completion.
- Added support for updating pending Direct-message compression as peer capabilities become known.
### Fixed and improved
- Kept active attachment transfers alive while data is moving and reduced delays between delivery steps.
- Corrected progress reporting for transfers split across multiple Resources by weighting each part by its payload size.
- Fixed intermittent propagation-node sync and unpeer failures caused by incorrectly encoded peer addresses.
### Build and compatibility
- Raised the host source-build minimum to Rust 1.89 and qualified the corresponding protocol dependency update.
- Restricted rsReticulum compatibility to the 1.3 patch line so a later breaking minor release requires an explicit update.
- Updated the Python interoperability baseline to Reticulum 1.4.2 and LXMF 1.0.1, with separate LXMF 1.1.0 checks.
## 1.2.0 - 2026-08-17
- Added the exact-reexport `lxmf_core::message_api` facade, a compiled message
Generated
+12 -10
View File
@@ -717,9 +717,9 @@ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mio"
version = "1.2.0"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
"wasi",
@@ -1052,7 +1052,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"aes",
"cbc",
@@ -1070,7 +1070,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1088,7 +1088,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -1096,6 +1096,7 @@ dependencies = [
"jni",
"libc",
"md-5",
"mio",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
@@ -1116,7 +1117,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1131,7 +1132,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"bzip2",
"hex",
@@ -1147,7 +1148,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -1169,11 +1170,12 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"zeroize",
]
[[package]]
name = "rns-transport"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -1192,7 +1194,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"rns-crypto",
"sha2",
+9 -9
View File
@@ -9,18 +9,18 @@ members = [
version = "1.2.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.87"
rust-version = "1.89"
[workspace.dependencies]
# Reticulum crates from a sibling rsReticulum checkout during development.
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.2.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.2.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.2.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.2.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.2.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.2.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.2.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.2.0" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.3.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.3.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.3.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.3.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.3.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.3.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.3.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.3.0" }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core", version = "1.2.0" }
-20
View File
@@ -1,20 +0,0 @@
# LXMF message API
`lxmf_core::message_api` is the canonical application path for constructing
and inspecting LXMF message values. It contains exact re-exports of the
existing message, status, and identifier identities; all module-qualified
paths remain supported.
The compiled `lxmf-core` `message` example demonstrates construction, signing,
packing, and unpacking. Its imports are the facade conformance contract.
This first boundary is deliberately narrower than an LXMF router facade.
`LxmRouter`, delivery ownership, propagation clients/nodes, handlers,
persistence, and raw Reticulum transport channels remain provisional,
module-qualified orchestration APIs. The facade does not alter wire fields,
signatures, serialization, delivery methods, proofs, or persistence.
Compatibility is checked by the reviewed API snapshot, the manifest/feature
contract, an additions-only comparison with the immutable Wave C floor, and an
external crate that compiles both canonical and retained imports. Platform,
wire, persistence, and Python interoperability gates remain separate evidence.
+7 -7
View File
@@ -5,7 +5,7 @@
**Rust LXMF messaging and propagation for Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.87+](https://img.shields.io/badge/rust-1.87%2B-orange.svg)](https://www.rust-lang.org)
[![Rust 1.89+](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org)
[![Compatibility floor: LXMF 1.0.1](https://img.shields.io/badge/compatibility%20floor-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![Current reference: LXMF 1.1.0](https://img.shields.io/badge/current%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
@@ -27,7 +27,7 @@ LXMF daemons on `PATH` without worry.
## Contents
- [Build It](#build-it)
- [Message API](MESSAGE_API.md)
- [Rust API](api/README.md)
- [Operating lxmd-rs](#operating-lxmd-rs)
- [Configuration](#configuration)
- [Delivery Model](#delivery-model)
@@ -342,11 +342,11 @@ Most daemon and control flags are implemented: `--config`, `--rnsconfig`,
Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`,
`--send-timeout-secs`, and `--send-fields-json`.
The compatibility-floor corpus is Python LXMF 1.0.1 with Reticulum 1.3.8;
current daemon, delivery, Resource/proof, and propagation behavior is also
checked against exact LXMF 1.1.0 and Reticulum 1.4.2 sources. Version-specific
legacy vectors retain their original provenance instead of being silently
rewritten to current expectations.
The complete release-baseline corpus and live matrix use Python LXMF 1.0.1
with Reticulum 1.4.2. A supplementary lane checks daemon, delivery,
Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the
same Reticulum 1.4.2 source. Historical vectors retain their original
provenance, and RNS 1.5.0 is intentionally deferred.
## Contributing
-28
View File
@@ -1,28 +0,0 @@
# Source release policy
rsLXMF source releases are built from immutable Git history. A release is
identified by an annotated `vX.Y.Z` tag whose version matches the workspace
package version and a dated `X.Y.Z` section in `CHANGELOG.md`.
Before creating a tag:
1. Move the relevant `Unreleased` changelog entries into a dated version
section.
2. Set the workspace version to that same semantic version and keep the
declared rsReticulum compatibility version accurate.
3. Record the exact rsReticulum commit used by the release workflow. The
compatibility version describes the manifest contract; the commit is the
source actually built and must be proven in an isolated sibling checkout.
4. Run `python3 scripts/ci/check_source_release_contract.py` and the normal CI
suite with the committed `Cargo.lock`.
5. Create the tag only after the release commit is final. Published tags are
immutable and must not be retargeted.
The release workflow checks out the requested existing tag, verifies that the
tag, manifest, changelog, dependency checkout, and release commit agree, and
builds with `--locked` on Rust 1.87.0. Release artifacts include this policy
and the changelog alongside the README and license.
All workspace packages are intentionally marked `publish = false`. Changing
that safeguard requires a separate package-distribution decision; a source
release does not change it.
-34
View File
@@ -1,34 +0,0 @@
{
"schemaVersion": 1,
"snapshotSourceCommit": "c934ccc5feaaddb55461404094ed6bb514aae2cc",
"capabilities": ["LXMF-01"],
"canonicalPath": "lxmf_core::message_api",
"retainedPaths": [
"lxmf_core::message",
"lxmf_core::constants",
"lxmf_core::types"
],
"internalSpiExcluded": [
"router",
"delivery ownership",
"propagation",
"handlers",
"persistence",
"raw Reticulum transport channels"
],
"classification": "additive-minor",
"publicApiDiff": {"added": 70, "removed": 0},
"semver": "compatible additive facade; version selection is deferred to Wave D",
"deprecations": "none",
"wirePersistenceRuntimeImpact": "none; exact re-exports only",
"consumers": [
"Ratspeak messaging",
"external canonical fixture",
"retained legacy fixture"
],
"platformEvidence": [
"host example/test/clippy/rustdoc",
"Rust 1.87 external fixture",
"downstream product target gates at dependency handoff"
]
}
-46
View File
@@ -1,46 +0,0 @@
{
"schemaVersion": 1,
"tool": {
"name": "cargo-public-api",
"version": "0.52.0",
"rustdocToolchain": "nightly-2026-08-01",
"target": "aarch64-apple-darwin",
"arguments": [
"--all-features",
"-sss"
]
},
"baseline": {
"commit": "b8d7afce73f7f098706029361568e63f22888ea3",
"capturedOn": "2026-08-17"
},
"compatibilityFloor": {
"evidenceCommit": "80bb96f799330e28a0125367d4c29826f5147cc3",
"sourceCommit": "b8d7afce73f7f098706029361568e63f22888ea3"
},
"snapshotSource": {
"commit": "c934ccc5feaaddb55461404094ed6bb514aae2cc",
"capturedOn": "2026-08-17",
"changeRecord": "api-reviews/wave-c-message-api.json"
},
"packages": [
{
"name": "lxmf-core",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api-baseline/lxmf-core.txt",
"itemCount": 1622,
"sha256": "c958cfdcb53117b02d1dbe907af6afaf5017d5ba92364267e21d204fe5ef3023"
},
{
"name": "lxmf-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api-baseline/lxmf-tools.txt",
"itemCount": 185,
"sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924"
}
]
}
+114
View File
@@ -0,0 +1,114 @@
# Rust API
Application code that constructs or inspects LXMF messages should use
`lxmf_core::message_api`. It re-exports the existing message, status, and
identifier types without wrapping or replacing them. The original
module-qualified paths remain supported.
The compiled `lxmf-core` `message` example demonstrates message construction,
signing, packing, and unpacking through this path.
## Stability
`lxmf-core` is candidate stable, but that classification does not make every
public implementation detail a permanent API. The message facade is the
recommended application path. Router ownership, delivery orchestration,
propagation clients and nodes, handlers, persistence representations,
admission machinery, Link-delivery state, and raw Reticulum channels remain
provisional module-qualified APIs.
`lxmf-tools` supports the `lxmd-rs` binary and is not a public library
integration target.
The message facade changes no wire fields, signatures, serialization,
delivery methods, proofs, persistence, or runtime behavior. Later reductions
to the broader module tree require a reviewed API diff, downstream migration,
and an explicit version decision.
## Delivery-owner integration
`LinkDeliveryManager::poll_ready` lets one embedding task wait for inbound
delivery packets, local admission acknowledgements, endpoint lifecycle changes,
and staged-transport capacity. On readiness, call `drain_events` and `tick`.
Keep periodic ticks for protocol deadlines, but schedule application maintenance
separately. Drains are bounded and may leave another ready turn. Cancelling the
wait does not discard a packet or publish an unread endpoint binding; existing
periodic consumers remain supported. The API is provisional delivery-owner
integration (LXMF-02/03, RET-05/07), not a new wire protocol or success signal.
`LinkDeliveryManager::set_link_endpoint_dispatch_handle` opts Direct packet
sends into the Reticulum owner's exact local-admission receipts. Supply the
handle from the same runtime that owns the manager's transport channel.
Local FIFO residence and the subsequent measured-RTT proof wait are different
phases; neither is a recipient delivery confirmation.
Applications using responder-owned backchannels should forward the ordered
`LinkManagerAccountingEvent` packet and Resource wait observations through
`observe_backchannel_packet_wait` and `observe_backchannel_resource_wait`,
retaining the exact packet/resource identity and original timestamps.
Forward the optional exact packet-cancellation capability with its original
wait observation as well. A separate application owner can then cancel a
packet still awaiting local admission without closing the shared Link. This
cannot retract driver-admitted bytes. When a command receipt cannot be
published to its message owner, retain its exact identity for bounded cleanup;
close and drain a oneshot receiver before discarding it to fence concurrent
publication.
Adapters implementing that close-and-drain protocol can install their sender
with `set_cancellation_aware_backchannel_sender`, allowing cancellation before
the command receipt arrives to notify the adapter immediately. The existing
`set_backchannel_sender` retains legacy receipt-after-cancellation behavior.
Each pending send captures its adapter policy; replacing a sender does not
retroactively change cancellation semantics for older sends.
`message_timeout_window` exposes the finite current owner window for an outer
orphan watchdog. Externally observed Resource windows include a bounded
180-second notification allowance measured from the original protocol deadline;
this does not alter the Resource engine's timeout or delay explicit terminal
events. It is not renewed by receiving the same observation or by keepalives.
Queued messages without an active protocol owner receive no
blanket timeout exemption. Explicit rejection and cancellation are not evidence
of a failed route.
When an authenticated recipient announcement rules out compression, call
`LinkDeliveryManager::disable_pending_direct_compression` before advancing
ready delivery events. It updates unconstructed Direct Resources and queued
messages, including Link setup waits. Constructed Resources and split plans
remain immutable, and propagation envelopes keep their independent policy.
The call only disables compression; new submissions still carry their policy.
This additive API remains provisional delivery-owner integration.
Applications that reserve inbound attachment memory can opt into
`set_inbound_resource_completion_handler`. It receives one owned completed
payload before the ordinary conclusion callback, so an application can move
its exact Link/Resource reservation into a queued payload and retain it through
processing. This synchronous callback must not block. It replaces the legacy
inbound packet-channel delivery for that Resource, without cloning the data;
applications that do not install it keep the existing completion behavior.
## Compatibility checks
The `api/` directory contains the evidence used by CI:
- `stability.json` records package tiers, source commits, snapshot hashes, and
the current review decision;
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
manifest, feature, dependency, target, and MSRV contract; and
- `fixtures/` compiles recommended and retained imports as an external
consumer.
These checks catch accidental changes, but they do not replace platform builds,
wire and persistence tests, Python interoperability, or manual review. The API
snapshot omits auto-derived, auto-trait, and blanket implementations and is not
by itself a complete SemVer verdict.
Run the checks with:
```sh
python3 tools/check-api-baseline.py
python3 tools/check-api-manifest.py
python3 tools/check-api-compatibility.py
cargo check --manifest-path api/fixtures/Cargo.toml --locked
```
Snapshot updates require a clean source commit and an explicit review recorded
in `api/stability.json`. Additions, removals, deprecations, platform impact, and
version consequences must be reviewed before accepting new evidence.
+8 -8
View File
@@ -319,9 +319,9 @@ dependencies = [
[[package]]
name = "mio"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
"wasi",
@@ -478,7 +478,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"aes",
"cbc",
@@ -496,7 +496,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"hex",
"rand",
@@ -514,7 +514,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"hex",
"rand",
@@ -529,7 +529,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"bzip2",
"hex",
@@ -545,7 +545,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -564,7 +564,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"rns-crypto",
"sha2",
@@ -7,4 +7,4 @@ publish = false
[workspace]
[dependencies]
lxmf-core = { path = "../crates/lxmf-core" }
lxmf-core = { path = "../../crates/lxmf-core" }
@@ -40,3 +40,20 @@ pub mod legacy {
let _ = std::mem::size_of::<UnverifiedReason>();
}
}
/// Delivery coordination remains a module-qualified opt-in API.
pub mod delivery_ownership {
use lxmf_core::link_delivery::LinkDeliveryManager;
pub fn compile_surface(manager: &mut LinkDeliveryManager) {
let _ = LinkDeliveryManager::set_link_endpoint_dispatch_handle;
let _ = LinkDeliveryManager::set_cancellation_aware_backchannel_sender;
let _ = LinkDeliveryManager::observe_backchannel_packet_wait;
let _ = LinkDeliveryManager::observe_backchannel_resource_wait;
let _ = LinkDeliveryManager::abandon_backchannel_packet;
let _ = LinkDeliveryManager::message_timeout_window;
manager.set_inbound_resource_completion_handler(|link_id, resource_id, data| {
let _: ([u8; 16], [u8; 32], Vec<u8>) = (link_id, resource_id, data);
});
}
}
@@ -468,10 +468,12 @@ pub lxmf_core::link_delivery::DirectLinkStartReport::link_state: rns_link::link:
pub lxmf_core::link_delivery::DirectLinkStartReport::queued_deliveries: usize
pub struct lxmf_core::link_delivery::LinkDeliveryManager
impl lxmf_core::link_delivery::LinkDeliveryManager
pub fn lxmf_core::link_delivery::LinkDeliveryManager::abandon_backchannel_packet(&mut self, [u8; 16], [u8; 32]) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::backchannel_link_snapshot(&self, [u8; 16]) -> core::option::Option<lxmf_core::link_delivery::BackchannelLinkSnapshot>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::cancel_delivery_by_message_hash(&mut self, [u8; 32]) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::delivery_link_available(&self, &[u8; 16]) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::direct_link_snapshot(&self, [u8; 16]) -> core::option::Option<lxmf_core::link_delivery::DirectLinkSnapshot>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::disable_pending_direct_compression(&mut self, [u8; 16])
pub fn lxmf_core::link_delivery::LinkDeliveryManager::drain_events(&mut self, &std::collections::hash::map::HashMap<alloc::string::String, [u8; 64]>)
pub fn lxmf_core::link_delivery::LinkDeliveryManager::fail_backchannel_link(&mut self, [u8; 16], &str) -> alloc::vec::Vec<lxmf_core::link_delivery::DeliveryResult>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::fail_delivery_by_message_hash(&mut self, [u8; 32], &str) -> alloc::vec::Vec<lxmf_core::link_delivery::DeliveryResult>
@@ -485,20 +487,30 @@ pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_request(&mut self,
pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_resource_proof(&mut self, &[u8; 16], &[u8]) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_resource_reject(&mut self, &[u8; 16], &[u8]) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::message_delivery_snapshot(&self, [u8; 32]) -> core::option::Option<lxmf_core::link_delivery::MessageDeliverySnapshot>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::message_timeout_window(&self, [u8; 32]) -> core::option::Option<(std::time::Instant, core::time::Duration)>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::new(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, core::option::Option<[u8; 64]>, core::option::Option<rns_crypto::ed25519::Ed25519PrivateKey>) -> Self
pub fn lxmf_core::link_delivery::LinkDeliveryManager::observe_backchannel_packet_wait(&mut self, [u8; 16], [u8; 32], std::time::Instant, core::time::Duration, bool, core::option::Option<rns_transport::link_endpoint_dispatch::LinkEndpointDispatchCancellation>) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::observe_backchannel_resource_wait(&mut self, [u8; 16], [u8; 32], std::time::Instant, core::time::Duration) -> bool
pub fn lxmf_core::link_delivery::LinkDeliveryManager::pending_count(&self) -> usize
pub fn lxmf_core::link_delivery::LinkDeliveryManager::poll_ready(&mut self, &mut core::task::wake::Context<'_>) -> core::task::poll::Poll<()>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::register_backchannel(&mut self, [u8; 16], [u8; 16])
pub fn lxmf_core::link_delivery::LinkDeliveryManager::remove_backchannel(&mut self, &[u8; 16]) -> core::option::Option<[u8; 16]>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::session_count(&self) -> usize
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_backchannel_sender(&mut self, tokio::sync::mpsc::bounded::Sender<lxmf_core::link_delivery::BackchannelSendCommand>)
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_cancellation_aware_backchannel_sender(&mut self, tokio::sync::mpsc::bounded::Sender<lxmf_core::link_delivery::BackchannelSendCommand>)
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_inbound_packet_sender(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>)
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_inbound_resource_accept_handler<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], &rns_protocol::resource_adv::ResourceAdvertisement) -> bool + core::marker::Send + core::marker::Sync + 'static
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_inbound_resource_completion_handler<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 32], alloc::vec::Vec<u8>) + core::marker::Send + core::marker::Sync + 'static
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_inbound_resource_concluded_handler<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 32]) + core::marker::Send + core::marker::Sync + 'static
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_inbound_resource_limit_bytes(&mut self, usize)
pub fn lxmf_core::link_delivery::LinkDeliveryManager::set_link_endpoint_dispatch_handle(&mut self, rns_transport::link_endpoint_dispatch::LinkEndpointDispatchHandle)
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_backchannel_delivery(&mut self, lxmf_core::message::LxMessage, [u8; 16]) -> core::result::Result<lxmf_core::link_delivery::BackchannelStartReport, lxmf_core::link_delivery::BackchannelStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_delivery(&mut self, lxmf_core::message::LxMessage, [u8; 16], u8) -> core::result::Result<[u8; 16], lxmf_core::link_delivery::LinkDeliveryStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_delivery_with_report(&mut self, lxmf_core::message::LxMessage, [u8; 16], u8) -> core::result::Result<lxmf_core::link_delivery::DirectLinkStartReport, lxmf_core::link_delivery::LinkDeliveryStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_delivery_with_report_and_timing(&mut self, lxmf_core::message::LxMessage, [u8; 16], u8, lxmf_core::link_delivery::LinkEstablishmentTiming) -> core::result::Result<lxmf_core::link_delivery::DirectLinkStartReport, lxmf_core::link_delivery::LinkDeliveryStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_delivery_with_timing(&mut self, lxmf_core::message::LxMessage, [u8; 16], u8, lxmf_core::link_delivery::LinkEstablishmentTiming) -> core::result::Result<[u8; 16], lxmf_core::link_delivery::LinkDeliveryStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_packed_delivery(&mut self, lxmf_core::message::LxMessage, [u8; 16], u8, alloc::vec::Vec<u8>, bool) -> core::result::Result<[u8; 16], lxmf_core::link_delivery::LinkDeliveryStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::start_packed_delivery_with_timing(&mut self, lxmf_core::message::LxMessage, [u8; 16], u8, alloc::vec::Vec<u8>, bool, lxmf_core::link_delivery::LinkEstablishmentTiming) -> core::result::Result<[u8; 16], lxmf_core::link_delivery::LinkDeliveryStartFailure>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::stats(&self) -> lxmf_core::link_delivery::LinkDeliveryStats
pub fn lxmf_core::link_delivery::LinkDeliveryManager::take_backchannel_resource_cancellations(&mut self) -> alloc::vec::Vec<lxmf_core::link_delivery::BackchannelResourceCancelRequest>
pub fn lxmf_core::link_delivery::LinkDeliveryManager::take_delivery_events(&mut self) -> alloc::vec::Vec<lxmf_core::link_delivery::LxmfDeliveryEvent>
@@ -521,6 +533,15 @@ pub lxmf_core::link_delivery::LinkDeliveryStats::pending_backchannel_deliveries:
pub lxmf_core::link_delivery::LinkDeliveryStats::pending_backchannel_starts: usize
pub lxmf_core::link_delivery::LinkDeliveryStats::queued_deliveries: usize
pub lxmf_core::link_delivery::LinkDeliveryStats::sessions: usize
pub struct lxmf_core::link_delivery::LinkEstablishmentTiming
impl lxmf_core::link_delivery::LinkEstablishmentTiming
pub const fn lxmf_core::link_delivery::LinkEstablishmentTiming::first_hop_timeout(self) -> core::time::Duration
pub fn lxmf_core::link_delivery::LinkEstablishmentTiming::from_first_hop_bitrate(u64) -> Self
pub fn lxmf_core::link_delivery::LinkEstablishmentTiming::from_first_hop_bitrate_and_mtu(u64, u32) -> Self
pub const fn lxmf_core::link_delivery::LinkEstablishmentTiming::from_first_hop_timeout(core::time::Duration) -> Self
pub fn lxmf_core::link_delivery::LinkEstablishmentTiming::timeout_for_hops(self, u8) -> core::time::Duration
impl core::default::Default for lxmf_core::link_delivery::LinkEstablishmentTiming
pub fn lxmf_core::link_delivery::LinkEstablishmentTiming::default() -> Self
pub struct lxmf_core::link_delivery::LxmfDeliveryEvent
pub lxmf_core::link_delivery::LxmfDeliveryEvent::attempts: u32
pub lxmf_core::link_delivery::LxmfDeliveryEvent::delivery_state: lxmf_core::link_delivery::DeliveryState
@@ -1414,6 +1435,7 @@ pub fn lxmf_core::router::LxmRouter::set_retain_node_lxms(&mut self, bool)
pub fn lxmf_core::router::LxmRouter::set_stamp_cost(&mut self, [u8; 16], u8)
pub fn lxmf_core::router::LxmRouter::set_stamp_requirements(&mut self, u8, u8)
pub fn lxmf_core::router::LxmRouter::set_transport(&mut self, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>)
pub fn lxmf_core::router::LxmRouter::state_snapshot(&self) -> lxmf_core::router::RouterStateSnapshot
pub fn lxmf_core::router::LxmRouter::stats(&self) -> lxmf_core::router::RouterStats
pub fn lxmf_core::router::LxmRouter::sync_peer_policies_for_store(&self, u64) -> alloc::vec::Vec<lxmf_core::peer::OutboundOfferPolicy>
pub fn lxmf_core::router::LxmRouter::sync_peers(&mut self) -> alloc::vec::Vec<[u8; 16]>
@@ -1484,6 +1506,9 @@ pub lxmf_core::router::RouterConfigExt::propagation_cost_min: u8
pub lxmf_core::router::RouterConfigExt::retain_synced_on_node: bool
impl core::default::Default for lxmf_core::router::RouterConfigExt
pub fn lxmf_core::router::RouterConfigExt::default() -> Self
pub struct lxmf_core::router::RouterStateSnapshot
impl lxmf_core::router::RouterStateSnapshot
pub fn lxmf_core::router::RouterStateSnapshot::save_state(&self, &std::path::Path) -> core::io::error::Result<()>
pub struct lxmf_core::router::RouterStats
pub lxmf_core::router::RouterStats::peers: usize
pub lxmf_core::router::RouterStats::pending_deferred_stamps: usize
File renamed without changes.
@@ -5,7 +5,7 @@
{
"name": "lxmf-core",
"version": "1.2.0",
"rustVersion": "1.87",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
"targets": [
@@ -103,7 +103,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -114,7 +114,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -125,7 +125,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -136,7 +136,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -147,7 +147,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -158,7 +158,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -239,7 +239,7 @@
{
"name": "lxmf-tools",
"version": "1.2.0",
"rustVersion": "1.87",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
"targets": [
@@ -328,7 +328,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -339,7 +339,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -350,7 +350,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [
@@ -363,7 +363,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -374,7 +374,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
+94
View File
@@ -0,0 +1,94 @@
{
"schemaVersion": 1,
"tool": {
"name": "cargo-public-api",
"version": "0.52.0",
"rustdocToolchain": "nightly-2026-08-01",
"target": "aarch64-apple-darwin",
"arguments": [
"--all-features",
"-sss"
]
},
"baseline": {
"commit": "b8d7afce73f7f098706029361568e63f22888ea3",
"capturedOn": "2026-08-17"
},
"compatibilityFloor": {
"evidenceCommit": "80bb96f799330e28a0125367d4c29826f5147cc3",
"sourceCommit": "b8d7afce73f7f098706029361568e63f22888ea3"
},
"snapshotSource": {
"commit": "98aa927e1d2da3ebcc42ebe25f635dcbb503faf7",
"capturedOn": "2026-09-24",
"review": {
"areas": [
"Exact local packet admission and proof-clock ownership",
"Finite original Resource windows and bounded external observation grace",
"Cancellation-aware backchannel adapters with legacy compatibility",
"Generation-safe cleanup, settlement and queued-message preservation",
"Owned reverse Resource completion handoff",
"LXMF-02/03 and RET-05/07 event-driven delivery readiness (September 24)",
"LXMF-02/03: late authenticated compression capability on pending Direct delivery"
],
"canonicalPath": "lxmf_core::link_delivery::LinkDeliveryManager",
"retainedPaths": [
"lxmf_core::message",
"lxmf_core::constants",
"lxmf_core::types",
"lxmf_core::router",
"lxmf_core::link_delivery"
],
"excludedImplementationAreas": [
"propagation and handlers",
"serialized persistence representations",
"raw Reticulum transport channels"
],
"classification": "compatible additive opt-in provisional delivery-owner integration; existing message facade and public signatures remain unchanged",
"publicApiDiff": {
"added": 95,
"removed": 0
},
"semver": "compatible additive APIs included in version 1.2.0",
"deprecations": "none",
"wirePersistenceRuntimeImpact": "No wire-format, cryptography, message identity or persisted-layout change. Exact local Link admission precedes RTT proof timing. Resource owner windows retain original timestamps; only externally observed Resources receive a finite 180-second accounting allowance after the original protocol deadline. Cancellation-aware adapters close and drain unpublished receipts while legacy sender installation retains its previous behavior. Exact cleanup is bounded and cannot erase replacement Links or lose uncancelled queued messages; authenticated settlement remains owned after Link closure. Optional reverse Resource completion hands off the single owned payload before conclusion cleanup, without changing legacy consumers. Authenticated no-compression announcements can now disable compression for unconstructed Direct Resources and queued payloads. Constructed Resources, split plans and propagation envelopes stay immutable; no wire fields or signatures change.",
"platformEvidence": [
"clean committed-source all-feature Apple ARM64 snapshot: seven added methods, zero removed; cumulative compatibility-floor diff is 93 additions and zero removals",
"564 LXMF core and 55 daemon tests passed on the final implementation checkpoint; strict all-target Clippy and core Rustdoc passed",
"independent actual-actor cancellation, captured legacy/aware policy, 256-owner reservation and replacement-Link/settlement review controls passed",
"actual encrypted Resource final-proof expiry and same-message retry produced one receiver publication; signed Link reuse/loss/recovery and completion-lease controls passed",
"default/all-feature external consumer fixtures and final working app runtime suite passed; no feature/MSRV/native-export changes",
"final clean combined host/MSRV/native/interop and artifact qualification remain separately required; focused software evidence is not physical fading-radio or mobile acceptance",
"September 24: additive poll_ready method; 75 focused delivery tests, encrypted 65 KB/750 KB/2.6 MB/8 MB readiness-driven transfers, and strict stable/MSRV Clippy passed. Physical radio speed remains separately qualified.",
"September 24 first-contact correction: 577 lxmf-core tests and strict all-target Clippy passed; the new API is additive provisional owner integration. Small/Micro native first-contact and full app runtime qualification are retained by the cross-repo maintainer harness."
]
}
},
"packages": [
{
"name": "lxmf-core",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 1647,
"sha256": "b7b1d52406e2c97a204a5fb567abc6a216733594a7abd63797ff55a70d8d3b73"
},
{
"name": "lxmf-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 185,
"sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924"
}
],
"deliveryReadinessReview": {
"reviewedOn": "2026-09-24",
"classification": "Compatible additive provisional integration method; no removed signatures, dependency requirement, MSRV, wire or persistence changes. No release-version bump in this implementation commit.",
"ownership": "Input and local receipt lookahead remain owned on cancellation; exact bind readiness does not publish the endpoint. One polling task; periodic deadline ticks remain required.",
"scheduling": "Bounded input drain; readiness covers packets, endpoint lifecycle/acknowledgements, backchannel receipts and staged-transport capacity. Existing lxmd-rs periodic consumers remain supported.",
"diagnostics": "Aggregate Resource request/part/repeated-part/byte action counts under a closed content-free target; dispatch is not driver admission or recipient delivery."
}
}
+1 -1
View File
@@ -1,2 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.87"
msrv = "1.89"
+21 -21
View File
@@ -159,14 +159,15 @@ impl DeliveryRatchetState {
}
}
if control_file_trusted && (!control_existed || control_changed) {
if let Err(error) = control.save_verified(&control_path, identity) {
tracing::warn!(
path = %control_path.display(),
%error,
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
);
}
if control_file_trusted
&& (!control_existed || control_changed)
&& let Err(error) = control.save_verified(&control_path, identity)
{
tracing::warn!(
path = %control_path.display(),
%error,
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
);
}
Ok(Self {
@@ -210,13 +211,12 @@ impl DeliveryRatchetState {
}
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind {
if let Some(packet) = self
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind
&& let Some(packet) = self
.destination
.cached_path_response_packet(tag, cache_now)?
{
return Ok(packet);
}
{
return Ok(packet);
}
if !self.control_file_trusted {
@@ -292,15 +292,15 @@ impl DeliveryRatchetState {
/// Best-effort shutdown checkpoint. Invalid files detected during load are
/// never overwritten by this operation.
pub fn save(&self, identity: &Identity) {
if self.ring_file_trusted {
if let Err(error) = self.ring.save_verified(&self.ring_path, identity) {
tracing::warn!(%error, "failed to save ratchet ring");
}
if self.ring_file_trusted
&& let Err(error) = self.ring.save_verified(&self.ring_path, identity)
{
tracing::warn!(%error, "failed to save ratchet ring");
}
if self.control_file_trusted {
if let Err(error) = self.control.save_verified(&self.control_path, identity) {
tracing::warn!(%error, "failed to save ratchet control state");
}
if self.control_file_trusted
&& let Err(error) = self.control.save_verified(&self.control_path, identity)
{
tracing::warn!(%error, "failed to save ratchet control state");
}
}
File diff suppressed because it is too large. Load diff
+19 -20
View File
@@ -606,19 +606,19 @@ impl LxMessage {
self.transient_id = Some(tid);
let mut stamp_value = 0;
if let Some(target_cost) = propagation_stamp_cost {
if self.propagation_stamp.is_none() {
let (stamp, value) = crate::stamper::generate_stamp(
&tid,
target_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)
.ok_or_else(|| {
MessageError::PackFailed("failed to generate propagation stamp".to_string())
})?;
self.propagation_stamp = Some(stamp);
stamp_value = value;
}
if let Some(target_cost) = propagation_stamp_cost
&& self.propagation_stamp.is_none()
{
let (stamp, value) = crate::stamper::generate_stamp(
&tid,
target_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)
.ok_or_else(|| {
MessageError::PackFailed("failed to generate propagation stamp".to_string())
})?;
self.propagation_stamp = Some(stamp);
stamp_value = value;
}
if let Some(ref prop_stamp) = self.propagation_stamp {
@@ -1008,14 +1008,13 @@ impl LxMessage {
// 4. Generate PoW stamp
let cost = self.stamp_cost.unwrap();
if let Some(message_id) = self.message_id {
if let Some((stamp, value)) =
if let Some(message_id) = self.message_id
&& let Some((stamp, value)) =
crate::stamper::generate_stamp(&message_id, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS)
{
self.stamp_value = Some(value as u16);
self.stamp = Some(stamp.to_vec());
return Some(stamp.to_vec());
}
{
self.stamp_value = Some(value as u16);
self.stamp = Some(stamp.to_vec());
return Some(stamp.to_vec());
}
None
+9 -8
View File
@@ -68,14 +68,15 @@ pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
fs::rename(&tmp, path)
})();
if result.is_err() && tmp.exists() {
if let Err(e) = fs::remove_file(&tmp) {
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
}
if result.is_err()
&& tmp.exists()
&& let Err(e) = fs::remove_file(&tmp)
{
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
}
result
+79 -82
View File
@@ -620,30 +620,28 @@ impl PropagationClient {
continue;
}
let node_hex = self.outbound_propagation_node.map(|h| hex_encode(&h));
if let Some(node_hex) = node_hex {
if let Some(pub_key) = known_identities.get(&node_hex) {
let ed25519_bytes: [u8; 32] = pub_key[32..64]
if let Some(node_hex) = node_hex
&& let Some(pub_key) = known_identities.get(&node_hex)
{
let ed25519_bytes: [u8; 32] = pub_key[32..64]
.try_into()
.expect("known_identities values are [u8; 64]; slice [32..64] is always 32 bytes");
if let Ok(verify_key) =
Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(
data,
&verify_key,
&ed25519_bytes,
interface_id,
);
}
if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(
data,
&verify_key,
&ed25519_bytes,
interface_id,
);
}
}
}
rns_wire::context::PacketContext::Response => {
if let Some(ref mut link) = self.link {
if let Ok((_request_id, response_data)) = link.handle_response(data)
{
self.handle_response_data(&response_data);
}
if let Some(ref mut link) = self.link
&& let Ok((_request_id, response_data)) = link.handle_response(data)
{
self.handle_response_data(&response_data);
}
}
rns_wire::context::PacketContext::ResourceAdv => {
@@ -709,47 +707,47 @@ impl PropagationClient {
None => return,
};
if let Ok(rtt_data) = link.validate_proof(proof_data, verify_key, ed25519_pub) {
if let Some(link_id) = self.link_id {
let rtt_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Lrrtt,
};
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
if let Ok(rtt_data) = link.validate_proof(proof_data, verify_key, ed25519_pub)
&& let Some(link_id) = self.link_id
{
let rtt_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Lrrtt,
};
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
let rtt_request = OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
link_id,
interface_id,
role: LinkEndpointRole::Initiator,
},
lifecycle_tx: self.endpoint_lifecycle_tx.clone(),
result_tx,
}) {
self.status.state = PropagationClientState::Failed;
return;
}
self.pending_endpoint_bind = Some(PendingEndpointBind {
let rtt_request = OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
link_id,
interface_id,
rtt_request,
result_rx,
});
role: LinkEndpointRole::Initiator,
},
lifecycle_tx: self.endpoint_lifecycle_tx.clone(),
result_tx,
}) {
self.status.state = PropagationClientState::Failed;
return;
}
self.pending_endpoint_bind = Some(PendingEndpointBind {
interface_id,
rtt_request,
result_rx,
});
}
}
@@ -1206,10 +1204,10 @@ impl PropagationClient {
if let Some(arr) = value.as_array() {
self.available_messages.clear();
for item in arr {
if let Some(id_bytes) = item.as_slice() {
if id_bytes.len() == 32 {
self.available_messages.push(id_bytes.to_vec());
}
if let Some(id_bytes) = item.as_slice()
&& id_bytes.len() == 32
{
self.available_messages.push(id_bytes.to_vec());
}
}
@@ -1272,20 +1270,19 @@ impl PropagationClient {
return;
}
if let Some(started) = self.started_at {
if started.elapsed() > self.timeout
&& matches!(
self.status.state,
PropagationClientState::LinkEstablishing
| PropagationClientState::ListRequested
| PropagationClientState::GetRequested
| PropagationClientState::PurgeRequested
)
{
self.cleanup();
self.status.state = PropagationClientState::Failed;
return;
}
if let Some(started) = self.started_at
&& started.elapsed() > self.timeout
&& matches!(
self.status.state,
PropagationClientState::LinkEstablishing
| PropagationClientState::ListRequested
| PropagationClientState::GetRequested
| PropagationClientState::PurgeRequested
)
{
self.cleanup();
self.status.state = PropagationClientState::Failed;
return;
}
let link_action = self.link.as_mut().map(Link::tick);
@@ -1384,10 +1381,10 @@ impl PropagationClient {
} else {
None
};
if let Some(outbound) = outbound {
if !self.queue_link_endpoint(outbound) {
self.status.state = PropagationClientState::Failed;
}
if let Some(outbound) = outbound
&& !self.queue_link_endpoint(outbound)
{
self.status.state = PropagationClientState::Failed;
}
}
@@ -1539,10 +1536,10 @@ impl PropagationClient {
fn cleanup(&mut self) {
let graceful_release = self.endpoint_release_queued || self.send_teardown();
if let Some(link_id) = self.link_id.take() {
if !graceful_release {
self.queue_endpoint_cleanup(link_id);
}
if let Some(link_id) = self.link_id.take()
&& !graceful_release
{
self.queue_endpoint_cleanup(link_id);
}
self.attached_interface = None;
self.endpoint_release_queued = false;
+173 -35
View File
@@ -254,12 +254,11 @@ pub(crate) fn prepare_sync_offer_snapshot(
.propagation_sync_limit
.map(kilobytes_to_bytes_fail_closed);
let mut handled_messages = snapshot.policy.handled_messages.clone();
if let Some(path) = snapshot.peer_path.as_ref() {
if let Ok(data) = std::fs::read(path) {
if let Some(peer) = LxmPeer::from_bytes_with_handled(&data) {
handled_messages.extend(peer.handled_messages);
}
}
if let Some(path) = snapshot.peer_path.as_ref()
&& let Ok(data) = std::fs::read(path)
&& let Some(peer) = LxmPeer::from_bytes_with_handled(&data)
{
handled_messages.extend(peer.handled_messages);
}
let mut candidates = snapshot.candidates;
@@ -745,6 +744,17 @@ impl PropagationNode {
PropagationEntry::new_stamped(tid, message_hash, destination_hash, size, sv);
pe.stored_at = ts;
// Older app hosts persisted opaque blobs without their PN
// stamp. Their filename TID hashes the entire file, whereas
// canonical stamped storage hashes the file before its final
// 32-byte stamp. Recover that exact legacy representation so
// client /get cannot truncate ciphertext after a restart.
// This distinguishes storage format, not stamp authenticity;
// retain the existing policy for other opaque/malformed files.
if data.len() > DESTINATION_LENGTH && message_hash == tid {
pe.stamped = false;
}
if let Ok(msg) = LxMessage::unpack(&data) {
pe.message_hash = msg.hash.unwrap_or([0u8; 32]);
pe.destination_hash = msg.destination_hash;
@@ -781,10 +791,10 @@ impl PropagationNode {
self.advance_offer_generation();
}
if before > after {
if let Some(ref dir) = self.storage_path {
self.cleanup_orphaned_files(dir);
}
if before > after
&& let Some(ref dir) = self.storage_path
{
self.cleanup_orphaned_files(dir);
}
}
@@ -802,10 +812,10 @@ impl PropagationNode {
if filename.ends_with(".peer") || filename.ends_with(".msgpack") {
continue;
}
if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename) {
if !self.store.contains(&tid) {
let _ = std::fs::remove_file(&path);
}
if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename)
&& !self.store.contains(&tid)
{
let _ = std::fs::remove_file(&path);
}
}
}
@@ -1105,16 +1115,15 @@ impl PropagationNode {
for want_val in wants_arr {
if let (Some(tid), Some(dir)) =
(parse_store_id(want_val), self.storage_path.as_ref())
&& let Some(entry) = self.store.get(&tid)
{
if let Some(entry) = self.store.get(&tid) {
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
if entry.destination_hash == *client_dest_hash {
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
}
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
if entry.destination_hash == *client_dest_hash {
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
}
}
}
@@ -1277,11 +1286,10 @@ impl PropagationNode {
// Compatibility wrapper: production uses the staged task
// path and exposes this delta to the daemon for off-loop
// persistence.
if !terminal_handled_ids.is_empty() {
if let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids)
{
tracing::warn!(%error, "failed to persist terminal offer dispositions");
}
if !terminal_handled_ids.is_empty()
&& let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids)
{
tracing::warn!(%error, "failed to persist terminal offer dispositions");
}
return offer;
}
@@ -1395,13 +1403,12 @@ impl PropagationNode {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map(|e| e == "peer").unwrap_or(false) {
if let Ok(data) = std::fs::read(&path) {
if let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data) {
self.prune_handled_against_store(&mut peer);
peers.push(peer);
}
}
if path.extension().map(|e| e == "peer").unwrap_or(false)
&& let Ok(data) = std::fs::read(&path)
&& let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data)
{
self.prune_handled_against_store(&mut peer);
peers.push(peer);
}
}
}
@@ -2840,9 +2847,140 @@ mod tests {
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(value.as_array().unwrap().len(), 1);
let full_id = rns_crypto::sha::full_hash(&lxmf_data);
let get_request = Value::Array(vec![
Value::Array(vec![Value::Binary(full_id.to_vec())]),
Value::Array(vec![]),
]);
let mut get_buf = Vec::new();
rmpv::encode::write_value(&mut get_buf, &get_request).unwrap();
let response = reloaded
.handle_get_request(&get_buf, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(
value.as_array().unwrap()[0].as_slice().unwrap(),
lxmf_data.as_slice(),
"legacy opaque blobs have no stamp to strip after restart"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_opaque_blob_reload_preserves_bytes_and_accounting_at_minimum_lengths() {
use rmpv::Value;
// These are storage-format controls, not authenticated ciphertext or
// stamp-validation tests. Retain the existing public ingress minimum.
for stamped in [false, true] {
for len in [17, 31, 32, 33, 48, 49, 144] {
let dir = tempfile::tempdir().unwrap();
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert!(!node.accept_propagated_blob(&[0xBB; 16], 0));
assert!(!node.accept_stamped_propagated_blob(&[0xBB; 16], &[0; 32], 0));
assert_eq!(node.message_count(), 0);
let mut blob = vec![0xBB; 16];
blob.resize(len, 0xCC);
let stamp = [0x5A; 32];
let full_id = rns_crypto::sha::full_hash(&blob);
let mut stored = blob.clone();
if stamped {
stored.extend_from_slice(&stamp);
assert!(node.accept_stamped_propagated_blob(&blob, &stamp, 0));
} else {
assert!(node.accept_propagated_blob(&blob, 0));
}
assert_eq!(node.total_size(), stored.len());
let path = dir
.path()
.join(node.store.get(&full_id).unwrap().filename());
assert_eq!(std::fs::read(&path).unwrap(), stored);
drop(node);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert_eq!(node.message_count(), 1);
assert_eq!(node.total_size(), stored.len());
assert_eq!(node.store.get(&full_id).unwrap().stamped, stamped);
// Duplicate admission must neither replace the known format
// nor grow the byte/accounting reservation after reload.
assert!(!node.accept_propagated_blob(&blob, 0));
assert!(!node.accept_stamped_propagated_blob(&blob, &stamp, 0));
assert_eq!(node.message_count(), 1);
assert_eq!(node.total_size(), stored.len());
assert!(node.pending_write_ids.is_empty());
assert_eq!(node.pending_write_bytes, 0);
let get = Value::Array(vec![
Value::Array(vec![Value::Binary(full_id.to_vec())]),
Value::Array(vec![]),
]);
let mut request = Vec::new();
rmpv::encode::write_value(&mut request, &get).unwrap();
let response = node
.handle_get_request(&request, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
let messages = value.as_array().unwrap();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0].as_slice().unwrap(), blob);
assert_eq!(
node.message_get_request(&[full_id]),
vec![(full_id, stored.clone())]
);
assert_eq!(std::fs::read(&path).unwrap(), stored);
}
}
}
#[test]
fn test_reloaded_legacy_message_keeps_original_get_bytes() {
use rmpv::Value;
let dir = tempfile::tempdir().unwrap();
let message = make_signed_message([0xBB; 16], [0xCC; 16], "legacy", "full message");
let packed = message.pack().unwrap();
let full_id = message.transient_id.or(message.hash).unwrap();
assert_ne!(full_id, rns_crypto::sha::full_hash(&packed));
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert!(node.accept_message(&message));
drop(node);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert_eq!(node.message_count(), 1);
assert_eq!(node.total_size(), packed.len());
assert!(!node.store.get(&full_id).unwrap().stamped);
let get = Value::Array(vec![
Value::Array(vec![Value::Binary(full_id.to_vec())]),
Value::Array(vec![]),
]);
let mut request = Vec::new();
rmpv::encode::write_value(&mut request, &get).unwrap();
let response = node
.handle_get_request(&request, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(value.as_array().unwrap()[0].as_slice().unwrap(), packed);
}
#[test]
fn test_handle_get_request_purge_phase() {
let dir = std::env::temp_dir().join("lxmf_test_get_purge");
+75 -83
View File
@@ -718,30 +718,27 @@ impl PropagationSyncTask {
continue;
}
let node_hex = self.node_dest_hash.map(|h| hex_encode(&h));
if let Some(node_hex) = node_hex {
if let Some(pub_key) = known_identities.get(&node_hex) {
let ed25519_bytes: [u8; 32] =
pub_key[32..64].try_into().unwrap();
if let Ok(verify_key) =
Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(
data,
&verify_key,
&ed25519_bytes,
interface_id,
);
}
if let Some(node_hex) = node_hex
&& let Some(pub_key) = known_identities.get(&node_hex)
{
let ed25519_bytes: [u8; 32] = pub_key[32..64].try_into().unwrap();
if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(
data,
&verify_key,
&ed25519_bytes,
interface_id,
);
}
}
}
rns_wire::context::PacketContext::ResourceHmu => {
if let Some(ref link) = self.link {
if let Ok(plaintext) = link.decrypt(data) {
if let Some(ref mut transfer) = self.active_transfer {
transfer.handle_hmu(&plaintext);
}
}
if let Some(ref link) = self.link
&& let Ok(plaintext) = link.decrypt(data)
&& let Some(ref mut transfer) = self.active_transfer
{
transfer.handle_hmu(&plaintext);
}
}
rns_wire::context::PacketContext::ResourceReq => {
@@ -760,16 +757,12 @@ impl PropagationSyncTask {
}
}
rns_wire::context::PacketContext::Response => {
if self.state == SyncTaskState::AwaitingResponse {
if let Some(ref mut link) = self.link {
if let Ok((_request_id, response_data)) =
link.handle_response(data)
{
let offer_response =
OfferResponse::from_msgpack(&response_data);
self.handle_offer_response(offer_response);
}
}
if self.state == SyncTaskState::AwaitingResponse
&& let Some(ref mut link) = self.link
&& let Ok((_request_id, response_data)) = link.handle_response(data)
{
let offer_response = OfferResponse::from_msgpack(&response_data);
self.handle_offer_response(offer_response);
}
}
rns_wire::context::PacketContext::ResourceRcl
@@ -1039,10 +1032,10 @@ impl PropagationSyncTask {
fn prepare_transfer_for_ids(&mut self, ids: &[PropagationTransientId]) {
if ids.is_empty() {
if let Some(node_hash) = self.node_dest_hash {
if let Ok(mut node) = self.propagation_node.lock() {
node.complete_sync(&node_hash);
}
if let Some(node_hash) = self.node_dest_hash
&& let Ok(mut node) = self.propagation_node.lock()
{
node.complete_sync(&node_hash);
}
self.state = SyncTaskState::Complete;
return;
@@ -1128,13 +1121,12 @@ impl PropagationSyncTask {
if self.terminal_result.is_none()
&& self.offer_policy.is_none()
&& self.last_sync.elapsed() >= self.sync_interval
&& let Some(node_hash) = self.node_dest_hash
{
if let Some(node_hash) = self.node_dest_hash {
if self.message_count() > 0 {
let _ = self.start_sync(node_hash);
} else {
self.last_sync = Instant::now();
}
if self.message_count() > 0 {
let _ = self.start_sync(node_hash);
} else {
self.last_sync = Instant::now();
}
}
}
@@ -1146,38 +1138,38 @@ impl PropagationSyncTask {
self.drive_transfers();
}
SyncTaskState::Complete | SyncTaskState::Failed => {
if self.terminal_result.is_none() {
if let Some(peer_hash) = self.node_dest_hash {
let complete = self.state == SyncTaskState::Complete;
self.terminal_result = Some(PeerSyncTerminalResult {
peer_hash,
state: if complete {
PeerSyncTerminalState::Complete
} else {
PeerSyncTerminalState::Failed
},
offer_generation: complete
.then_some(self.active_offer_generation)
.flatten(),
generation_exhausted: complete && self.generation_exhausted,
offered: if complete { self.offered_count } else { 0 },
outgoing: if complete { self.outgoing_count } else { 0 },
tx_bytes: if complete { self.transfer_data_size } else { 0 },
link_establishment_rate: self.link_establishment_rate,
sync_transfer_rate: (complete && self.outgoing_count > 0)
.then(|| {
self.transfer_started.map(|started| {
let elapsed = started.elapsed().as_secs_f64();
if elapsed > 0.0 {
self.transfer_wire_size as f64 * 8.0 / elapsed
} else {
0.0
}
})
if self.terminal_result.is_none()
&& let Some(peer_hash) = self.node_dest_hash
{
let complete = self.state == SyncTaskState::Complete;
self.terminal_result = Some(PeerSyncTerminalResult {
peer_hash,
state: if complete {
PeerSyncTerminalState::Complete
} else {
PeerSyncTerminalState::Failed
},
offer_generation: complete
.then_some(self.active_offer_generation)
.flatten(),
generation_exhausted: complete && self.generation_exhausted,
offered: if complete { self.offered_count } else { 0 },
outgoing: if complete { self.outgoing_count } else { 0 },
tx_bytes: if complete { self.transfer_data_size } else { 0 },
link_establishment_rate: self.link_establishment_rate,
sync_transfer_rate: (complete && self.outgoing_count > 0)
.then(|| {
self.transfer_started.map(|started| {
let elapsed = started.elapsed().as_secs_f64();
if elapsed > 0.0 {
self.transfer_wire_size as f64 * 8.0 / elapsed
} else {
0.0
}
})
.flatten(),
});
}
})
.flatten(),
});
}
self.cleanup_sync();
self.last_sync = Instant::now();
@@ -1311,10 +1303,10 @@ impl PropagationSyncTask {
self.active_offer_generation = Some(generation);
self.generation_exhausted = generation_exhausted;
self.record_handled_updates(&terminal_handled_ids);
if offer.transient_ids.is_empty() {
if let Ok(mut node) = self.propagation_node.lock() {
node.complete_sync(&node_hash);
}
if offer.transient_ids.is_empty()
&& let Ok(mut node) = self.propagation_node.lock()
{
node.complete_sync(&node_hash);
}
offer
}
@@ -1589,10 +1581,10 @@ impl PropagationSyncTask {
let completed_ids = std::mem::take(&mut self.active_transfer_ids);
self.record_handled_updates(&completed_ids);
if let Some(node_hash) = self.node_dest_hash {
if let Ok(mut node) = self.propagation_node.lock() {
node.complete_sync(&node_hash);
}
if let Some(node_hash) = self.node_dest_hash
&& let Ok(mut node) = self.propagation_node.lock()
{
node.complete_sync(&node_hash);
}
self.state = SyncTaskState::Complete;
}
@@ -1741,10 +1733,10 @@ impl PropagationSyncTask {
peer.link_closed();
}
if let Some(link_id) = self.link_id.take() {
if !graceful_release {
self.queue_endpoint_cleanup(link_id);
}
if let Some(link_id) = self.link_id.take()
&& !graceful_release
{
self.queue_endpoint_cleanup(link_id);
}
self.attached_interface = None;
self.pending_endpoint_bind = None;
+142 -34
View File
@@ -20,7 +20,7 @@ use crate::peer::{LxmPeer, OutboundOfferPolicy};
use crate::propagation::PropagationStore;
use crate::propagation_client::PropagationTransferStatus;
use crate::stamper;
use crate::ticket::{Ticket, TicketStore};
use crate::ticket::{Ticket, TicketStore, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
/// Router configuration.
@@ -352,6 +352,37 @@ pub struct StampCostEntry {
pub recorded_at: f64,
}
/// Owned, coherent snapshot of the router state written by [`LxmRouter::save_state`].
///
/// Creating the snapshot only clones in-memory state. The caller can therefore
/// release any lock that protects the router before calling [`Self::save_state`],
/// keeping filesystem I/O out of the router's critical section.
#[derive(Debug, Clone)]
pub struct RouterStateSnapshot {
outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>,
tickets: TicketStoreSnapshot,
local_deliveries: HashMap<PropagationTransientId, f64>,
locally_processed: HashMap<PropagationTransientId, f64>,
node_stats: crate::persist::PersistedNodeStats,
}
impl RouterStateSnapshot {
/// Persist this owned snapshot using the router's MessagePack layout.
///
/// Each file is written atomically via rename, matching
/// [`LxmRouter::save_state`].
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, &self.tickets)?;
persist::save_local_deliveries(state_dir, &self.local_deliveries)?;
persist::save_locally_processed(state_dir, &self.locally_processed)?;
persist::save_node_stats(state_dir, &self.node_stats)?;
Ok(())
}
}
impl LxmRouter {
pub fn new(config: RouterConfig) -> Self {
Self {
@@ -530,16 +561,16 @@ impl LxmRouter {
}
}
if message.method == DeliveryMethod::Opportunistic {
if let Ok(packed) = message.pack_payload() {
let content_size = packed
.len()
.saturating_sub(TIMESTAMP_SIZE + STRUCT_OVERHEAD);
// Approximates ENCRYPTED_PACKET_MAX_CONTENT for default RNS parameters.
let max_content = 295;
if content_size > max_content {
message.method = DeliveryMethod::Direct;
}
if message.method == DeliveryMethod::Opportunistic
&& let Ok(packed) = message.pack_payload()
{
let content_size = packed
.len()
.saturating_sub(TIMESTAMP_SIZE + STRUCT_OVERHEAD);
// Approximates ENCRYPTED_PACKET_MAX_CONTENT for default RNS parameters.
let max_content = 295;
if content_size > max_content {
message.method = DeliveryMethod::Direct;
}
}
@@ -560,13 +591,12 @@ impl LxmRouter {
message: &mut LxMessage,
) -> Result<(), TicketPreparationError> {
let now = now_f64();
if message.outbound_ticket.is_none() {
if let Some(ticket) = self
if message.outbound_ticket.is_none()
&& let Some(ticket) = self
.ticket_store
.find_outbound(&message.destination_hash, now)
{
message.outbound_ticket = Some(ticket.token);
}
{
message.outbound_ticket = Some(ticket.token);
}
if message.include_ticket && !message.fields.contains_key(&FIELD_TICKET) {
@@ -884,10 +914,8 @@ impl LxmRouter {
.active_deferred_stamp
.as_ref()
.is_some_and(|job| job.message_hash == *message_hash);
if active_matches {
if let Some(job) = self.active_deferred_stamp.take() {
job.handle.cancel();
}
if active_matches && let Some(job) = self.active_deferred_stamp.take() {
job.handle.cancel();
}
return true;
}
@@ -1129,25 +1157,29 @@ impl LxmRouter {
Ok(())
}
/// Persist runtime state to `state_dir` using MessagePack. Safe to call
/// periodically; each file is written atomically via rename.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, &self.ticket_store.snapshot())?;
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
persist::save_node_stats(
state_dir,
&persist::PersistedNodeStats {
/// Clone all runtime state written by [`Self::save_state`] into one owned
/// value. Embedders can take this snapshot while holding the router lock,
/// release the lock, and perform persistence through
/// [`RouterStateSnapshot::save_state`].
pub fn state_snapshot(&self) -> RouterStateSnapshot {
RouterStateSnapshot {
outbound_stamp_costs: self.outbound_stamp_costs.clone(),
tickets: self.ticket_store.snapshot(),
local_deliveries: self.propagation_store.locally_delivered_ids().clone(),
locally_processed: self.propagation_store.locally_processed_ids().clone(),
node_stats: crate::persist::PersistedNodeStats {
client_propagation_messages_received: self.client_propagation_messages_received,
client_propagation_messages_served: self.client_propagation_messages_served,
unpeered_propagation_incoming: self.unpeered_propagation_incoming,
unpeered_propagation_rx_bytes: self.unpeered_propagation_rx_bytes,
},
)?;
Ok(())
}
}
/// Persist runtime state to `state_dir` using MessagePack. Safe to call
/// periodically; each file is written atomically via rename.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
self.state_snapshot().save_state(state_dir)
}
/// Return peer destination hashes that are due for sync and mark each as
@@ -3051,6 +3083,82 @@ mod tests {
assert_eq!(r2.unpeered_propagation_rx_bytes, 13);
}
#[test]
fn test_state_snapshot_is_an_owned_coherent_copy() {
let dest = [0xA1; 16];
let transient = [0xB2; 32];
let mut router = LxmRouter::new(RouterConfig::default());
router.set_stamp_cost(dest, 8);
router.remember_ticket(dest, [0xC3; 16], 4_102_444_800.0);
router.propagation_store.mark_locally_delivered(transient);
router.propagation_store.mark_locally_processed(transient);
router.client_propagation_messages_received = 10;
router.client_propagation_messages_served = 11;
router.unpeered_propagation_incoming = 12;
router.unpeered_propagation_rx_bytes = 13;
let snapshot = router.state_snapshot();
// Mutating every persisted router dataset after capture must not alter
// the snapshot that a background persistence task owns.
router.set_stamp_cost(dest, 42);
router.remember_ticket(dest, [0xD4; 16], 4_102_444_800.0);
router
.propagation_store
.replace_locally_delivered(HashMap::new());
router
.propagation_store
.replace_locally_processed(HashMap::new());
router.client_propagation_messages_received = 20;
router.client_propagation_messages_served = 21;
router.unpeered_propagation_incoming = 22;
router.unpeered_propagation_rx_bytes = 23;
assert_eq!(snapshot.outbound_stamp_costs[&dest].cost, 8);
assert_eq!(snapshot.tickets.outbound.len(), 1);
assert_eq!(snapshot.tickets.outbound[0].token, [0xC3; 16]);
assert!(snapshot.local_deliveries.contains_key(&transient));
assert!(snapshot.locally_processed.contains_key(&transient));
assert_eq!(snapshot.node_stats.client_propagation_messages_received, 10);
assert_eq!(snapshot.node_stats.client_propagation_messages_served, 11);
assert_eq!(snapshot.node_stats.unpeered_propagation_incoming, 12);
assert_eq!(snapshot.node_stats.unpeered_propagation_rx_bytes, 13);
}
#[test]
fn test_state_snapshot_persists_after_router_is_dropped() {
let tmp = tempfile::TempDir::new().unwrap();
let dest = [0xA5; 16];
let transient = [0xB6; 32];
let snapshot = {
let mut router = LxmRouter::new(RouterConfig::default());
router.set_stamp_cost(dest, 9);
router.remember_ticket(dest, [0xC7; 16], 4_102_444_800.0);
router.propagation_store.mark_locally_delivered(transient);
router.propagation_store.mark_locally_processed(transient);
router.client_propagation_messages_received = 30;
router.client_propagation_messages_served = 31;
router.unpeered_propagation_incoming = 32;
router.unpeered_propagation_rx_bytes = 33;
router.state_snapshot()
};
snapshot.save_state(tmp.path()).unwrap();
let mut restored = LxmRouter::new(RouterConfig::default());
restored.load_state(tmp.path()).unwrap();
assert_eq!(restored.outbound_stamp_costs[&dest].cost, 9);
assert_eq!(restored.get_outbound_ticket(&dest), Some([0xC7; 16]));
assert!(restored.propagation_store.is_locally_delivered(&transient));
assert!(restored.propagation_store.is_locally_processed(&transient));
assert_eq!(restored.client_propagation_messages_received, 30);
assert_eq!(restored.client_propagation_messages_served, 31);
assert_eq!(restored.unpeered_propagation_incoming, 32);
assert_eq!(restored.unpeered_propagation_rx_bytes, 33);
}
/// T1-10: persisted dedup timestamps are the REAL first-seen times —
/// restored on load (not reset to save-time), so age-based expiry is
/// stable across arbitrarily many save/load cycles.
File diff suppressed because it is too large. Load diff
+14 -15
View File
@@ -324,17 +324,16 @@ impl DaemonConfig {
dc.outbound_propagation_node = Some(trimmed.to_string());
}
}
if get_int(Some(sec), "propagation_stamp_cost_target").is_none() {
if let Some(cost) = sec.get_uint("propagation_stamp_cost") {
dc.propagation_stamp_cost = cost as u8;
}
if get_int(Some(sec), "propagation_stamp_cost_target").is_none()
&& let Some(cost) = sec.get_uint("propagation_stamp_cost")
{
dc.propagation_stamp_cost = cost as u8;
}
if get_float(Some(sec), "propagation_message_max_accepted_size").is_none()
&& get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none()
&& let Some(limit) = sec.get_uint("propagation_limit")
{
if let Some(limit) = sec.get_uint("propagation_limit") {
dc.propagation_limit_kb = limit as usize;
}
dc.propagation_limit_kb = limit as usize;
}
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
@@ -343,14 +342,14 @@ impl DaemonConfig {
if !dc.auth_required {
dc.auth_required = sec.get_bool_or("auth_required", false);
}
if dc.control_allowed.is_empty() {
if let Some(allowed) = sec.get("allowed") {
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
if dc.control_allowed.is_empty()
&& let Some(allowed) = sec.get("allowed")
{
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
+49 -5
View File
@@ -45,6 +45,7 @@ impl ControlCommandKind {
}
}
/// Query propagation control with a raw peer hash, or no payload for status.
pub async fn query_control(
transport_tx: tokio::sync::mpsc::Sender<rns_transport::messages::TransportMessage>,
identity: Identity,
@@ -59,13 +60,25 @@ pub async fn query_control(
target_identity_hash,
CONTROL_APP_NAME,
path,
payload,
encode_control_payload(payload),
0,
Duration::from_secs_f64(timeout_secs.max(0.0)),
)
.await
}
fn encode_control_payload(payload: Vec<u8>) -> Vec<u8> {
// LinkClient accepts an encoded MessagePack value. Raw hash bytes can
// themselves form a complete value (e.g. 0xaf followed by 15 bytes), so
// letting Link infer the type can truncate or reinterpret a peer address.
// Python sends a bytes object for sync/unpeer and None for status.
encode_value(&if payload.is_empty() {
Value::Nil
} else {
Value::Binary(payload)
})
}
pub async fn resolve_remote_identity_hash(
transport_tx: mpsc::Sender<TransportMessage>,
remote_destination_hash: [u8; 16],
@@ -98,10 +111,10 @@ pub fn decode_control_response(response: &[u8]) -> ControlResponse {
return ControlResponse::Success;
};
if let Some(code) = value.as_u64() {
if let Some(error) = peer_error_from_code(code as u8) {
return ControlResponse::Error(error);
}
if let Some(code) = value.as_u64()
&& let Some(error) = peer_error_from_code(code as u8)
{
return ControlResponse::Error(error);
}
if value.is_nil() {
@@ -844,6 +857,37 @@ fn encode_value(value: &Value) -> Vec<u8> {
mod tests {
use super::*;
#[test]
fn control_payload_preserves_every_peer_hash_prefix_as_binary() {
for prefix in 0..=u8::MAX {
let mut hash = vec![0x41; 16];
hash[0] = prefix;
assert_eq!(
decode_value(&encode_control_payload(hash.clone())),
Value::Binary(hash),
"peer prefix {prefix:#04x} must not select a MessagePack type"
);
}
for hash in [
hex::decode("af55b3f0e0b336fdfdbe263c12a688e0").unwrap(),
[vec![0xc4, 14], vec![0x41; 14]].concat(),
[vec![0x9f], vec![0; 15]].concat(),
] {
assert_eq!(
decode_value(&encode_control_payload(hash.clone())),
Value::Binary(hash)
);
}
}
#[test]
fn empty_control_payload_matches_python_status_nil() {
assert_eq!(
decode_value(&encode_control_payload(Vec::new())),
Value::Nil
);
}
#[tokio::test]
async fn remote_identity_resolution_uses_recall_and_path_request_without_handlers() {
use rns_transport::messages::{
+7 -5
View File
@@ -11,7 +11,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
EXPECTED_RUST_VERSION = "1.87"
EXPECTED_RUST_VERSION = "1.89"
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
@@ -65,9 +65,11 @@ def check_packages(document: dict[str, object]) -> tuple[str, str]:
)
requirement = reticulum_requirements.pop()
if not requirement.startswith("^"):
# The project permits breaking core APIs in a minor release; caret ranges
# would silently admit the next incompatible minor line.
if not re.fullmatch(r"~\d+\.\d+\.\d+", requirement):
fail(f"unexpected rsReticulum compatibility requirement {requirement!r}")
return str(versions.pop()), requirement.removeprefix("^")
return str(versions.pop()), requirement.removeprefix("~")
def check_workflow_actions() -> None:
@@ -92,8 +94,8 @@ def check_workflow_actions() -> None:
def check_release_workflow(reticulum_version: str) -> str:
workflow = (ROOT / ".github/workflows/release.yml").read_text()
if not re.search(r"^\s*toolchain:\s*1\.87\.0\s*$", workflow, re.MULTILINE):
fail("release workflow does not select Rust 1.87.0")
if not re.search(r"^\s*toolchain:\s*1\.89\.0\s*$", workflow, re.MULTILINE):
fail("release workflow does not select Rust 1.89.0")
if "ref: ${{ env.RELEASE_TAG }}" not in workflow:
fail("release workflow does not check out RELEASE_TAG")
+40 -37
View File
@@ -16,7 +16,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = ROOT / "api-stability.json"
CONFIG_PATH = ROOT / "api" / "stability.json"
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
HASH_PATTERN = re.compile(r"^[0-9a-f]{64}$")
TIERS = {
@@ -60,32 +60,41 @@ def load_config() -> dict[str, object]:
return config
def validate_change_record(path: str, snapshot_commit: str) -> None:
record_path = ROOT / path
try:
record = json.loads(record_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
fail(f"cannot read snapshot change record {path}: {error}")
def validate_snapshot_review(record: object) -> None:
if not isinstance(record, dict):
fail("snapshot review is missing")
required = {
"schemaVersion", "snapshotSourceCommit", "capabilities", "classification",
"publicApiDiff", "semver", "deprecations", "platformEvidence",
"areas",
"canonicalPath",
"classification",
"publicApiDiff",
"semver",
"deprecations",
"wirePersistenceRuntimeImpact",
"platformEvidence",
}
if not required.issubset(record) or record.get("schemaVersion") != 1:
fail("snapshot change record is incomplete")
if record.get("snapshotSourceCommit") != snapshot_commit:
fail("snapshot change record does not match the snapshot source commit")
if not isinstance(record.get("capabilities"), list) or not record["capabilities"]:
fail("snapshot change record must name capability IDs")
if not required.issubset(record):
fail("snapshot review is incomplete")
if not isinstance(record.get("areas"), list) or not record["areas"]:
fail("snapshot review must name the affected API areas")
if not all(isinstance(area, str) and area for area in record["areas"]):
fail("snapshot review API areas must be non-empty strings")
diff = record.get("publicApiDiff")
if not isinstance(diff, dict) or set(diff) != {"added", "removed"}:
fail("snapshot change record must classify added and removed API lines")
fail("snapshot review must classify added and removed API lines")
if not all(isinstance(diff[key], int) and diff[key] >= 0 for key in diff):
fail("snapshot change record API counts must be non-negative integers")
fail("snapshot review API counts must be non-negative integers")
if not isinstance(record.get("platformEvidence"), list) or not record["platformEvidence"]:
fail("snapshot change record must name platform evidence")
for key in ("classification", "semver", "deprecations"):
fail("snapshot review must name platform evidence")
for key in (
"canonicalPath",
"classification",
"semver",
"deprecations",
"wirePersistenceRuntimeImpact",
):
if not isinstance(record.get(key), str) or not record[key]:
fail(f"snapshot change record must name {key}")
fail(f"snapshot review must name {key}")
def public_packages(manifest_path: str) -> set[str]:
@@ -183,10 +192,7 @@ def validate_metadata(
)
if snapshot_ancestor.returncode != 0:
fail(f"snapshot source commit {snapshot_commit} is not an ancestor of HEAD")
change_record = snapshot_source.get("changeRecord")
if not isinstance(change_record, str) or not change_record.startswith("api-reviews/"):
fail("snapshot source must name a reviewed change record")
validate_change_record(change_record, snapshot_commit)
validate_snapshot_review(snapshot_source.get("review"))
packages = config.get("packages")
if not isinstance(packages, list) or not packages:
@@ -209,7 +215,7 @@ def validate_metadata(
fail(f"{name} has an unknown stability tier")
if package.get("compatibility") != "reviewed-snapshot":
fail(f"{name} must use the reviewed-snapshot compatibility policy")
if not isinstance(snapshot, str) or not snapshot.startswith("api-baseline/"):
if not isinstance(snapshot, str) or not snapshot.startswith("api/snapshots/"):
fail(f"{name} has an invalid snapshot path")
snapshot_path = ROOT / snapshot
if not snapshot_path.is_file() and not updating:
@@ -292,29 +298,26 @@ def main() -> None:
parser.add_argument("--metadata-only", action="store_true")
parser.add_argument("--update", action="store_true")
parser.add_argument("--snapshot-source-commit")
parser.add_argument("--change-record")
args = parser.parse_args()
if args.metadata_only and args.update:
fail("--metadata-only and --update are mutually exclusive")
config = load_config()
if args.update:
if not args.snapshot_source_commit or not args.change_record:
fail("--update requires --snapshot-source-commit and --change-record")
if not args.snapshot_source_commit:
fail("--update requires --snapshot-source-commit")
head = run(["git", "rev-parse", "HEAD"]).strip()
if args.snapshot_source_commit != head:
fail("snapshot source must be the clean source commit at HEAD")
if not args.change_record.startswith("api-reviews/"):
fail("change record must be stored below api-reviews/")
status = run(["git", "status", "--porcelain=v1", "--untracked-files=all"])
dirty_paths = {line[3:] for line in status.splitlines() if len(line) > 3}
if dirty_paths - {args.change_record}:
fail("snapshot source has uncommitted changes outside the review record")
config["snapshotSource"] = {
"commit": args.snapshot_source_commit,
"capturedOn": date.today().isoformat(),
"changeRecord": args.change_record,
}
if dirty_paths - {"api/stability.json"}:
fail("snapshot source has uncommitted changes outside api/stability.json")
snapshot_source = config.get("snapshotSource")
if not isinstance(snapshot_source, dict):
fail("snapshot source identity is missing")
snapshot_source["commit"] = args.snapshot_source_commit
snapshot_source["capturedOn"] = date.today().isoformat()
packages = validate_metadata(config, updating=args.update)
if args.metadata_only:
print("api baseline metadata: ok")
+29 -11
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Reject removals from the immutable Wave C public-API compatibility floor."""
"""Reject removals from the reviewed public-API compatibility floor."""
from __future__ import annotations
@@ -10,7 +10,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
LEDGER_PATH = ROOT / "api-stability.json"
LEDGER_PATH = ROOT / "api" / "stability.json"
def fail(message: str) -> None:
@@ -32,21 +32,41 @@ def git_show(commit: str, path: str) -> str:
return result.stdout
def load_floor_ledger(commit: str) -> dict[str, object]:
for path in ("api/stability.json", "api-stability.json"):
result = subprocess.run(
["git", "show", f"{commit}:{path}"],
cwd=ROOT,
capture_output=True,
text=True,
)
if result.returncode == 0:
return json.loads(result.stdout)
fail(f"cannot read API ledger at compatibility floor {commit}")
def main() -> None:
metadata = subprocess.run(
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
)
if metadata.returncode != 0:
fail("snapshot metadata or reviewed change record is invalid")
fail("snapshot metadata or review is invalid")
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit")
if not isinstance(floor, str):
fail("api-stability.json has no compatibility-floor commit")
fail("api/stability.json has no compatibility-floor commit")
floor_ledger = load_floor_ledger(floor)
floor_snapshots = {
package["name"]: package["snapshot"] for package in floor_ledger["packages"]
}
total_added = 0
total_removed = 0
for package in ledger["packages"]:
path = package["snapshot"]
before = set(git_show(floor, path).splitlines())
floor_path = floor_snapshots.get(package["name"])
if not isinstance(floor_path, str):
fail(f"{package['name']} is absent from the compatibility floor")
before = set(git_show(floor, floor_path).splitlines())
after = set((ROOT / path).read_text(encoding="utf-8").splitlines())
added = sorted(after - before)
removed = sorted(before - after)
@@ -58,17 +78,15 @@ def main() -> None:
print(f"- {line}", file=sys.stderr)
if total_removed:
fail(
f"{total_removed} public API lines were removed from the Wave C floor; "
f"{total_removed} public API lines were removed from the compatibility floor; "
"the current policy permits additions only"
)
change_record = json.loads(
(ROOT / ledger["snapshotSource"]["changeRecord"]).read_text(encoding="utf-8")
)
if change_record["publicApiDiff"] != {
review = ledger["snapshotSource"]["review"]
if review["publicApiDiff"] != {
"added": total_added,
"removed": total_removed,
}:
fail("reviewed change record does not match the measured API diff")
fail("snapshot review does not match the measured API diff")
print(f"api compatibility: additive-only (+{total_added}, -0)")
+2 -2
View File
@@ -12,8 +12,8 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
LEDGER_PATH = ROOT / "api-stability.json"
CONTRACT_PATH = ROOT / "api-baseline" / "manifest-contract.json"
LEDGER_PATH = ROOT / "api" / "stability.json"
CONTRACT_PATH = ROOT / "api" / "snapshots" / "manifest-contract.json"
def fail(message: str) -> None: