hydo-assert 0.2.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,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 [yyyy] [name of copyright owner]
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,238 @@
1
+ Metadata-Version: 2.4
2
+ Name: hydo-assert
3
+ Version: 0.2.0
4
+ Summary: Assertion SDK for programs tested under hydo, a deterministic hypervisor (always/sometimes properties, BUGGIFY fault points, bounded liveness, operation histories)
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/kakoc/hydo
7
+ Project-URL: Documentation, https://github.com/kakoc/hydo/tree/main/sdk/python#readme
8
+ Project-URL: Repository, https://github.com/kakoc/hydo
9
+ Project-URL: Issues, https://github.com/kakoc/hydo/issues
10
+ Keywords: testing,assertions,deterministic,fault-injection,simulation,hydo
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # hydo-assert: the Python assertion SDK
24
+
25
+ A Python program running under hydo (the deterministic hypervisor of
26
+ [github.com/kakoc/hydo](https://github.com/kakoc/hydo)) uses this package to say what must be
27
+ true and what should happen at least once. It writes the same console records as the Go SDK
28
+ (`sdk/go`), byte for byte, with the same deduplication rules, so `hydo run` and the explorer
29
+ (`hydo explore`) read them unchanged. The wire format and the verdict
30
+ rules are in `hydo/ASSERTIONS.md` of that repository; paths below are relative to it.
31
+
32
+ - Distribution name `hydo-assert`, import name `hydo_assert`.
33
+ - Standard library only; Python 3.8 or later; thread-safe and safe to call from asyncio code.
34
+ - Install it from PyPI (`pip install hydo-assert`), or from a checkout (`pip install ./sdk/python`),
35
+ or put `sdk/python/src` on `PYTHONPATH`, or copy `src/hydo_assert/` into the guest image (the
36
+ `hydo/onboard/examples/python-kv` example does that).
37
+
38
+ ## Use
39
+
40
+ ```python
41
+ import hydo_assert as ha
42
+
43
+ # Declare at module level: the catalog is complete once the module is imported.
44
+ ACKED = ha.always("kv.acked_durable", "every acknowledged PUT reads back with its value")
45
+ PARSES = ha.always_or_unreachable("kv.log_parses", "every complete log line parses on replay")
46
+ SIZE = ha.always("kv.log_size", "the log holds at most 10000 entries")
47
+ REPLAYED = ha.sometimes("kv.recovered", "the server replayed a non-empty log at start")
48
+ TORN = ha.reachable("kv.torn_tail", "the log ended in a partial line")
49
+ BAD = ha.unreachable("kv.bad_command", "the server got a command it does not know")
50
+ BACK = ha.eventually("kv.back", "the server answers within 5 s", 5.0) # seconds or timedelta
51
+ LOST = ha.buggify("kv.put.lost_reply", "the PUT is logged but its reply is lost")
52
+
53
+ ha.catalog() # once, early: the HYDO-ASSERT-DECL lines
54
+ ACKED.check(got == want, {"key": k, "got": got}) # returns bool(cond)
55
+ REPLAYED.check(n > 0, {"entries": n})
56
+ TORN.hit({"bytes": len(tail)})
57
+ BAD.hit()
58
+ SIZE.cmp(n, "<=", 10000) # details: left, op, right
59
+ if LOST.fire({"key": k}): # BUGGIFY fault point
60
+ return
61
+ BACK.await_cond(lambda: ping() == "PONG", poll=0.2) # blocks; one record
62
+ w = BACK.begin(); ...; w.done() # or: anchor now, condition true now / w.expire()
63
+ ha.setup_complete() # HYDO-SETUP-COMPLETE
64
+ ```
65
+
66
+ In asyncio code use `await BACK.await_async(cond, poll)`: `cond` may be a plain function or an
67
+ `async def`, and the wait between checks is `asyncio.sleep`. Every other call is a short write
68
+ to the console under one process-wide lock that is never held across a blocking call or an
69
+ `await`, so it is safe from coroutines and from threads.
70
+
71
+ | Go SDK (`hydoassert`) | Python (`hydo_assert`) |
72
+ |---|---|
73
+ | `Always(id, msg)`, `AlwaysOrUnreachable`, `Sometimes`, `Reachable`, `Unreachable` | `always(id, msg)`, `always_or_unreachable`, `sometimes`, `reachable`, `unreachable` (return an `Assertion`) |
74
+ | `a.Check(cond, d)`, `a.Hit(d)` | `a.check(cond, details=None)`, `a.hit(details=None)` |
75
+ | `a.Cmp(left, op, right, d)` | `a.cmp(left, op, right, details=None)` (`op` is one of `<`, `<=`, `==`, `!=`, `>=`, `>`) |
76
+ | `Eventually(id, msg, within)`, `l.Await(cond, poll, d)`, `l.Begin()`, `w.Done(d)`, `w.Expire(d)` | `eventually(id, msg, within)`, `l.await_cond(cond, poll, details=None)`, `await l.await_async(cond, poll, details=None)`, `l.begin()`, `w.done(details=None)`, `w.expire(details=None)` |
77
+ | `Buggify(id, msg)`, `p.Fire(d)` | `buggify(id, msg)`, `p.fire(details=None)` |
78
+ | `Catalog()`, `SetupComplete()` | `catalog()`, `setup_complete()` |
79
+ | `D{...}` | any mapping (a `dict`); `hydo_assert.D` is `dict` |
80
+
81
+ The naming follows the other SDKs (`sdk/js`, `sdk/rust`): the Go names in Python's snake case,
82
+ and `await_cond` / `await_async` for Go's `Await`. That table, `Liveness`, `Watch` and `Point`
83
+ (the classes the calls return) and the history recorder below are the whole API: a comparison
84
+ has one form, `cmp` with its operator, and names that start with `_` (the modules `_core`,
85
+ `_buggify`, `_eventually`, `_json`, `_sink`) are the package's own.
86
+
87
+ ## Records, deduplication, catalog
88
+
89
+ - Records go to `/dev/ttyS0` (opened once, `O_WRONLY|O_APPEND|O_NOCTTY`, one `write` per
90
+ record). `HYDO_ASSERT_OUT=<path>` writes to that existing file, `stderr` to standard error
91
+ (plain logging outside hydo), `off` nowhere, and `logging` (Python only) logs each record line
92
+ at INFO on the logger `hydo_assert`. If the file cannot be opened, standard error is used.
93
+ - A process writes each (assertion, outcome) pair once: the first pass and the first failure,
94
+ with the details of that evaluation. A `sometimes` that evaluated false is never written.
95
+ `unreachable` is written with `ok:false`. A record whose details hold a NaN or an infinity is
96
+ not written at all, but still counts as written (as in Go, where `json.Marshal` fails after
97
+ the pair was marked).
98
+ - The catalog (`catalog()`) lists every declared assertion in declaration order: the order in
99
+ which the declaring statements ran, which for module-level declarations is the import order.
100
+ A module that is never imported contributes nothing; import it before calling `catalog()`.
101
+ Call `catalog()` in the process whose console output is collected for each run (for a
102
+ server started before the explorer's snapshot point, that is a client or the oracle, not the
103
+ server; see the example).
104
+ - Details are encoded exactly as Go's `encoding/json` encodes the equivalent Go value: keys in
105
+ UTF-8 byte order, `<`, `>`, `&`, U+2028 and U+2029 escaped, other non-ASCII text raw, Go's
106
+ float format (`1e+21`, `1.5e-7`, `3` for `3.0`, `-0`). The caller's dict is never changed
107
+ (Go adds `left`/`op`/`right`, `hit`, `elapsed_ms` to the caller's map; Python adds them to a
108
+ copy, which gives the same record).
109
+ - Python values Go has no form for: a tuple is an array; `bytes` is a base64 string (as Go
110
+ encodes `[]byte`); a set is an array sorted by encoded element; integer dict keys are written
111
+ in decimal; any other object is the string `str(obj)`. A lone surrogate (an undecodable byte
112
+ read with `surrogateescape`) is written as `\ufffd`, as the pinned guest Go 1.26.5 writes an
113
+ invalid UTF-8 byte (Go 1.27 writes a raw U+FFFD instead).
114
+ - `details` that is not a mapping is wrapped as `{"value": details}`.
115
+ - After `os.fork()` the child keeps the parent's deduplication state (it is one program's
116
+ history) and gets fresh locks.
117
+
118
+ ## BUGGIFY
119
+
120
+ Same decisions as the Go SDK: configured by `$HYDO_BUGGIFY`, or else the file
121
+ `$HYDO_BUGGIFY_FILE` (default `/tmp/hydo-buggify`), holding
122
+ `<seed-hex>[,<enable-permille>[,<fire-permille>]]` (defaults 250 and 250, FoundationDB's
123
+ values), parsed as Go's `strconv.ParseUint` does (no `0x`, no sign, no spaces inside a field;
124
+ an unparsable seed leaves BUGGIFY off, an unparsable permille keeps its default). It is read
125
+ once, at the first evaluation of any point, which also writes
126
+ `HYDO-BUGGIFY {"seed":..,"enable_pm":..,"fire_pm":..,"enabled":[..]}`. A point is enabled
127
+ for the run when `splitmix64(seed ^ fnv1a(id)) % 1000 < enable`; its k-th evaluation fires
128
+ when `splitmix64(splitmix64(seed ^ fnv1a(id)) + k·0x9e3779b97f4a7c15) % 1000 < fire`. Each
129
+ point is also a `sometimes` property `buggify.<id>` ("fault point fired: <msg>"), recorded at
130
+ its first firing with `{"hit": k}`. Without a configuration every point returns False and has
131
+ no other effect. Under hydo the schedule token `B=<seed>` (`hydo explore --buggify`) reaches the
132
+ file through the guest init: an onboarded project gets it with `buggify: true` in its
133
+ `hydo.yaml` (`hydo/onboard/MANIFEST.md`).
134
+
135
+ ## History recorder
136
+
137
+ The module `hydo_assert.history` records operation histories for hydo's host-side checkers
138
+ (linearizability of a register or compare-and-set object per key, and Elle-style list-append;
139
+ the format and the checkers are in `hydo/HISTORIES.md`). It writes the same `HYDO-HIST` lines as
140
+ the Go recorder (`sdk/go/hydohist`), byte for byte except the time field. It is a separate
141
+ module: `import hydo_assert` does not load it, so the assertion records are unchanged.
142
+
143
+ ```python
144
+ from hydo_assert import history as hh
145
+
146
+ kv = hh.History("kv")
147
+ op = kv.invoke(3, "write", "k1", hh.enc(v)) # process 3, before the request
148
+ try:
149
+ rev = put("k1", v)
150
+ op.ok("k1", hh.ver(v, rev)) # the version the store assigned, if any
151
+ except Rejected:
152
+ op.fail() # it definitely had no effect
153
+ except Exception:
154
+ op.info() # a timeout: the outcome is unknown
155
+ kv.invoke(3, "read", "k1").ok("k1", hh.value_or_nil(get("k1"))) # None means absent
156
+
157
+ la = hh.History("la")
158
+ tx = la.invoke(4, "txn", hh.append_mop("x", "1"), hh.read_mop("y"))
159
+ tx.ok(hh.append_mop("x", "1"), hh.read_result_mop("y", "1", "2"))
160
+ ```
161
+
162
+ | Go (`hydohist`) | Python (`hydo_assert.history`) |
163
+ |---|---|
164
+ | `New(name)` | `History(name)` |
165
+ | `h.Invoke(proc, f, args...)`, `h.Record(proc, typ, f, args...)` | `h.invoke(proc, f, *args)`, `h.record(proc, typ, f, *args)` |
166
+ | `op.Ok(args...)`, `op.Fail()`, `op.Info()` | `op.ok(*args)` (no args repeats the invocation's), `op.fail()`, `op.info()` |
167
+ | `Enc`, `Ver`, `ValOrNil(v, ok)`, `List` | `enc`, `ver`, `value_or_nil(v)` (None means absent), `list_value` |
168
+ | `Append`, `Read`, `ReadResult`, `Nil` | `append_mop`, `read_mop`, `read_result_mop`, `NIL` |
169
+
170
+ - `list_value` has a longer name than Go's `List` so that it does not hide the builtin `list`
171
+ for a program that uses `from hydo_assert.history import *`. The micro-op helpers have the
172
+ Rust SDK's names.
173
+ - A process is an int or a token without spaces. Arguments are tokens: a `str` is written as
174
+ it is (encode free-form values with `enc`), an `int` is written in decimal, and `bytes` are
175
+ written as they are. Versions are int64 values; a value outside that range raises
176
+ `ValueError`, and a value that is not an int (including `bool`) raises `TypeError`.
177
+ - Records go to `/dev/console`. `HYDO_HIST_OUT=<path>` appends to that file and creates it if
178
+ it is missing (mode 0644), `stderr` writes to standard error, and `off` writes nothing. If the
179
+ file cannot be opened, standard error is used. The setting is read once, at the first record,
180
+ and is separate from `HYDO_ASSERT_OUT`.
181
+ - Each record is one `os.write` call made under a lock, so threads never interleave lines. The
182
+ time field is `time.monotonic_ns()` (CLOCK_MONOTONIC on Linux, deterministic under hydo). It
183
+ is read under the lock, so the times of successive lines never decrease; Go reads it just
184
+ before its lock, and the line format is the same. A forked child gets a new lock and keeps the
185
+ descriptor.
186
+ - Text is written as UTF-8. A `str` is encoded with the `surrogateescape` rule, so a string
187
+ that came from bytes that way (`os.fsdecode`, `sys.argv`, `os.environ`, or `enc` of bytes)
188
+ gives back its original bytes. Any other lone surrogate is written as U+FFFD. `enc` of
189
+ `bytes` keeps invalid UTF-8 bytes as they are, as Go's `Enc` does, and returns them as
190
+ surrogateescape characters.
191
+ - A process has at most one operation in flight: give each concurrent client (thread or task)
192
+ its own process number. Record the invocation before sending the request and the completion
193
+ after the reply, because the checkers order operations by the position of their records.
194
+
195
+ ## Determinism
196
+
197
+ The records are a pure function of the program's evaluation sequence: no clocks (except the
198
+ guest's monotonic clock for `eventually`, which hvx makes deterministic), no host state,
199
+ catalog in declaration order, sorted keys. A Python program is itself deterministic under hydo:
200
+ the guest CRNG is seeded identically every run, so even the hash seed is the same; setting
201
+ `PYTHONHASHSEED=0` makes that independent of the CRNG. `PYTHONDONTWRITEBYTECODE=1` avoids
202
+ writing `.pyc` files on the guest's read-only root.
203
+
204
+ ## Tests
205
+
206
+ - `python3 -m unittest discover -s sdk/python/tests`: the encoder (Go's float and string
207
+ forms), deduplication, details not mutated, NaN, catalog order, 16 threads writing 2000
208
+ evaluations each without an interleaved line, asyncio `eventually`, fork, BUGGIFY decisions
209
+ and rates. Passes on Python 3.8.20 and 3.15.0.
210
+ - `tests/test_cases.py` (run by the same `unittest` command): the shared cases (`sdk/cases`,
211
+ written by the reference SDK, `sdk/rust`; format and rules in `sdk/rust/README.md`, "The
212
+ shared cases"). For every case and run it starts itself as a child process, makes the
213
+ case's calls with this package and `hydo_assert.history`, and compares the bytes the sink
214
+ received and the calls' results with the case's files: every assertion type, comparisons,
215
+ details with tricky values (invalid UTF-8 as `surrogateescape` characters), the catalog,
216
+ `eventually`, BUGGIFY under 18 configurations, `HYDO_ASSERT_OUT`, and the
217
+ history records with every helper and `HYDO_HIST_OUT` setting. Cases that need a float32
218
+ (`f32`) are skipped and listed. To add a case, add it to the Rust SDK's
219
+ `tests/cases/defs.rs` and run `HYDO_BLESS=1 cargo test --test cases` there; this test then
220
+ runs it. A format change starts in the Rust SDK too: after it is blessed, this test fails on
221
+ the lines this package must change. No other language is needed to run it. Passes on Python
222
+ 3.8.20 and 3.15.0.
223
+ - `tests/test_history.py` (run by the same `unittest` command): the exact lines of the Go
224
+ recorder's own unit test, the encoding of every byte class, the argument checks, the sink
225
+ settings, one `os.write` per record, 8 threads writing 400 records each without an
226
+ interleaved line, and fork.
227
+ - The files of `src/hydo_assert/` are copied into the python-kv example's images, so a change
228
+ to any of them changes those images' bytes and every python-kv fingerprint (the last such
229
+ change, a reworded comment in `_core.py`, re-recorded them in milestone 157;
230
+ docs/REBASELINE.md has the values).
231
+
232
+ ## Limits
233
+
234
+ - No call-site form that registers itself before it runs (the Rust SDK's macros do that with a
235
+ linker section). A Python assertion is in the catalog once the statement that declares it has
236
+ run, so declare at module level.
237
+ - `cmp` compares any two Python values that support the operator; values that cannot be
238
+ compared evaluate to false. Go's `Cmp` takes only `int64`.
@@ -0,0 +1,216 @@
1
+ # hydo-assert: the Python assertion SDK
2
+
3
+ A Python program running under hydo (the deterministic hypervisor of
4
+ [github.com/kakoc/hydo](https://github.com/kakoc/hydo)) uses this package to say what must be
5
+ true and what should happen at least once. It writes the same console records as the Go SDK
6
+ (`sdk/go`), byte for byte, with the same deduplication rules, so `hydo run` and the explorer
7
+ (`hydo explore`) read them unchanged. The wire format and the verdict
8
+ rules are in `hydo/ASSERTIONS.md` of that repository; paths below are relative to it.
9
+
10
+ - Distribution name `hydo-assert`, import name `hydo_assert`.
11
+ - Standard library only; Python 3.8 or later; thread-safe and safe to call from asyncio code.
12
+ - Install it from PyPI (`pip install hydo-assert`), or from a checkout (`pip install ./sdk/python`),
13
+ or put `sdk/python/src` on `PYTHONPATH`, or copy `src/hydo_assert/` into the guest image (the
14
+ `hydo/onboard/examples/python-kv` example does that).
15
+
16
+ ## Use
17
+
18
+ ```python
19
+ import hydo_assert as ha
20
+
21
+ # Declare at module level: the catalog is complete once the module is imported.
22
+ ACKED = ha.always("kv.acked_durable", "every acknowledged PUT reads back with its value")
23
+ PARSES = ha.always_or_unreachable("kv.log_parses", "every complete log line parses on replay")
24
+ SIZE = ha.always("kv.log_size", "the log holds at most 10000 entries")
25
+ REPLAYED = ha.sometimes("kv.recovered", "the server replayed a non-empty log at start")
26
+ TORN = ha.reachable("kv.torn_tail", "the log ended in a partial line")
27
+ BAD = ha.unreachable("kv.bad_command", "the server got a command it does not know")
28
+ BACK = ha.eventually("kv.back", "the server answers within 5 s", 5.0) # seconds or timedelta
29
+ LOST = ha.buggify("kv.put.lost_reply", "the PUT is logged but its reply is lost")
30
+
31
+ ha.catalog() # once, early: the HYDO-ASSERT-DECL lines
32
+ ACKED.check(got == want, {"key": k, "got": got}) # returns bool(cond)
33
+ REPLAYED.check(n > 0, {"entries": n})
34
+ TORN.hit({"bytes": len(tail)})
35
+ BAD.hit()
36
+ SIZE.cmp(n, "<=", 10000) # details: left, op, right
37
+ if LOST.fire({"key": k}): # BUGGIFY fault point
38
+ return
39
+ BACK.await_cond(lambda: ping() == "PONG", poll=0.2) # blocks; one record
40
+ w = BACK.begin(); ...; w.done() # or: anchor now, condition true now / w.expire()
41
+ ha.setup_complete() # HYDO-SETUP-COMPLETE
42
+ ```
43
+
44
+ In asyncio code use `await BACK.await_async(cond, poll)`: `cond` may be a plain function or an
45
+ `async def`, and the wait between checks is `asyncio.sleep`. Every other call is a short write
46
+ to the console under one process-wide lock that is never held across a blocking call or an
47
+ `await`, so it is safe from coroutines and from threads.
48
+
49
+ | Go SDK (`hydoassert`) | Python (`hydo_assert`) |
50
+ |---|---|
51
+ | `Always(id, msg)`, `AlwaysOrUnreachable`, `Sometimes`, `Reachable`, `Unreachable` | `always(id, msg)`, `always_or_unreachable`, `sometimes`, `reachable`, `unreachable` (return an `Assertion`) |
52
+ | `a.Check(cond, d)`, `a.Hit(d)` | `a.check(cond, details=None)`, `a.hit(details=None)` |
53
+ | `a.Cmp(left, op, right, d)` | `a.cmp(left, op, right, details=None)` (`op` is one of `<`, `<=`, `==`, `!=`, `>=`, `>`) |
54
+ | `Eventually(id, msg, within)`, `l.Await(cond, poll, d)`, `l.Begin()`, `w.Done(d)`, `w.Expire(d)` | `eventually(id, msg, within)`, `l.await_cond(cond, poll, details=None)`, `await l.await_async(cond, poll, details=None)`, `l.begin()`, `w.done(details=None)`, `w.expire(details=None)` |
55
+ | `Buggify(id, msg)`, `p.Fire(d)` | `buggify(id, msg)`, `p.fire(details=None)` |
56
+ | `Catalog()`, `SetupComplete()` | `catalog()`, `setup_complete()` |
57
+ | `D{...}` | any mapping (a `dict`); `hydo_assert.D` is `dict` |
58
+
59
+ The naming follows the other SDKs (`sdk/js`, `sdk/rust`): the Go names in Python's snake case,
60
+ and `await_cond` / `await_async` for Go's `Await`. That table, `Liveness`, `Watch` and `Point`
61
+ (the classes the calls return) and the history recorder below are the whole API: a comparison
62
+ has one form, `cmp` with its operator, and names that start with `_` (the modules `_core`,
63
+ `_buggify`, `_eventually`, `_json`, `_sink`) are the package's own.
64
+
65
+ ## Records, deduplication, catalog
66
+
67
+ - Records go to `/dev/ttyS0` (opened once, `O_WRONLY|O_APPEND|O_NOCTTY`, one `write` per
68
+ record). `HYDO_ASSERT_OUT=<path>` writes to that existing file, `stderr` to standard error
69
+ (plain logging outside hydo), `off` nowhere, and `logging` (Python only) logs each record line
70
+ at INFO on the logger `hydo_assert`. If the file cannot be opened, standard error is used.
71
+ - A process writes each (assertion, outcome) pair once: the first pass and the first failure,
72
+ with the details of that evaluation. A `sometimes` that evaluated false is never written.
73
+ `unreachable` is written with `ok:false`. A record whose details hold a NaN or an infinity is
74
+ not written at all, but still counts as written (as in Go, where `json.Marshal` fails after
75
+ the pair was marked).
76
+ - The catalog (`catalog()`) lists every declared assertion in declaration order: the order in
77
+ which the declaring statements ran, which for module-level declarations is the import order.
78
+ A module that is never imported contributes nothing; import it before calling `catalog()`.
79
+ Call `catalog()` in the process whose console output is collected for each run (for a
80
+ server started before the explorer's snapshot point, that is a client or the oracle, not the
81
+ server; see the example).
82
+ - Details are encoded exactly as Go's `encoding/json` encodes the equivalent Go value: keys in
83
+ UTF-8 byte order, `<`, `>`, `&`, U+2028 and U+2029 escaped, other non-ASCII text raw, Go's
84
+ float format (`1e+21`, `1.5e-7`, `3` for `3.0`, `-0`). The caller's dict is never changed
85
+ (Go adds `left`/`op`/`right`, `hit`, `elapsed_ms` to the caller's map; Python adds them to a
86
+ copy, which gives the same record).
87
+ - Python values Go has no form for: a tuple is an array; `bytes` is a base64 string (as Go
88
+ encodes `[]byte`); a set is an array sorted by encoded element; integer dict keys are written
89
+ in decimal; any other object is the string `str(obj)`. A lone surrogate (an undecodable byte
90
+ read with `surrogateescape`) is written as `\ufffd`, as the pinned guest Go 1.26.5 writes an
91
+ invalid UTF-8 byte (Go 1.27 writes a raw U+FFFD instead).
92
+ - `details` that is not a mapping is wrapped as `{"value": details}`.
93
+ - After `os.fork()` the child keeps the parent's deduplication state (it is one program's
94
+ history) and gets fresh locks.
95
+
96
+ ## BUGGIFY
97
+
98
+ Same decisions as the Go SDK: configured by `$HYDO_BUGGIFY`, or else the file
99
+ `$HYDO_BUGGIFY_FILE` (default `/tmp/hydo-buggify`), holding
100
+ `<seed-hex>[,<enable-permille>[,<fire-permille>]]` (defaults 250 and 250, FoundationDB's
101
+ values), parsed as Go's `strconv.ParseUint` does (no `0x`, no sign, no spaces inside a field;
102
+ an unparsable seed leaves BUGGIFY off, an unparsable permille keeps its default). It is read
103
+ once, at the first evaluation of any point, which also writes
104
+ `HYDO-BUGGIFY {"seed":..,"enable_pm":..,"fire_pm":..,"enabled":[..]}`. A point is enabled
105
+ for the run when `splitmix64(seed ^ fnv1a(id)) % 1000 < enable`; its k-th evaluation fires
106
+ when `splitmix64(splitmix64(seed ^ fnv1a(id)) + k·0x9e3779b97f4a7c15) % 1000 < fire`. Each
107
+ point is also a `sometimes` property `buggify.<id>` ("fault point fired: <msg>"), recorded at
108
+ its first firing with `{"hit": k}`. Without a configuration every point returns False and has
109
+ no other effect. Under hydo the schedule token `B=<seed>` (`hydo explore --buggify`) reaches the
110
+ file through the guest init: an onboarded project gets it with `buggify: true` in its
111
+ `hydo.yaml` (`hydo/onboard/MANIFEST.md`).
112
+
113
+ ## History recorder
114
+
115
+ The module `hydo_assert.history` records operation histories for hydo's host-side checkers
116
+ (linearizability of a register or compare-and-set object per key, and Elle-style list-append;
117
+ the format and the checkers are in `hydo/HISTORIES.md`). It writes the same `HYDO-HIST` lines as
118
+ the Go recorder (`sdk/go/hydohist`), byte for byte except the time field. It is a separate
119
+ module: `import hydo_assert` does not load it, so the assertion records are unchanged.
120
+
121
+ ```python
122
+ from hydo_assert import history as hh
123
+
124
+ kv = hh.History("kv")
125
+ op = kv.invoke(3, "write", "k1", hh.enc(v)) # process 3, before the request
126
+ try:
127
+ rev = put("k1", v)
128
+ op.ok("k1", hh.ver(v, rev)) # the version the store assigned, if any
129
+ except Rejected:
130
+ op.fail() # it definitely had no effect
131
+ except Exception:
132
+ op.info() # a timeout: the outcome is unknown
133
+ kv.invoke(3, "read", "k1").ok("k1", hh.value_or_nil(get("k1"))) # None means absent
134
+
135
+ la = hh.History("la")
136
+ tx = la.invoke(4, "txn", hh.append_mop("x", "1"), hh.read_mop("y"))
137
+ tx.ok(hh.append_mop("x", "1"), hh.read_result_mop("y", "1", "2"))
138
+ ```
139
+
140
+ | Go (`hydohist`) | Python (`hydo_assert.history`) |
141
+ |---|---|
142
+ | `New(name)` | `History(name)` |
143
+ | `h.Invoke(proc, f, args...)`, `h.Record(proc, typ, f, args...)` | `h.invoke(proc, f, *args)`, `h.record(proc, typ, f, *args)` |
144
+ | `op.Ok(args...)`, `op.Fail()`, `op.Info()` | `op.ok(*args)` (no args repeats the invocation's), `op.fail()`, `op.info()` |
145
+ | `Enc`, `Ver`, `ValOrNil(v, ok)`, `List` | `enc`, `ver`, `value_or_nil(v)` (None means absent), `list_value` |
146
+ | `Append`, `Read`, `ReadResult`, `Nil` | `append_mop`, `read_mop`, `read_result_mop`, `NIL` |
147
+
148
+ - `list_value` has a longer name than Go's `List` so that it does not hide the builtin `list`
149
+ for a program that uses `from hydo_assert.history import *`. The micro-op helpers have the
150
+ Rust SDK's names.
151
+ - A process is an int or a token without spaces. Arguments are tokens: a `str` is written as
152
+ it is (encode free-form values with `enc`), an `int` is written in decimal, and `bytes` are
153
+ written as they are. Versions are int64 values; a value outside that range raises
154
+ `ValueError`, and a value that is not an int (including `bool`) raises `TypeError`.
155
+ - Records go to `/dev/console`. `HYDO_HIST_OUT=<path>` appends to that file and creates it if
156
+ it is missing (mode 0644), `stderr` writes to standard error, and `off` writes nothing. If the
157
+ file cannot be opened, standard error is used. The setting is read once, at the first record,
158
+ and is separate from `HYDO_ASSERT_OUT`.
159
+ - Each record is one `os.write` call made under a lock, so threads never interleave lines. The
160
+ time field is `time.monotonic_ns()` (CLOCK_MONOTONIC on Linux, deterministic under hydo). It
161
+ is read under the lock, so the times of successive lines never decrease; Go reads it just
162
+ before its lock, and the line format is the same. A forked child gets a new lock and keeps the
163
+ descriptor.
164
+ - Text is written as UTF-8. A `str` is encoded with the `surrogateescape` rule, so a string
165
+ that came from bytes that way (`os.fsdecode`, `sys.argv`, `os.environ`, or `enc` of bytes)
166
+ gives back its original bytes. Any other lone surrogate is written as U+FFFD. `enc` of
167
+ `bytes` keeps invalid UTF-8 bytes as they are, as Go's `Enc` does, and returns them as
168
+ surrogateescape characters.
169
+ - A process has at most one operation in flight: give each concurrent client (thread or task)
170
+ its own process number. Record the invocation before sending the request and the completion
171
+ after the reply, because the checkers order operations by the position of their records.
172
+
173
+ ## Determinism
174
+
175
+ The records are a pure function of the program's evaluation sequence: no clocks (except the
176
+ guest's monotonic clock for `eventually`, which hvx makes deterministic), no host state,
177
+ catalog in declaration order, sorted keys. A Python program is itself deterministic under hydo:
178
+ the guest CRNG is seeded identically every run, so even the hash seed is the same; setting
179
+ `PYTHONHASHSEED=0` makes that independent of the CRNG. `PYTHONDONTWRITEBYTECODE=1` avoids
180
+ writing `.pyc` files on the guest's read-only root.
181
+
182
+ ## Tests
183
+
184
+ - `python3 -m unittest discover -s sdk/python/tests`: the encoder (Go's float and string
185
+ forms), deduplication, details not mutated, NaN, catalog order, 16 threads writing 2000
186
+ evaluations each without an interleaved line, asyncio `eventually`, fork, BUGGIFY decisions
187
+ and rates. Passes on Python 3.8.20 and 3.15.0.
188
+ - `tests/test_cases.py` (run by the same `unittest` command): the shared cases (`sdk/cases`,
189
+ written by the reference SDK, `sdk/rust`; format and rules in `sdk/rust/README.md`, "The
190
+ shared cases"). For every case and run it starts itself as a child process, makes the
191
+ case's calls with this package and `hydo_assert.history`, and compares the bytes the sink
192
+ received and the calls' results with the case's files: every assertion type, comparisons,
193
+ details with tricky values (invalid UTF-8 as `surrogateescape` characters), the catalog,
194
+ `eventually`, BUGGIFY under 18 configurations, `HYDO_ASSERT_OUT`, and the
195
+ history records with every helper and `HYDO_HIST_OUT` setting. Cases that need a float32
196
+ (`f32`) are skipped and listed. To add a case, add it to the Rust SDK's
197
+ `tests/cases/defs.rs` and run `HYDO_BLESS=1 cargo test --test cases` there; this test then
198
+ runs it. A format change starts in the Rust SDK too: after it is blessed, this test fails on
199
+ the lines this package must change. No other language is needed to run it. Passes on Python
200
+ 3.8.20 and 3.15.0.
201
+ - `tests/test_history.py` (run by the same `unittest` command): the exact lines of the Go
202
+ recorder's own unit test, the encoding of every byte class, the argument checks, the sink
203
+ settings, one `os.write` per record, 8 threads writing 400 records each without an
204
+ interleaved line, and fork.
205
+ - The files of `src/hydo_assert/` are copied into the python-kv example's images, so a change
206
+ to any of them changes those images' bytes and every python-kv fingerprint (the last such
207
+ change, a reworded comment in `_core.py`, re-recorded them in milestone 157;
208
+ docs/REBASELINE.md has the values).
209
+
210
+ ## Limits
211
+
212
+ - No call-site form that registers itself before it runs (the Rust SDK's macros do that with a
213
+ linker section). A Python assertion is in the catalog once the statement that declares it has
214
+ run, so declare at module level.
215
+ - `cmp` compares any two Python values that support the operator; values that cannot be
216
+ compared evaluate to false. Go's `Cmp` takes only `int64`.