meshlogd 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ # Python build / cache
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .venv/
9
+ venv/
10
+ .env
11
+
12
+ # meshlog runtime data (append-only field logs) and Reticulum state
13
+ *.jsonl
14
+ .reticulum/
15
+
16
+ # tooling
17
+ .pytest_cache/
18
+ .ruff_cache/
19
+ .mypy_cache/
20
+ .DS_Store
meshlogd-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Kevin Hoffman
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: meshlogd
3
+ Version: 0.1.0
4
+ Summary: Event-sourced, eventually-consistent dataset that converges over a partition-prone Reticulum (LoRa) mesh.
5
+ Project-URL: Homepage, https://meshlogd.org
6
+ Project-URL: Source, https://github.com/meshlogd/meshlogd
7
+ Project-URL: Issues, https://github.com/meshlogd/meshlogd/issues
8
+ Author-email: Kevin Hoffman <alothien+meshlogd@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: anti-entropy,crdt,event-sourcing,eventually-consistent,gossip,lora,mesh,offline-first,radio,reticulum
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Communications
17
+ Classifier: Topic :: System :: Networking
18
+ Requires-Python: >=3.9
19
+ Provides-Extra: dev
20
+ Requires-Dist: build; extra == 'dev'
21
+ Requires-Dist: twine; extra == 'dev'
22
+ Provides-Extra: radio
23
+ Requires-Dist: rns>=0.7; extra == 'radio'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # meshlog
27
+
28
+ An **event-sourced, eventually-consistent dataset** that converges over a
29
+ frequently-partitioning, low-bandwidth mesh. Built for the "trusted
30
+ collaborators, no internet, private radio" case: a base camp and field teams
31
+ (humanitarian assessment, SAR, expeditions) collecting a shared dataset with no
32
+ server and no connectivity, reconciling whenever radios come into range.
33
+
34
+ The transport is [Reticulum](https://reticulum.network) on real hardware
35
+ (LoRa/packet radio/anything), but the engine is transport-agnostic and ships
36
+ with an in-memory transport so you can run, test, and watch it converge with no
37
+ radios at all.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install meshlogd # core engine (stdlib-only)
43
+ pip install "meshlogd[radio]" # + Reticulum, for the real LoRa/packet-radio transport
44
+ ```
45
+
46
+ > **Naming:** the distribution and daemon command are **`meshlogd`**; the importable
47
+ > library is **`meshlog`** (`import meshlog`) — the trailing `d` follows the Unix
48
+ > daemon convention (cf. `ssh`/`sshd`), like how `pyyaml` installs but imports as `yaml`.
49
+
50
+ ## The idea in one breath
51
+
52
+ KoboToolbox already solves offline *data entry* but syncs to a central server
53
+ over the internet. meshlog replaces that central sync with **peer-to-peer
54
+ anti-entropy gossip over a radio mesh**, so the shared dataset converges with no
55
+ server and no internet. Kobo (or any form UI) owns the forms; meshlog owns the
56
+ replication layer Kobo doesn't have.
57
+
58
+ ## Why event sourcing makes this easy
59
+
60
+ The whole database is a **grow-only set of immutable, per-author events**. That
61
+ single decision hands you the hard distributed-systems properties almost for
62
+ free:
63
+
64
+ - **Merging is set union.** Union is commutative, associative, and idempotent,
65
+ so the dataset is a CRDT: it converges regardless of the order or grouping in
66
+ which events arrive across a partitioning network.
67
+ - **Per-author contiguous feeds** (the Secure-Scuttlebutt trick) collapse "what
68
+ do you have?" down to one integer per author — a **high-water-mark frontier**.
69
+ That digest is tiny enough to ride inside a Reticulum *announce*.
70
+ - **Hash-chained feeds** make history tamper-evident (we're trusted-collaborator,
71
+ so we want integrity — just not anonymity).
72
+ - **The materialized view is a pure fold** over the event set, so two nodes with
73
+ the same events compute byte-identical state. Conflicts on mutable scalar
74
+ fields resolve by **Last-Writer-Wins keyed on a Hybrid Logical Clock**, not
75
+ wall time and not arrival order — so concurrent edits from two islands pick the
76
+ same winner everywhere.
77
+
78
+ ## Anti-entropy protocol (the entire thing)
79
+
80
+ ```
81
+ when two peers can talk:
82
+ each sends its FRONTIER = {author: high_water_seq}
83
+ on receiving a peer's frontier:
84
+ push the slice of every feed above the peer's marks (chunked)
85
+ ingest is idempotent + gap-buffering, so overlaps/reorders are harmless
86
+ ```
87
+
88
+ Multi-hop convergence is automatic: a node relays *every* author's events it
89
+ holds, not just its own, so A's events reach C through B even if A and C never
90
+ meet. That's the store-and-forward property, achieved without special-casing it.
91
+
92
+ ## Layout
93
+
94
+ ```
95
+ meshlog/
96
+ hlc.py Hybrid Logical Clock
97
+ event.py immutable, hash-chained, content-addressed Event
98
+ feedstore.py append-only per-author log; frontier + delta computation
99
+ reducer.py deterministic fold -> materialized records (Kobo-style)
100
+ transport.py Transport interface + in-memory SimTransport (partitions)
101
+ node.py Node + the anti-entropy protocol
102
+ rns_transport.py real Reticulum transport (Link + Resource + announce)
103
+ demo_sim.py base camp + 4 teams converge across staged partitions
104
+ test_convergence.py 200 randomized partition trials + fold-determinism check
105
+ meshlog/cli.py CLI to run a node over a live Reticulum mesh (the `meshlogd` command)
106
+ ```
107
+
108
+ ## Run it (no radios needed)
109
+
110
+ ```bash
111
+ python -m demo_sim # scripted scenario, prints the converged dataset
112
+ python -m test_convergence # 200 randomized partition/merge trials
113
+ ```
114
+
115
+ The demo islands three groups, has each collect independently, stages a
116
+ conflicting concurrent edit, then heals the network in stages and verifies every
117
+ node ends with identical frontiers, identical views, and the same LWW winner.
118
+
119
+ ## Run it for real (over Reticulum)
120
+
121
+ ```bash
122
+ pip install "meshlogd[radio]" # pulls in Reticulum (rns)
123
+ # Machine A:
124
+ meshlogd --name base --data base.jsonl --create R-100 site_assessment
125
+ # Machine B (same LAN to start; add a LoRa interface in ~/.reticulum/config later):
126
+ meshlogd --name team_a --data team_a.jsonl --create R-200 water_point
127
+ # type `view` at either prompt to watch the dataset converge
128
+ ```
129
+
130
+ ## Verification status
131
+
132
+ - `feedstore`, `reducer`, `hlc`, `node`, `transport`, the demo, and the 200
133
+ randomized trials **run and pass** as committed.
134
+ - `rns_transport.py` / `meshlog/cli.py` are written against the Reticulum 1.3.x API
135
+ (Identity, Destination, Link, Resource, Packet, announce handlers) and are
136
+ faithful to the docs/examples, but have **not** been exercised on a live mesh
137
+ here. Stand up two instances to validate end-to-end before field use.
138
+
139
+ ## Deliberately left as extension points
140
+
141
+ - **Attachments / blobs.** Events carry a content hash + size; the bytes are not
142
+ inlined. Add a content-addressed blob store and transfer blobs lazily over RNS
143
+ Resources, *after* structured events, so photos never starve assessment data on
144
+ a slow link.
145
+ - **Signatures.** `Event.is_authentic()` currently checks the content hash. With
146
+ RNS you already hold each author's Ed25519 key — sign the event id and verify
147
+ on ingest to close the trusted-but-verify loop.
148
+ - **Wire codec.** Prototype uses JSON for readability. Swap `_encode/_decode` for
149
+ MessagePack or CBOR to cut bytes on the radio.
150
+ - **Compaction / snapshots.** Grow-only logs grow. Add periodic signed snapshots
151
+ + feed truncation once a quorum has acknowledged a watermark.
152
+ - **Kobo bridge.** Poll the KoboToolbox/ODK submission API (or read KoboCollect
153
+ instances) and translate each submission into `record.create` + `field.set`
154
+ events. That's the actual on-ramp to the HHI use case.
155
+
156
+ ## Reading list (steal from these)
157
+
158
+ - **Secure Scuttlebutt** — append-only per-author feeds + gossip replication for
159
+ intermittent offline networks. This design is a close cousin.
160
+ - **CRDTs** — why union-based / LWW-register merges converge.
161
+ - **Kulkarni et al. 2014, Hybrid Logical Clocks** — the clock used here.
162
+ - **Reticulum manual**, Understanding + API Reference chapters — Link, Resource,
163
+ and the announce mechanism.
@@ -0,0 +1,138 @@
1
+ # meshlog
2
+
3
+ An **event-sourced, eventually-consistent dataset** that converges over a
4
+ frequently-partitioning, low-bandwidth mesh. Built for the "trusted
5
+ collaborators, no internet, private radio" case: a base camp and field teams
6
+ (humanitarian assessment, SAR, expeditions) collecting a shared dataset with no
7
+ server and no connectivity, reconciling whenever radios come into range.
8
+
9
+ The transport is [Reticulum](https://reticulum.network) on real hardware
10
+ (LoRa/packet radio/anything), but the engine is transport-agnostic and ships
11
+ with an in-memory transport so you can run, test, and watch it converge with no
12
+ radios at all.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install meshlogd # core engine (stdlib-only)
18
+ pip install "meshlogd[radio]" # + Reticulum, for the real LoRa/packet-radio transport
19
+ ```
20
+
21
+ > **Naming:** the distribution and daemon command are **`meshlogd`**; the importable
22
+ > library is **`meshlog`** (`import meshlog`) — the trailing `d` follows the Unix
23
+ > daemon convention (cf. `ssh`/`sshd`), like how `pyyaml` installs but imports as `yaml`.
24
+
25
+ ## The idea in one breath
26
+
27
+ KoboToolbox already solves offline *data entry* but syncs to a central server
28
+ over the internet. meshlog replaces that central sync with **peer-to-peer
29
+ anti-entropy gossip over a radio mesh**, so the shared dataset converges with no
30
+ server and no internet. Kobo (or any form UI) owns the forms; meshlog owns the
31
+ replication layer Kobo doesn't have.
32
+
33
+ ## Why event sourcing makes this easy
34
+
35
+ The whole database is a **grow-only set of immutable, per-author events**. That
36
+ single decision hands you the hard distributed-systems properties almost for
37
+ free:
38
+
39
+ - **Merging is set union.** Union is commutative, associative, and idempotent,
40
+ so the dataset is a CRDT: it converges regardless of the order or grouping in
41
+ which events arrive across a partitioning network.
42
+ - **Per-author contiguous feeds** (the Secure-Scuttlebutt trick) collapse "what
43
+ do you have?" down to one integer per author — a **high-water-mark frontier**.
44
+ That digest is tiny enough to ride inside a Reticulum *announce*.
45
+ - **Hash-chained feeds** make history tamper-evident (we're trusted-collaborator,
46
+ so we want integrity — just not anonymity).
47
+ - **The materialized view is a pure fold** over the event set, so two nodes with
48
+ the same events compute byte-identical state. Conflicts on mutable scalar
49
+ fields resolve by **Last-Writer-Wins keyed on a Hybrid Logical Clock**, not
50
+ wall time and not arrival order — so concurrent edits from two islands pick the
51
+ same winner everywhere.
52
+
53
+ ## Anti-entropy protocol (the entire thing)
54
+
55
+ ```
56
+ when two peers can talk:
57
+ each sends its FRONTIER = {author: high_water_seq}
58
+ on receiving a peer's frontier:
59
+ push the slice of every feed above the peer's marks (chunked)
60
+ ingest is idempotent + gap-buffering, so overlaps/reorders are harmless
61
+ ```
62
+
63
+ Multi-hop convergence is automatic: a node relays *every* author's events it
64
+ holds, not just its own, so A's events reach C through B even if A and C never
65
+ meet. That's the store-and-forward property, achieved without special-casing it.
66
+
67
+ ## Layout
68
+
69
+ ```
70
+ meshlog/
71
+ hlc.py Hybrid Logical Clock
72
+ event.py immutable, hash-chained, content-addressed Event
73
+ feedstore.py append-only per-author log; frontier + delta computation
74
+ reducer.py deterministic fold -> materialized records (Kobo-style)
75
+ transport.py Transport interface + in-memory SimTransport (partitions)
76
+ node.py Node + the anti-entropy protocol
77
+ rns_transport.py real Reticulum transport (Link + Resource + announce)
78
+ demo_sim.py base camp + 4 teams converge across staged partitions
79
+ test_convergence.py 200 randomized partition trials + fold-determinism check
80
+ meshlog/cli.py CLI to run a node over a live Reticulum mesh (the `meshlogd` command)
81
+ ```
82
+
83
+ ## Run it (no radios needed)
84
+
85
+ ```bash
86
+ python -m demo_sim # scripted scenario, prints the converged dataset
87
+ python -m test_convergence # 200 randomized partition/merge trials
88
+ ```
89
+
90
+ The demo islands three groups, has each collect independently, stages a
91
+ conflicting concurrent edit, then heals the network in stages and verifies every
92
+ node ends with identical frontiers, identical views, and the same LWW winner.
93
+
94
+ ## Run it for real (over Reticulum)
95
+
96
+ ```bash
97
+ pip install "meshlogd[radio]" # pulls in Reticulum (rns)
98
+ # Machine A:
99
+ meshlogd --name base --data base.jsonl --create R-100 site_assessment
100
+ # Machine B (same LAN to start; add a LoRa interface in ~/.reticulum/config later):
101
+ meshlogd --name team_a --data team_a.jsonl --create R-200 water_point
102
+ # type `view` at either prompt to watch the dataset converge
103
+ ```
104
+
105
+ ## Verification status
106
+
107
+ - `feedstore`, `reducer`, `hlc`, `node`, `transport`, the demo, and the 200
108
+ randomized trials **run and pass** as committed.
109
+ - `rns_transport.py` / `meshlog/cli.py` are written against the Reticulum 1.3.x API
110
+ (Identity, Destination, Link, Resource, Packet, announce handlers) and are
111
+ faithful to the docs/examples, but have **not** been exercised on a live mesh
112
+ here. Stand up two instances to validate end-to-end before field use.
113
+
114
+ ## Deliberately left as extension points
115
+
116
+ - **Attachments / blobs.** Events carry a content hash + size; the bytes are not
117
+ inlined. Add a content-addressed blob store and transfer blobs lazily over RNS
118
+ Resources, *after* structured events, so photos never starve assessment data on
119
+ a slow link.
120
+ - **Signatures.** `Event.is_authentic()` currently checks the content hash. With
121
+ RNS you already hold each author's Ed25519 key — sign the event id and verify
122
+ on ingest to close the trusted-but-verify loop.
123
+ - **Wire codec.** Prototype uses JSON for readability. Swap `_encode/_decode` for
124
+ MessagePack or CBOR to cut bytes on the radio.
125
+ - **Compaction / snapshots.** Grow-only logs grow. Add periodic signed snapshots
126
+ + feed truncation once a quorum has acknowledged a watermark.
127
+ - **Kobo bridge.** Poll the KoboToolbox/ODK submission API (or read KoboCollect
128
+ instances) and translate each submission into `record.create` + `field.set`
129
+ events. That's the actual on-ramp to the HHI use case.
130
+
131
+ ## Reading list (steal from these)
132
+
133
+ - **Secure Scuttlebutt** — append-only per-author feeds + gossip replication for
134
+ intermittent offline networks. This design is a close cousin.
135
+ - **CRDTs** — why union-based / LWW-register merges converge.
136
+ - **Kulkarni et al. 2014, Hybrid Logical Clocks** — the clock used here.
137
+ - **Reticulum manual**, Understanding + API Reference chapters — Link, Resource,
138
+ and the announce mechanism.
@@ -0,0 +1,151 @@
1
+ """Scenario demo: a shared assessment dataset converging across a partitioning mesh.
2
+
3
+ Five nodes -- a base camp and four field teams -- collect KoboToolbox-style
4
+ assessment records while the network is islanded, then reconcile as partitions
5
+ heal. We also stage a *concurrent conflicting edit* to the same field from two
6
+ separated islands, and show that last-writer-wins resolves to the same winner on
7
+ every node once they converge.
8
+
9
+ Run: python -m demo_sim (from the project root)
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+
15
+ from meshlog import Node
16
+ from meshlog.hlc import HLC
17
+ from meshlog.transport import SimNetwork, SimTransport
18
+
19
+
20
+ def make_clock(start_ms: int):
21
+ """A controllable physical clock so the demo is deterministic and we can
22
+ stage 'team B edits later than team A' precisely."""
23
+ state = {"t": start_ms}
24
+
25
+ def phys():
26
+ state["t"] += 1
27
+ return state["t"]
28
+
29
+ return phys, state
30
+
31
+
32
+ def settle(nodes, rounds=6):
33
+ """Run gossip rounds until quiet. With a fixed partition, a couple of rounds
34
+ suffice; we run extra for good measure."""
35
+ for _ in range(rounds):
36
+ for n in nodes.values():
37
+ n.gossip_round()
38
+
39
+
40
+ def frontiers_equal(nodes) -> bool:
41
+ fs = [json.dumps(n.frontier(), sort_keys=True) for n in nodes.values()]
42
+ return len(set(fs)) == 1
43
+
44
+
45
+ def views_equal(nodes) -> bool:
46
+ vs = [json.dumps(n.view(), sort_keys=True) for n in nodes.values()]
47
+ return len(set(vs)) == 1
48
+
49
+
50
+ def report(label, nodes):
51
+ print(f"\n--- {label} ---")
52
+ for name, n in nodes.items():
53
+ print(f" {name:6s} events held: {n.store.event_count():2d} "
54
+ f"records: {len(n.view()):2d}")
55
+
56
+
57
+ def main():
58
+ net = SimNetwork()
59
+ names = ["base", "team_a", "team_b", "team_c", "team_d"]
60
+
61
+ # Give each node its own controllable clock, staggered so HLC ties are
62
+ # meaningful and team_b's later edit deterministically wins the conflict.
63
+ nodes: dict[str, Node] = {}
64
+ for i, name in enumerate(names):
65
+ phys, _ = make_clock(1_000_000 + i) # distinct starting points
66
+ t = SimTransport(name, net)
67
+ nodes[name] = Node(name, t, hlc=HLC(_phys=phys))
68
+
69
+ print("=" * 64)
70
+ print("meshlog convergence demo: base camp + 4 field teams")
71
+ print("=" * 64)
72
+
73
+ # ---------------------------------------------------------------
74
+ # Phase 1: TOTAL PARTITION. Three islands, each collecting data.
75
+ # island 1: base
76
+ # island 2: team_a, team_b
77
+ # island 3: team_c, team_d
78
+ # ---------------------------------------------------------------
79
+ net.set_partitions([{"base"}, {"team_a", "team_b"}, {"team_c", "team_d"}])
80
+
81
+ nodes["base"].create_record("R-100", "site_assessment")
82
+ nodes["base"].set_field("R-100", "site_name", "North Ridge Camp")
83
+ nodes["base"].set_field("R-100", "status", "OPENED")
84
+
85
+ nodes["team_a"].create_record("R-200", "water_point")
86
+ nodes["team_a"].set_field("R-200", "location", "well by the river")
87
+ nodes["team_a"].set_field("R-200", "functional", True)
88
+ nodes["team_b"].create_record("R-201", "shelter_count")
89
+ nodes["team_b"].set_field("R-201", "tents", 48)
90
+
91
+ nodes["team_c"].create_record("R-300", "medical_need")
92
+ nodes["team_c"].set_field("R-300", "triage", "yellow")
93
+ nodes["team_d"].add_note("R-300", "team_d corroborates: 2 cases need evac")
94
+
95
+ # Staged CONFLICT: both base and team_a set R-100.status while partitioned.
96
+ # team_a's clock is later, so its value must win everywhere after merge.
97
+ nodes["base"].set_field("R-100", "status", "OPENED") # earlier
98
+ nodes["team_a"].set_field("R-100", "status", "AT_CAPACITY") # later -> winner
99
+
100
+ # Gossip *within* each island only (partitions block cross-island traffic).
101
+ settle(nodes)
102
+ report("Phase 1: total partition (3 islands collect independently)", nodes)
103
+ print(" frontiers identical across all nodes? ", frontiers_equal(nodes))
104
+
105
+ # ---------------------------------------------------------------
106
+ # Phase 2: PARTIAL HEAL. Base reconnects with island 2.
107
+ # ---------------------------------------------------------------
108
+ net.set_partitions([{"base", "team_a", "team_b"}, {"team_c", "team_d"}])
109
+ settle(nodes)
110
+ report("Phase 2: base + team_a + team_b merged (team_c/d still islanded)", nodes)
111
+
112
+ # ---------------------------------------------------------------
113
+ # Phase 3: FULL HEAL. Everyone reachable; converge.
114
+ # ---------------------------------------------------------------
115
+ net.set_partitions([{"base", "team_a", "team_b", "team_c", "team_d"}])
116
+ settle(nodes)
117
+ report("Phase 3: full heal", nodes)
118
+
119
+ # ---------------------------------------------------------------
120
+ # Verify convergence.
121
+ # ---------------------------------------------------------------
122
+ print("\n" + "=" * 64)
123
+ ok_front = frontiers_equal(nodes)
124
+ ok_views = views_equal(nodes)
125
+ print(f" all frontiers identical? {ok_front}")
126
+ print(f" all materialized views equal? {ok_views}")
127
+
128
+ winner = nodes["base"].view()["R-100"]["fields"]["status"]
129
+ print(f" conflict R-100.status resolved to: {winner!r} "
130
+ f"(expected 'AT_CAPACITY', team_b's later HLC wins)")
131
+ same_winner = all(
132
+ n.view()["R-100"]["fields"]["status"] == winner for n in nodes.values()
133
+ )
134
+ print(f" every node agrees on the winner? {same_winner}")
135
+
136
+ print("\n Final converged dataset (from base camp's view):")
137
+ print(json.dumps(nodes["base"].view(), indent=2, sort_keys=True))
138
+
139
+ print("\n" + "=" * 64)
140
+ if ok_front and ok_views and same_winner and winner == "AT_CAPACITY":
141
+ print(" RESULT: ALL NODES CONVERGED [PASS]")
142
+ else:
143
+ print(" RESULT: divergence detected [FAIL]")
144
+ raise SystemExit(1)
145
+ print(f" network carried {net.messages_sent} messages, "
146
+ f"{net.bytes_sent} bytes total")
147
+ print("=" * 64)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()