Spaces:
Running
Running
Release Afterkey 0.1.0 with benchmarks, ZeroMQ example and source kit
Browse files- LICENSE +202 -0
- README.md +75 -5
- bench/compare.cpp +285 -0
- bench/environment.md +42 -0
- bench/fanout.cpp +181 -0
- bench/fanout.json +14 -0
- bench/replay.cpp +87 -0
- bench/replay.md +42 -0
- bench/replay_prepare.py +63 -0
- bench/results.csv +26 -0
- demo/index.html +136 -0
- examples/quickstart.cpp +18 -0
- examples/streamsieve.cpp +94 -0
- examples/zmq_catchup.cpp +129 -0
- include/afterkey.hpp +144 -0
- include/afterkey_journal.hpp +177 -0
- index.html +134 -17
- releases/afterkey-0.1.0.zip +3 -0
- tests/test_afterkey.cpp +293 -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 [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.
|
README.md
CHANGED
|
@@ -1,10 +1,80 @@
|
|
| 1 |
---
|
| 2 |
title: Afterkey
|
| 3 |
-
emoji: 🦀
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: red
|
| 6 |
sdk: static
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Afterkey
|
|
|
|
|
|
|
|
|
|
| 3 |
sdk: static
|
| 4 |
+
app_file: demo/index.html
|
| 5 |
+
license: apache-2.0
|
| 6 |
+
short_description: C++17 latest-state updates for lagging readers
|
| 7 |
+
tags:
|
| 8 |
+
- cpp
|
| 9 |
+
- multi-agent
|
| 10 |
+
- streaming
|
| 11 |
+
- benchmarks
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Afterkey
|
| 15 |
+
|
| 16 |
+
**Let a slow reader catch up with one value per changed key.** Afterkey is a C++17 header for agent dashboards, worker state and telemetry fan-out. A producer overwrites a fixed set of keys. Each reader keeps one 64-bit cursor. A reader that sleeps through a million updates to the same key receives one row when it returns. Deletions travel through the same feed.
|
| 17 |
+
|
| 18 |
+
[Try two independent readers in your browser](https://afterkey.tancurl3.chatgpt.site) · [Download the source kit](https://raw.githubusercontent.com/pgg898200-ship-it/streamsieve/main/afterkey/releases/afterkey-0.1.0.zip) · [Reproduce the benchmarks](bench/environment.md)
|
| 19 |
+
|
| 20 |
+
## Run in 30 seconds
|
| 21 |
+
|
| 22 |
+
Download the standalone kit and run the example with a C++17 compiler. If you cloned StreamSieve, start in its `afterkey/` directory and run the last two commands.
|
| 23 |
+
|
| 24 |
+
```sh
|
| 25 |
+
curl -fsSLO https://raw.githubusercontent.com/pgg898200-ship-it/streamsieve/main/afterkey/releases/afterkey-0.1.0.zip
|
| 26 |
+
unzip -q afterkey-0.1.0.zip
|
| 27 |
+
cd afterkey-0.1.0
|
| 28 |
+
c++ -std=c++17 -O2 -Iinclude examples/quickstart.cpp -o /tmp/afterkey-demo
|
| 29 |
+
/tmp/afterkey-demo
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
The reader starts after revision 1. It receives the latest value for key 7 and the deletion of key 3, in that order.
|
| 33 |
+
|
| 34 |
+
```text
|
| 35 |
+
3 7 11
|
| 36 |
+
4 3 deleted
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
For an existing service, copy [include/afterkey.hpp](include/afterkey.hpp) into its include path. The header has no third-party dependencies. Each callback receives a revision, a dense key and a borrowed pointer to the absolute value. A null pointer means deletion. Advance the cursor only after your consumer has successfully applied the entire batch. Retrying after a partial failure can redeliver rows, so apply values and tombstones idempotently.
|
| 40 |
+
|
| 41 |
+
## Which workload benefits?
|
| 42 |
+
|
| 43 |
+
With 1,048,576 populated keys, 16 hot keys and 16 staggered readers, Index ran **2.04× faster than a cursor-indexed append log** and **1.15× faster than an equivalent std::list recency index**. The latter isolates the benefit of the dense slot representation. The machine was a shared AMD EPYC 9V74 VM. Each mixed operation is one write or one poll, and a poll can deliver many rows.
|
| 44 |
+
|
| 45 |
+
| Synthetic workload | Afterkey Index | Bounded Journal | Cursor log | std::list |
|
| 46 |
+
| --- | ---: | ---: | ---: | ---: |
|
| 47 |
+
| 1M populated keys, 16 hot | 5.60 | 20.47 | 11.45 | 6.42 |
|
| 48 |
+
| 16K populated keys, 16 hot | 4.41 | 13.09 | 10.41 | 6.06 |
|
| 49 |
+
| 16K populated keys, uniform writes | 421.46 | 134.77 | 121.63 | 546.34 |
|
| 50 |
+
|
| 51 |
+
Values are median elapsed nanoseconds per mixed operation across 5 or 9 trials. Timings include the callback and exclude initialization. The cursor log won under uniform churn. With broad changes, contiguous traversal makes the Journal a faster bounded-memory option in this workload. CPU-time medians, sample ranges, the full-map scan and additional cases are in the [results CSV](bench/results.csv).
|
| 52 |
+
|
| 53 |
+
With **4,096 independently lagging readers**, a second benchmark measured each synchronous catch-up call on one thread. For a moving hot set, p99 was **1.67 µs** for Index and **4.99 µs** for the cursor log. With uniform writes, p99 was **417.86 µs** and **75.92 µs** respectively. The timer includes the consuming callback. Queueing, network and producer time are excluded. [Latency harness](bench/fanout.cpp) · [Raw percentiles](bench/fanout.json)
|
| 54 |
+
|
| 55 |
+
The public replays check exact ordered outputs. On the FreeInference session trace an hourly reader received 64 rows for 1,375 recorded completions. On the Paris Vélib’ trace an hourly reader received 895,673 rows for 5,143,865 recorded writes. At one-minute intervals only 94 Paris writes were superseded. Poll schedules were simulated. These counts describe the work a reader can skip. [Sources, checksums and replay commands](bench/replay.md)
|
| 56 |
+
|
| 57 |
+
## Contracts and costs
|
| 58 |
+
|
| 59 |
+
| | Index | Journal |
|
| 60 |
+
| --- | --- | --- |
|
| 61 |
+
| Header | `afterkey.hpp` | `afterkey_journal.hpp` |
|
| 62 |
+
| Write | O(1) worst-case bookkeeping | O(1) amortized, O(capacity) on compaction |
|
| 63 |
+
| Read | O(1 + distinct keys touched since cursor) | Scans up to min(2 × capacity, writes since cursor) entries, plus a seek for older cursors |
|
| 64 |
+
| Storage | Dense slots, two 32-bit neighbor indices per slot | Dense slots plus a bounded chronological key journal |
|
| 65 |
+
|
| 66 |
+
Both implementations retain one current payload per live key and tombstones for erased keys. Their own storage is allocated at construction. Payloads and callbacks can allocate. Use an application-level dense ID mapping for strings or sparse IDs. Every put and erase advances the revision, including unchanged values and repeated erases. The index rejects future cursors, out-of-range keys and callback writes. Payloads must be nothrow-move-constructible and nothrow-destructible.
|
| 67 |
+
|
| 68 |
+
Run reads and writes on one event loop or serialize access externally. Cursors belong to one live instance. On process restart generate a new instance identifier, replace client state, and replay from zero. A client expanding its subscription also needs a fresh snapshot of added keys. For audit trails, increments, commands and intermediate transitions, retain a separate event log.
|
| 69 |
+
|
| 70 |
+
## Integrations
|
| 71 |
+
|
| 72 |
+
- [StreamSieve channel scores](examples/streamsieve.cpp) publishes absolute scores and checks that a dashboard and a slower observer both reconstruct the underlying native state.
|
| 73 |
+
- [ZeroMQ catch-up](examples/zmq_catchup.cpp) serves independent filtered readers over REQ/REP, including tombstones and reconnects to the same server instance. Its topic masks filter after index traversal. Build instructions are in the example. The multi-topic slow-consumer case was described in [libzmq issue 1688](https://github.com/zeromq/libzmq/issues/1688).
|
| 74 |
+
- [Randomized reference tests](tests/test_afterkey.cpp) exercise tombstones, callbacks, independent readers and historical cursors across compactions. Run `c++ -std=c++17 -O2 tests/test_afterkey.cpp -o /tmp/test-afterkey && /tmp/test-afterkey`.
|
| 75 |
+
|
| 76 |
+
## Prior art
|
| 77 |
+
|
| 78 |
+
Kubernetes already moves changed nodes to the head of a generation-ordered list and stops its snapshot walk when it reaches an old generation. CouchDB provides a durable document changes feed with latest-change semantics. Chronicle Ring offers conflation for low-latency messaging. Afterkey packages this pattern as a small, in-process C++ component with dense storage, ordered tombstones and reproducible crossover measurements. The measured competitors above are in-process C++ implementations. [Kubernetes scheduler source](https://cos.googlesource.com/third_party/kubernetes/+/4f5c634fcfa498e3634c9b6b31cc4ca4c6a1203c/pkg/scheduler/backend/cache/cache.go) · [CouchDB changes feed](https://docs.couchdb.org/en/stable/api/database/changes.html) · [Chronicle Ring](https://chronicle.software/products/chronicle-ring)
|
| 79 |
+
|
| 80 |
+
Afterkey source is licensed under [Apache-2.0](LICENSE). Trace datasets retain their respective licenses.
|
bench/compare.cpp
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "../include/afterkey.hpp"
|
| 2 |
+
#include "../include/afterkey_journal.hpp"
|
| 3 |
+
|
| 4 |
+
#include <algorithm>
|
| 5 |
+
#include <array>
|
| 6 |
+
#include <chrono>
|
| 7 |
+
#include <ctime>
|
| 8 |
+
#include <cstdint>
|
| 9 |
+
#include <iomanip>
|
| 10 |
+
#include <iostream>
|
| 11 |
+
#include <iterator>
|
| 12 |
+
#include <list>
|
| 13 |
+
#include <stdexcept>
|
| 14 |
+
#include <string>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
// All implementations expose the most recent change per key in revision order,
|
| 18 |
+
// including tombstones. Each reader advances its own cursor independently.
|
| 19 |
+
using U64 = std::uint64_t;
|
| 20 |
+
using Key = std::uint32_t;
|
| 21 |
+
|
| 22 |
+
struct Row {
|
| 23 |
+
U64 revision{};
|
| 24 |
+
U64 value{};
|
| 25 |
+
bool present{};
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
class State {
|
| 29 |
+
protected:
|
| 30 |
+
std::vector<Row> rows;
|
| 31 |
+
U64 clock{};
|
| 32 |
+
void change(Key k, U64 v, bool present) { rows[k] = {++clock, v, present}; }
|
| 33 |
+
template<class Sink>
|
| 34 |
+
void emit(Key k, Sink& sink) const {
|
| 35 |
+
const Row& r = rows[k];
|
| 36 |
+
sink(r.revision, k, r.present ? &r.value : nullptr);
|
| 37 |
+
}
|
| 38 |
+
public:
|
| 39 |
+
State(std::size_t capacity, std::size_t) : rows(capacity) {}
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
// Strong append-log baseline: cursor directly addresses the first candidate,
|
| 43 |
+
// then an array lookup skips stale log entries. Reserve even its future history.
|
| 44 |
+
class Log : public State {
|
| 45 |
+
std::vector<Key> log;
|
| 46 |
+
void write(Key k, U64 value, bool present) {
|
| 47 |
+
change(k, value, present);
|
| 48 |
+
log.push_back(k);
|
| 49 |
+
}
|
| 50 |
+
public:
|
| 51 |
+
Log(std::size_t n, std::size_t writes) : State(n, writes) { log.reserve(n + writes); }
|
| 52 |
+
void put(Key k, U64 v) { write(k, v, true); }
|
| 53 |
+
void erase(Key k) { write(k, 0, false); }
|
| 54 |
+
template<class Sink> void since(U64 cursor, Sink&& sink) const {
|
| 55 |
+
for (std::size_t i = cursor; i < log.size(); ++i) {
|
| 56 |
+
Key k = log[i];
|
| 57 |
+
if (rows[k].revision == i + 1) emit(k, sink);
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
};
|
| 61 |
+
|
| 62 |
+
// Latest stamp per slot. Scratch is reused. Sort the matches to honor the
|
| 63 |
+
// same oldest-to-newest callback order as the log and recency-list variants.
|
| 64 |
+
class Scan : public State {
|
| 65 |
+
std::vector<Key> matches;
|
| 66 |
+
public:
|
| 67 |
+
Scan(std::size_t n, std::size_t writes) : State(n, writes) { matches.reserve(n); }
|
| 68 |
+
void put(Key k, U64 v) { change(k, v, true); }
|
| 69 |
+
void erase(Key k) { change(k, 0, false); }
|
| 70 |
+
template<class Sink> void since(U64 cursor, Sink&& sink) {
|
| 71 |
+
matches.clear();
|
| 72 |
+
for (std::size_t k = 0; k < rows.size(); ++k) {
|
| 73 |
+
if (rows[k].revision > cursor) matches.push_back(static_cast<Key>(k));
|
| 74 |
+
}
|
| 75 |
+
std::sort(matches.begin(), matches.end(), [this](Key a, Key b) {
|
| 76 |
+
return rows[a].revision < rows[b].revision;
|
| 77 |
+
});
|
| 78 |
+
for (Key k : matches) emit(k, sink);
|
| 79 |
+
}
|
| 80 |
+
};
|
| 81 |
+
|
| 82 |
+
// Equivalent recency algorithm built from std::list. splice() reuses the node.
|
| 83 |
+
// Reverse discovery + forward emission is needed for ordered cursor results.
|
| 84 |
+
class List {
|
| 85 |
+
struct Node { Key key; Row row; };
|
| 86 |
+
std::list<Node> order;
|
| 87 |
+
std::vector<std::list<Node>::iterator> position;
|
| 88 |
+
U64 clock{};
|
| 89 |
+
void write(Key k, U64 v, bool present) {
|
| 90 |
+
auto i = position[k];
|
| 91 |
+
if (i == order.end()) position[k] = order.insert(i, {k, {++clock, v, present}});
|
| 92 |
+
else {
|
| 93 |
+
i->row = {++clock, v, present};
|
| 94 |
+
order.splice(order.end(), order, i);
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
public:
|
| 98 |
+
List(std::size_t n, std::size_t) : position(n, order.end()) {}
|
| 99 |
+
void put(Key k, U64 v) { write(k, v, true); }
|
| 100 |
+
void erase(Key k) { write(k, 0, false); }
|
| 101 |
+
template<class Sink> void since(U64 cursor, Sink&& sink) const {
|
| 102 |
+
if (cursor == clock) return;
|
| 103 |
+
auto start = order.begin();
|
| 104 |
+
if (start->row.revision <= cursor) {
|
| 105 |
+
start = order.end();
|
| 106 |
+
while (start != order.begin()) {
|
| 107 |
+
auto prev = std::prev(start);
|
| 108 |
+
if (prev->row.revision <= cursor) break;
|
| 109 |
+
start = prev;
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
for (auto i = start; i != order.end(); ++i) {
|
| 113 |
+
const Row& r = i->row;
|
| 114 |
+
sink(r.revision, i->key, r.present ? &r.value : nullptr);
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
};
|
| 118 |
+
|
| 119 |
+
class Afterkey : public afterkey::Index<U64> {
|
| 120 |
+
public:
|
| 121 |
+
Afterkey(std::size_t n, std::size_t) : afterkey::Index<U64>(n) {}
|
| 122 |
+
};
|
| 123 |
+
|
| 124 |
+
class Journal : public afterkey::Journal<U64> {
|
| 125 |
+
public:
|
| 126 |
+
Journal(std::size_t n, std::size_t) : afterkey::Journal<U64>(n) {}
|
| 127 |
+
};
|
| 128 |
+
|
| 129 |
+
enum class Kind { put, erase, read };
|
| 130 |
+
struct Op { Kind kind; Key key; U64 argument; };
|
| 131 |
+
struct Scenario {
|
| 132 |
+
const char* name;
|
| 133 |
+
unsigned hot_keys; // zero spans the full registry
|
| 134 |
+
unsigned writes_per_poll;
|
| 135 |
+
unsigned readers;
|
| 136 |
+
};
|
| 137 |
+
constexpr Scenario scenarios[] = {
|
| 138 |
+
{"hot-lag", 16, 2048, 16}, // 16 readers each revisit the same hot set
|
| 139 |
+
{"uniform-lag", 0, 2048, 16}, // same read schedule; little compaction
|
| 140 |
+
{"frequent", 0, 4, 1}, // short suffix is favorable to the raw log
|
| 141 |
+
{"write-only", 0, 0, 0} // overhead when nobody reads
|
| 142 |
+
};
|
| 143 |
+
|
| 144 |
+
static U64 random_word(U64& state) {
|
| 145 |
+
state += 0x9e3779b97f4a7c15ULL;
|
| 146 |
+
U64 z = state;
|
| 147 |
+
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
|
| 148 |
+
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
|
| 149 |
+
return z ^ (z >> 31);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
static std::vector<Op> trace(const Scenario& s, std::size_t n, std::size_t writes) {
|
| 153 |
+
std::vector<Op> ops;
|
| 154 |
+
std::vector<bool> live(n, true);
|
| 155 |
+
std::vector<U64> cursors(s.readers, n);
|
| 156 |
+
U64 rng = 0xc004a17;
|
| 157 |
+
auto keyspace = s.hot_keys ? std::min(n, static_cast<std::size_t>(s.hot_keys)) : n;
|
| 158 |
+
for (std::size_t i = 1; i <= writes; ++i) {
|
| 159 |
+
Key k = static_cast<Key>(random_word(rng) % keyspace);
|
| 160 |
+
U64 v = random_word(rng);
|
| 161 |
+
bool remove = (v & 15) == 0 && live[k];
|
| 162 |
+
live[k] = !remove;
|
| 163 |
+
ops.push_back({remove ? Kind::erase : Kind::put, k, v});
|
| 164 |
+
// Stagger polls across the read period. After an initial partial
|
| 165 |
+
// period each independent cursor observes exactly writes_per_poll writes.
|
| 166 |
+
if (s.readers) {
|
| 167 |
+
unsigned stride = s.writes_per_poll / s.readers;
|
| 168 |
+
if (i % stride == 0) {
|
| 169 |
+
auto& cursor = cursors[(i / stride - 1) % cursors.size()];
|
| 170 |
+
ops.push_back({Kind::read, 0, cursor});
|
| 171 |
+
cursor = n + i;
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
return ops;
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
struct Result { U64 digest; U64 emitted; double seconds; double cpu_seconds; };
|
| 179 |
+
template<class T>
|
| 180 |
+
static Result run(std::size_t capacity, std::size_t writes, const std::vector<Op>& ops) {
|
| 181 |
+
T index(capacity, writes);
|
| 182 |
+
for (std::size_t k = 0; k < capacity; ++k) index.put(static_cast<Key>(k), k);
|
| 183 |
+
U64 digest = 0xcbf29ce484222325ULL;
|
| 184 |
+
U64 emitted = 0;
|
| 185 |
+
auto consume = [&](U64 rev, Key key, const U64* value) {
|
| 186 |
+
digest = (digest ^ rev) * 1099511628211ULL;
|
| 187 |
+
digest = (digest ^ key) * 1099511628211ULL;
|
| 188 |
+
digest = (digest ^ (value ? *value : 0)) * 1099511628211ULL;
|
| 189 |
+
digest ^= (value != nullptr);
|
| 190 |
+
++emitted;
|
| 191 |
+
};
|
| 192 |
+
std::clock_t cpu_start = std::clock();
|
| 193 |
+
auto start = std::chrono::steady_clock::now();
|
| 194 |
+
for (const auto& op : ops) {
|
| 195 |
+
if (op.kind == Kind::put) index.put(op.key, op.argument);
|
| 196 |
+
else if (op.kind == Kind::erase) index.erase(op.key);
|
| 197 |
+
else {
|
| 198 |
+
digest ^= op.argument;
|
| 199 |
+
index.since(op.argument, consume);
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
auto end = std::chrono::steady_clock::now();
|
| 203 |
+
std::clock_t cpu_end = std::clock();
|
| 204 |
+
// Consume final state (outside timing), including in write-only workloads.
|
| 205 |
+
U64 timed_emitted = emitted;
|
| 206 |
+
index.since(capacity, consume);
|
| 207 |
+
return {digest, timed_emitted, std::chrono::duration<double>(end-start).count(),
|
| 208 |
+
static_cast<double>(cpu_end - cpu_start) / CLOCKS_PER_SEC};
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
using Run = Result(*)(std::size_t, std::size_t, const std::vector<Op>&);
|
| 212 |
+
constexpr std::array<Run, 5> methods{run<Afterkey>, run<Journal>, run<Log>, run<List>, run<Scan>};
|
| 213 |
+
constexpr std::array<const char*, 5> names{"afterkey", "afterkey-journal", "cursor-log", "std-list", "stamp-scan"};
|
| 214 |
+
|
| 215 |
+
static double median(const std::vector<double>& sorted) {
|
| 216 |
+
auto n = sorted.size();
|
| 217 |
+
return (sorted[(n-1)/2] + sorted[n/2]) / 2;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
static std::size_t number(const char* arg, const char* name, std::size_t limit) {
|
| 221 |
+
std::string s(arg);
|
| 222 |
+
if (s.empty() || s.find_first_not_of("0123456789") != std::string::npos)
|
| 223 |
+
throw std::invalid_argument(name);
|
| 224 |
+
auto n = std::stoull(s);
|
| 225 |
+
if (n == 0 || n > limit) throw std::out_of_range(name);
|
| 226 |
+
return static_cast<std::size_t>(n);
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
int main(int argc, char** argv) {
|
| 230 |
+
try {
|
| 231 |
+
if (argc > 5 || (argc > 1 && std::string(argv[1]) == "--help")) {
|
| 232 |
+
std::cerr << "Usage: compare [capacity=16384] [writes=32768] [repetitions=5] [scenario]\n"
|
| 233 |
+
<< "Scenarios: hot-lag uniform-lag frequent write-only\n";
|
| 234 |
+
return argc > 5 ? 2 : 0;
|
| 235 |
+
}
|
| 236 |
+
std::size_t n = argc > 1 ? number(argv[1], "capacity", UINT32_MAX - 1) : 16384;
|
| 237 |
+
std::size_t w = argc > 2 ? number(argv[2], "writes", UINT32_MAX) : 32768;
|
| 238 |
+
std::size_t reps = argc > 3 ? number(argv[3], "repetitions", 1000) : 5;
|
| 239 |
+
std::cout << "scenario,method,capacity,writes,reads,emitted,repetitions,min_ns_op,median_ns_op,max_ns_op,median_mixed_mops_s,median_cpu_ns_op,checksum\n";
|
| 240 |
+
bool matched = false;
|
| 241 |
+
for (auto s : scenarios) {
|
| 242 |
+
if (argc == 5 && s.name != std::string(argv[4])) continue;
|
| 243 |
+
matched = true;
|
| 244 |
+
auto ops = trace(s, n, w);
|
| 245 |
+
std::array<std::vector<double>, methods.size()> times;
|
| 246 |
+
std::array<std::vector<double>, methods.size()> cpu_times;
|
| 247 |
+
// Independently materialized row stamps + ordered output serve as oracle.
|
| 248 |
+
Result expected = run<Scan>(n, w, ops);
|
| 249 |
+
for (std::size_t trial = 0; trial <= reps; ++trial) {
|
| 250 |
+
for (std::size_t j = 0; j < methods.size(); ++j) {
|
| 251 |
+
auto m = (trial + j) % methods.size();
|
| 252 |
+
double elapsed = 0, cpu = 0;
|
| 253 |
+
std::size_t runs = 0;
|
| 254 |
+
do {
|
| 255 |
+
Result r = methods[m](n, w, ops);
|
| 256 |
+
if (r.digest != expected.digest || r.emitted != expected.emitted)
|
| 257 |
+
throw std::runtime_error(std::string(s.name) + ": incorrect output for " + names[m]);
|
| 258 |
+
elapsed += r.seconds;
|
| 259 |
+
cpu += r.cpu_seconds;
|
| 260 |
+
++runs;
|
| 261 |
+
} while (trial && elapsed < 0.008);
|
| 262 |
+
if (trial) {
|
| 263 |
+
double ns_per_op = 1e9 / (runs * static_cast<double>(ops.size()));
|
| 264 |
+
times[m].push_back(elapsed * ns_per_op);
|
| 265 |
+
cpu_times[m].push_back(cpu * ns_per_op);
|
| 266 |
+
}
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
for (std::size_t m = 0; m < methods.size(); ++m) {
|
| 270 |
+
auto& t = times[m];
|
| 271 |
+
std::sort(t.begin(), t.end());
|
| 272 |
+
auto& cpu = cpu_times[m];
|
| 273 |
+
std::sort(cpu.begin(), cpu.end());
|
| 274 |
+
std::cout << s.name << ',' << names[m] << ',' << n << ',' << w << ','
|
| 275 |
+
<< ops.size()-w << ',' << expected.emitted << ',' << reps << ','
|
| 276 |
+
<< std::fixed << std::setprecision(3) << t.front() << ',' << median(t)
|
| 277 |
+
<< ',' << t.back() << ',' << 1000 / median(t) << ',' << median(cpu) << ',' << expected.digest << '\n';
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
if (!matched) throw std::invalid_argument("unknown scenario");
|
| 281 |
+
} catch (const std::exception& e) {
|
| 282 |
+
std::cerr << "compare: " << e.what() << '\n';
|
| 283 |
+
return 1;
|
| 284 |
+
}
|
| 285 |
+
}
|
bench/environment.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Native replay benchmark
|
| 2 |
+
|
| 3 |
+
The CSV records single-threaded, in-process C++17 replay. Each input operation is one put, erase, or poll. One poll can emit many records. Polls synchronously consume every returned key, revision, tombstone flag, and value in increasing revision order. A separately sorted dense-array implementation supplies the expected digest and callback count. Every warmup and measured replay checks both. The write-only scenario also checks the final state after timing.
|
| 4 |
+
|
| 5 |
+
## Reproduce
|
| 6 |
+
|
| 7 |
+
From the Afterkey directory on Linux, choose a CPU available to the process. CPU 2 was available for the recorded run.
|
| 8 |
+
|
| 9 |
+
```sh
|
| 10 |
+
g++ -std=c++17 -O3 -DNDEBUG -Wall -Wextra -pedantic bench/compare.cpp -o /tmp/afterkey-compare
|
| 11 |
+
taskset -c 2 /tmp/afterkey-compare 16384 65536 9
|
| 12 |
+
taskset -c 2 /tmp/afterkey-compare 1048576 65536 5 hot-lag
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
The recorded machine reported Linux x86-64, AMD EPYC 9V74, GCC 14.2.0 (Debian 14.2.0-19) and glibc 2.41. It was a shared virtual environment. All methods use the same compiler, flags, deterministic trace, key space and callback.
|
| 16 |
+
|
| 17 |
+
## Timing and workloads
|
| 18 |
+
|
| 19 |
+
The benchmark prefills every key outside the timed region and constructs its input stream in advance using SplitMix64 with seed `0xc004a17`. Approximately one in sixteen writes erases a present key. Erased keys become live again on the next put. Each implementation receives one warmup. Timed trials rotate method order. Each trial repeats an identical replay with a fresh instance until at least 8 ms of timed wall time have accumulated. Initialization, final-state verification and teardown are outside that interval. The application loop, callback and checksum are inside it.
|
| 20 |
+
|
| 21 |
+
| Scenario | Key distribution | Reader schedule |
|
| 22 |
+
| --- | --- | --- |
|
| 23 |
+
| hot-lag | Uniform over 16 hot keys | 16 independent cursors, each polled every 2,048 writes. Starts stagger by 128 writes. |
|
| 24 |
+
| uniform-lag | Uniform over every registered key | Same staggered schedule as hot-lag |
|
| 25 |
+
| frequent | Uniform over every registered key | One cursor every four writes |
|
| 26 |
+
| write-only | Uniform over every registered key | Zero timed polls |
|
| 27 |
+
|
| 28 |
+
The append-log baseline reserves storage for the entire run and seeks directly to each cursor, then discards superseded entries by checking a dense array of latest revisions. The std::list implementation splices stable nodes on overwrite, stores the data within each node and uses dense per-key iterators. It has the same output-sensitive read complexity as Afterkey Index. The dense scan reuses its sort buffer.
|
| 29 |
+
|
| 30 |
+
`min_ns_op`, `median_ns_op`, and `max_ns_op` are trial-level elapsed time divided by total mixed operations. `median_mixed_mops_s` counts millions of writes plus polls per elapsed second. `median_cpu_ns_op` uses process CPU time over the same replay loop. These statistics describe amortized throughput. The range reflects variation across trials. This benchmark does not capture single-operation tail latency, network time, synchronization or production adoption. For measured record counts from public traces under simulated poll schedules, see [public-trace replay](replay.md).
|
| 31 |
+
|
| 32 |
+
## Load the CSV with Hugging Face Datasets
|
| 33 |
+
|
| 34 |
+
Install `datasets` and `fsspec[http]` in a Python environment. This streams the published benchmark rows from an immutable GitHub revision.
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
from datasets import load_dataset
|
| 38 |
+
url = "https://raw.githubusercontent.com/pgg898200-ship-it/streamsieve/33590c650619a518e9f873e2825b6a5db47590e0/afterkey/bench/results.csv"
|
| 39 |
+
rows = load_dataset("csv", data_files=url, split="train", streaming=True,
|
| 40 |
+
usecols=["scenario", "method", "median_ns_op"])
|
| 41 |
+
print(next(iter(rows)))
|
| 42 |
+
```
|
bench/fanout.cpp
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "../include/afterkey.hpp"
|
| 2 |
+
|
| 3 |
+
#include <algorithm>
|
| 4 |
+
#include <atomic>
|
| 5 |
+
#include <chrono>
|
| 6 |
+
#include <cmath>
|
| 7 |
+
#include <cstdint>
|
| 8 |
+
#include <iostream>
|
| 9 |
+
#include <stdexcept>
|
| 10 |
+
#include <vector>
|
| 11 |
+
|
| 12 |
+
// g++ -std=c++17 -O3 -DNDEBUG bench/fanout.cpp -o /tmp/afterkey-fanout
|
| 13 |
+
// taskset -c 2 /tmp/afterkey-fanout
|
| 14 |
+
// The result is JSON. Timings cover the call and its consuming callbacks. Reader
|
| 15 |
+
// scheduling, prefill and result verification are outside each sample.
|
| 16 |
+
using Key = std::uint32_t;
|
| 17 |
+
using U64 = std::uint64_t;
|
| 18 |
+
using Clock = std::chrono::steady_clock;
|
| 19 |
+
constexpr Key capacity = 1U << 20;
|
| 20 |
+
constexpr Key readers = 4096;
|
| 21 |
+
constexpr Key warmup = 8192;
|
| 22 |
+
constexpr Key measured_writes = 32768;
|
| 23 |
+
constexpr unsigned trials = 3;
|
| 24 |
+
|
| 25 |
+
class CursorLog {
|
| 26 |
+
struct Row { U64 revision{}; U64 value{}; bool present{}; };
|
| 27 |
+
std::vector<Row> rows;
|
| 28 |
+
std::vector<Key> history;
|
| 29 |
+
void write(Key key, U64 value, bool present) {
|
| 30 |
+
history.push_back(key);
|
| 31 |
+
rows[key] = {history.size(), value, present};
|
| 32 |
+
}
|
| 33 |
+
public:
|
| 34 |
+
explicit CursorLog(Key n) : rows(n) { history.reserve(n + warmup + measured_writes); }
|
| 35 |
+
void put(Key k, U64 v) { write(k, v, true); }
|
| 36 |
+
void erase(Key k) { write(k, 0, false); }
|
| 37 |
+
template<class Sink> void since(U64 cursor, Sink&& consume) const {
|
| 38 |
+
for (std::size_t i = cursor; i < history.size(); ++i) {
|
| 39 |
+
Key k = history[i];
|
| 40 |
+
const auto& r = rows[k];
|
| 41 |
+
if (r.revision == i + 1) consume(r.revision, k, r.present ? &r.value : nullptr);
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
static U64 random_word(U64& state) {
|
| 47 |
+
state += 0x9e3779b97f4a7c15ULL;
|
| 48 |
+
U64 z = state;
|
| 49 |
+
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
|
| 50 |
+
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
|
| 51 |
+
return z ^ (z >> 31);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
struct Write { Key key; U64 value; };
|
| 55 |
+
struct Trace {
|
| 56 |
+
std::vector<Write> writes;
|
| 57 |
+
std::vector<std::vector<Key>> polls;
|
| 58 |
+
std::size_t measured_polls = 0;
|
| 59 |
+
explicit Trace(bool uniform) : polls(warmup + measured_writes) {
|
| 60 |
+
U64 writer_rng = 0x20190d;
|
| 61 |
+
U64 reader_rng = 0x10074d;
|
| 62 |
+
for (Key i = 0; i < polls.size(); ++i) {
|
| 63 |
+
Key word = static_cast<Key>(random_word(writer_rng));
|
| 64 |
+
// Move 16 of the 64 hot keys every 512 writes. All readers see the
|
| 65 |
+
// same state history, with different cuts based on their own pace.
|
| 66 |
+
Key base = (i / 512) * 16;
|
| 67 |
+
Key k = uniform ? word % capacity : (base + word % 64) % capacity;
|
| 68 |
+
writes.push_back({k, random_word(writer_rng)});
|
| 69 |
+
}
|
| 70 |
+
for (Key reader = 0; reader < readers; ++reader) {
|
| 71 |
+
Key period = 256U << (reader % 6);
|
| 72 |
+
Key first = random_word(reader_rng) % period;
|
| 73 |
+
for (Key i = first; i < polls.size(); i += period) {
|
| 74 |
+
polls[i].push_back(reader);
|
| 75 |
+
measured_polls += i >= warmup;
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
};
|
| 80 |
+
|
| 81 |
+
struct Output { U64 hash, count; };
|
| 82 |
+
struct Samples { std::vector<U64> latency; U64 emitted = 0; };
|
| 83 |
+
|
| 84 |
+
static U64 ns(Clock::time_point start, Clock::time_point end) {
|
| 85 |
+
return std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
template<class Store>
|
| 89 |
+
static void run(const Trace& trace, Samples& samples, std::vector<Output>& oracle, bool first) {
|
| 90 |
+
Store store(capacity);
|
| 91 |
+
for (Key k = 0; k < capacity; ++k) store.put(k, k);
|
| 92 |
+
std::vector<U64> cursors(readers, capacity);
|
| 93 |
+
std::size_t poll_num = 0;
|
| 94 |
+
U64 emitted = 0;
|
| 95 |
+
for (std::size_t i = 0; i < trace.writes.size(); ++i) {
|
| 96 |
+
const auto& w = trace.writes[i];
|
| 97 |
+
if ((w.value & 31) == 0) store.erase(w.key);
|
| 98 |
+
else store.put(w.key, w.value);
|
| 99 |
+
for (Key reader : trace.polls[i]) {
|
| 100 |
+
U64 cursor = cursors[reader];
|
| 101 |
+
Output out{0xcbf29ce484222325ULL ^ cursor, 0};
|
| 102 |
+
auto consume = [&](U64 revision, Key key, const U64* value) {
|
| 103 |
+
out.hash = (out.hash ^ revision) * 1099511628211ULL;
|
| 104 |
+
out.hash = (out.hash ^ key) * 1099511628211ULL;
|
| 105 |
+
out.hash = (out.hash ^ (value ? *value : 0)) * 1099511628211ULL;
|
| 106 |
+
out.hash ^= value != nullptr;
|
| 107 |
+
++out.count;
|
| 108 |
+
};
|
| 109 |
+
auto start = Clock::now();
|
| 110 |
+
std::atomic_signal_fence(std::memory_order_seq_cst);
|
| 111 |
+
store.since(cursor, consume);
|
| 112 |
+
std::atomic_signal_fence(std::memory_order_seq_cst);
|
| 113 |
+
auto end = Clock::now();
|
| 114 |
+
cursors[reader] = capacity + i + 1;
|
| 115 |
+
if (i >= warmup) {
|
| 116 |
+
samples.latency.push_back(ns(start, end));
|
| 117 |
+
emitted += out.count;
|
| 118 |
+
if (first) oracle.push_back(out);
|
| 119 |
+
else if (out.count != oracle.at(poll_num).count || out.hash != oracle[poll_num].hash)
|
| 120 |
+
throw std::runtime_error("per-poll output mismatch");
|
| 121 |
+
++poll_num;
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
if (poll_num != trace.measured_polls) throw std::runtime_error("missing poll");
|
| 126 |
+
samples.emitted += emitted;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
static U64 percentile(const std::vector<U64>& sorted, double fraction) {
|
| 130 |
+
auto rank = static_cast<std::size_t>(std::ceil(fraction * sorted.size()));
|
| 131 |
+
return sorted[rank - 1];
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
static void summarize(const char* name, Samples& s) {
|
| 135 |
+
std::sort(s.latency.begin(), s.latency.end());
|
| 136 |
+
std::cout << " \"" << name << "\": {\"samples\":" << s.latency.size()
|
| 137 |
+
<< ",\"emitted_per_trial\":" << s.emitted / trials
|
| 138 |
+
<< ",\"p50_ns\":" << percentile(s.latency, 0.5)
|
| 139 |
+
<< ",\"p99_ns\":" << percentile(s.latency, 0.99)
|
| 140 |
+
<< ",\"p999_ns\":" << percentile(s.latency, 0.999) << "}";
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
int main() {
|
| 144 |
+
std::vector<U64> floor;
|
| 145 |
+
for (unsigned i = 0; i < 100000; ++i) {
|
| 146 |
+
auto a = Clock::now();
|
| 147 |
+
std::atomic_signal_fence(std::memory_order_seq_cst);
|
| 148 |
+
auto b = Clock::now();
|
| 149 |
+
floor.push_back(ns(a, b));
|
| 150 |
+
}
|
| 151 |
+
std::sort(floor.begin(), floor.end());
|
| 152 |
+
std::cout << "{\n \"capacity\":" << capacity << ", \"readers\":" << readers
|
| 153 |
+
<< ", \"warmup_writes\":" << warmup << ", \"measured_writes\":" << measured_writes
|
| 154 |
+
<< ", \"trials\":" << trials << ", \"empty_clock_pair_median_ns\":" << percentile(floor, 0.5)
|
| 155 |
+
<< ",\n \"method\":\"Single-threaded synthetic closed-loop wall time per poll, including consuming callback. "
|
| 156 |
+
"Nearest-rank percentiles pooled across trials. Timers are unsubtracted. Requests execute serially. "
|
| 157 |
+
"Excludes queue wait, networking and producer time.\",\n \"scenarios\":{\n";
|
| 158 |
+
for (bool uniform : {false, true}) {
|
| 159 |
+
Trace trace(uniform);
|
| 160 |
+
std::vector<Output> oracle;
|
| 161 |
+
oracle.reserve(trace.measured_polls);
|
| 162 |
+
Samples index, log;
|
| 163 |
+
index.latency.reserve(trials * trace.measured_polls);
|
| 164 |
+
log.latency.reserve(trials * trace.measured_polls);
|
| 165 |
+
for (unsigned trial = 0; trial < trials; ++trial) {
|
| 166 |
+
if (trial % 2 == 0) {
|
| 167 |
+
run<CursorLog>(trace, log, oracle, trial == 0);
|
| 168 |
+
run<afterkey::Index<U64>>(trace, index, oracle, false);
|
| 169 |
+
} else {
|
| 170 |
+
run<afterkey::Index<U64>>(trace, index, oracle, false);
|
| 171 |
+
run<CursorLog>(trace, log, oracle, false);
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
std::cout << " \"" << (uniform ? "uniform" : "moving-hot-set") << "\":{\n";
|
| 175 |
+
summarize("afterkey", index);
|
| 176 |
+
std::cout << ",\n";
|
| 177 |
+
summarize("cursor-log", log);
|
| 178 |
+
std::cout << "\n }" << (uniform ? "\n" : ",\n");
|
| 179 |
+
}
|
| 180 |
+
std::cout << " }\n}\n";
|
| 181 |
+
}
|
bench/fanout.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"capacity":1048576, "readers":4096, "warmup_writes":8192, "measured_writes":32768, "trials":3, "empty_clock_pair_median_ns":30,
|
| 3 |
+
"method":"Single-threaded synthetic closed-loop wall time per poll, including consuming callback. Nearest-rank percentiles pooled across trials. Timers are unsubtracted. Requests execute serially. Excludes queue wait, networking and producer time.",
|
| 4 |
+
"scenarios":{
|
| 5 |
+
"moving-hot-set":{
|
| 6 |
+
"afterkey": {"samples":516312,"emitted_per_trial":14432972,"p50_ns":401,"p99_ns":1673,"p999_ns":2574},
|
| 7 |
+
"cursor-log": {"samples":516312,"emitted_per_trial":14432972,"p50_ns":430,"p99_ns":4987,"p999_ns":17315}
|
| 8 |
+
},
|
| 9 |
+
"uniform":{
|
| 10 |
+
"afterkey": {"samples":516312,"emitted_per_trial":134053894,"p50_ns":3254,"p99_ns":417859,"p999_ns":743480},
|
| 11 |
+
"cursor-log": {"samples":516312,"emitted_per_trial":134053894,"p50_ns":1272,"p99_ns":75916,"p999_ns":167762}
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
}
|
bench/replay.cpp
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "afterkey.hpp"
|
| 2 |
+
#include <algorithm>
|
| 3 |
+
#include <cstdint>
|
| 4 |
+
#include <exception>
|
| 5 |
+
#include <fstream>
|
| 6 |
+
#include <iostream>
|
| 7 |
+
#include <limits>
|
| 8 |
+
#include <sstream>
|
| 9 |
+
#include <stdexcept>
|
| 10 |
+
#include <string>
|
| 11 |
+
#include <vector>
|
| 12 |
+
|
| 13 |
+
struct Event {
|
| 14 |
+
uint64_t time_ms;
|
| 15 |
+
uint32_t key;
|
| 16 |
+
uint64_t value;
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
// Replay one independent reader that polls at UTC-aligned time boundaries.
|
| 20 |
+
// Compare complete ordered (revision, key, value) output at every nonempty poll.
|
| 21 |
+
// The reference uses the input as its log and a dense last-revision array.
|
| 22 |
+
void replay(const std::vector<Event>& events, uint32_t capacity, uint64_t period_ms) {
|
| 23 |
+
afterkey::Index<uint64_t> index(capacity);
|
| 24 |
+
std::vector<uint64_t> stamps(capacity);
|
| 25 |
+
uint64_t cursor = 0, delivered = 0, polls = 0;
|
| 26 |
+
auto poll = [&] {
|
| 27 |
+
uint64_t scan = cursor;
|
| 28 |
+
auto skip_stale = [&] {
|
| 29 |
+
while (scan < index.version() && stamps[events[scan].key] != scan + 1)
|
| 30 |
+
++scan;
|
| 31 |
+
};
|
| 32 |
+
index.since(cursor, [&](uint64_t rev, uint32_t key, const uint64_t* value) {
|
| 33 |
+
skip_stale();
|
| 34 |
+
if (scan == index.version() || rev != scan + 1 ||
|
| 35 |
+
key != events[scan].key || !value || *value != events[scan].value)
|
| 36 |
+
throw std::runtime_error("index and log disagree");
|
| 37 |
+
++scan;
|
| 38 |
+
++delivered;
|
| 39 |
+
});
|
| 40 |
+
skip_stale();
|
| 41 |
+
if (scan != index.version()) throw std::runtime_error("index omitted a key");
|
| 42 |
+
++polls;
|
| 43 |
+
cursor = index.version();
|
| 44 |
+
};
|
| 45 |
+
uint64_t bucket = events.front().time_ms / period_ms;
|
| 46 |
+
for (const auto& event : events) {
|
| 47 |
+
if (event.time_ms / period_ms != bucket) {
|
| 48 |
+
poll();
|
| 49 |
+
bucket = event.time_ms / period_ms;
|
| 50 |
+
}
|
| 51 |
+
stamps[event.key] = index.put(event.key, event.value);
|
| 52 |
+
}
|
| 53 |
+
poll();
|
| 54 |
+
std::cout << period_ms << ',' << capacity << ',' << polls << ',' << events.size()
|
| 55 |
+
<< ',' << delivered << ',' << uint64_t(capacity) * polls << '\n';
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
int main(int argc, char** argv) {
|
| 59 |
+
if (argc != 2) {
|
| 60 |
+
std::cerr << "usage: replay prepared-events.tsv\n";
|
| 61 |
+
return 2;
|
| 62 |
+
}
|
| 63 |
+
try {
|
| 64 |
+
std::ifstream source(argv[1]);
|
| 65 |
+
if (!source) throw std::runtime_error("cannot open replay file");
|
| 66 |
+
std::vector<Event> events;
|
| 67 |
+
uint32_t capacity = 0;
|
| 68 |
+
std::string line;
|
| 69 |
+
while (std::getline(source, line)) {
|
| 70 |
+
std::istringstream fields(line);
|
| 71 |
+
Event e{};
|
| 72 |
+
if (!(fields >> e.time_ms >> e.key >> e.value) ||
|
| 73 |
+
(fields >> std::ws && !fields.eof()) ||
|
| 74 |
+
e.key == std::numeric_limits<uint32_t>::max() ||
|
| 75 |
+
(!events.empty() && e.time_ms < events.back().time_ms))
|
| 76 |
+
throw std::runtime_error("invalid event row");
|
| 77 |
+
events.push_back(e);
|
| 78 |
+
capacity = std::max(capacity, e.key + 1);
|
| 79 |
+
}
|
| 80 |
+
if (source.bad() || events.empty()) throw std::runtime_error("unreadable or empty replay");
|
| 81 |
+
std::cout << "poll_ms,keys,nonempty_polls,log_rows,latest_rows,full_map_slots\n";
|
| 82 |
+
for (uint64_t ms : {60000, 3600000, 86400000}) replay(events, capacity, ms);
|
| 83 |
+
} catch (const std::exception& e) {
|
| 84 |
+
std::cerr << e.what() << '\n';
|
| 85 |
+
return 1;
|
| 86 |
+
}
|
| 87 |
+
}
|
bench/replay.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Catch-up on two recorded streams
|
| 2 |
+
|
| 3 |
+
Each row below is one replay of a public trace with a simulated reader. Keys and timestamps come from the source. At every nonempty poll the harness checks the exact ordered sequence of revisions, keys and values against a forward log scan with a dense last-revision array. Both implementations emit the same rows. All 15,615 nonempty polls passed.
|
| 4 |
+
|
| 5 |
+
| Trace | Poll interval | Keys | Nonempty polls | Log records inspected | Latest rows emitted | Slots in a full map scan |
|
| 6 |
+
|---|---:|---:|---:|---:|---:|---:|
|
| 7 |
+
| Paris bike availability | 1 min | 1,489 | 14,344 | 5,143,865 | 5,143,771 | 21,358,216 |
|
| 8 |
+
| Paris bike availability | 1 hr | 1,489 | 720 | 5,143,865 | 895,673 | 1,072,080 |
|
| 9 |
+
| Paris bike availability | 1 day | 1,489 | 30 | 5,143,865 | 43,683 | 44,670 |
|
| 10 |
+
| Agent session progress | 1 min | 25 | 496 | 1,375 | 643 | 12,400 |
|
| 11 |
+
| Agent session progress | 1 hr | 25 | 23 | 1,375 | 64 | 575 |
|
| 12 |
+
| Agent session progress | 1 day | 25 | 2 | 1,375 | 28 | 50 |
|
| 13 |
+
|
| 14 |
+
The Paris minute reader saw just 94 superseded writes across the month. The hourly reader saw 5.74 log records per emitted row. At daily intervals nearly every station changed, making a full map scan competitive on inspection count. The full-map column is capacity times nonempty polls and excludes the cost of collecting and sorting by revision. Afterkey's ordered iteration can walk the changed suffix twice. These figures count workload and output, not elapsed time or CPU instructions.
|
| 15 |
+
|
| 16 |
+
## Run the replays
|
| 17 |
+
|
| 18 |
+
From the Afterkey directory with Python 3.11+, a C++17 compiler and curl:
|
| 19 |
+
|
| 20 |
+
~~~sh
|
| 21 |
+
c++ -std=c++17 -O3 -Iinclude bench/replay.cpp -o /tmp/afterkey-replay
|
| 22 |
+
|
| 23 |
+
# Agent progress. Requires the zstd CLI.
|
| 24 |
+
curl -fL 'https://huggingface.co/datasets/harvardMadsys/freeinference_agentic_trace/resolve/bb26cf72c9c20f2b05f765d88548156a74d3c253/release/2026-05-17_2026-05-23/traces/2026-05-17.jsonl.zst' -o /tmp/afterkey-agents.jsonl.zst
|
| 25 |
+
python3 bench/replay_prepare.py agents /tmp/afterkey-agents.jsonl.zst > /tmp/afterkey-agents.tsv
|
| 26 |
+
/tmp/afterkey-replay /tmp/afterkey-agents.tsv
|
| 27 |
+
|
| 28 |
+
# Station availability. The compressed download is 41 MB.
|
| 29 |
+
python3 -m venv /tmp/afterkey-replay-env
|
| 30 |
+
/tmp/afterkey-replay-env/bin/pip install duckdb==1.4.1
|
| 31 |
+
curl -fL 'https://data.citybik.es/dumps/by-network/2025/202509-velib-stats.parquet' -o /tmp/afterkey-city.parquet
|
| 32 |
+
/tmp/afterkey-replay-env/bin/python bench/replay_prepare.py city /tmp/afterkey-city.parquet > /tmp/afterkey-city.tsv
|
| 33 |
+
/tmp/afterkey-replay /tmp/afterkey-city.tsv
|
| 34 |
+
~~~
|
| 35 |
+
|
| 36 |
+
The preparation script verifies each original file's SHA-256. The output format is a space-separated line with epoch milliseconds, dense key and unsigned 64-bit value. Each simulation groups events into UTC-aligned intervals and flushes the last partial bucket. Empty intervals generate no work in the comparison. The replay reads the prepared file into memory, which lets its oracle inspect original events independently of Afterkey. A production reader can discard consumed history when its delivery guarantees allow it.
|
| 37 |
+
|
| 38 |
+
## Sources and transformations
|
| 39 |
+
|
| 40 |
+
**CityBikes.** Every September 2025 Paris Vélib’ record contributes a write keyed by station ID. The value packs available bikes and free docks into one integer. Ties between stations are resolved by station ID. A repeated value still advances the revision. Source data and generated row files are downloaded or generated locally. Bike-share data by CityBikes contributors and available from [https://data.citybik.es](https://data.citybik.es/). CityBikes contributors. (2026) Bike-share data retrieved from [https://data.citybik.es](https://data.citybik.es/). The source describes the compilation's ODbL 1.0 license and underlying operator terms.
|
| 41 |
+
|
| 42 |
+
**FreeInference.** The May 17 partition contributes one write per completed LLM request, including nested subagent sessions. The session is the key and the most recent completion-token count is the value. Completion timestamps set the order, with session ID and step breaking ties. Some sessions finish on the following date. This models a dashboard watching agent progress. The recording contains neither the modeled subscriber nor its polling schedule. William Nixon, Muxin Tian, Yunjia Zheng, Haryadi S. Gunawi and Juncheng Yang, *From Requests to Sessions: A Large-Scale Characterization of Human-Driven Agentic Workloads* (2026). [Dataset, CC BY 4.0](https://huggingface.co/datasets/harvardMadsys/freeinference_agentic_trace) · [Paper](https://doi.org/10.5281/zenodo.23903440)
|
bench/replay_prepare.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prepare release-pinned public traces for replay.cpp. See replay.md."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
CITY_HASH = "3d4b3961d5d89b501d8a40fd8d00ac743688aaa0577f9dc60d6c65f34d4bef0d"
|
| 10 |
+
AGENT_HASH = "f768c3a44d6c7eb02340adcb7bceaf5a451e20dc568d7a96d69f78bfb70e09a8"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def prepare_city(path):
|
| 14 |
+
import duckdb
|
| 15 |
+
|
| 16 |
+
db = duckdb.connect(config={'threads': 1, 'memory_limit': '128MB'})
|
| 17 |
+
# Station and time uniquely identify each row in this source.
|
| 18 |
+
result = db.execute("""
|
| 19 |
+
WITH keys AS (
|
| 20 |
+
SELECT id, row_number() OVER (ORDER BY id) - 1 AS key
|
| 21 |
+
FROM (SELECT DISTINCT id FROM read_parquet($1))
|
| 22 |
+
)
|
| 23 |
+
SELECT epoch_ms(timestamp), key,
|
| 24 |
+
(bikes::UBIGINT << 32) | free::UBIGINT
|
| 25 |
+
FROM read_parquet($1) JOIN keys USING (id)
|
| 26 |
+
ORDER BY timestamp, id
|
| 27 |
+
""", [str(path)])
|
| 28 |
+
while rows := result.fetchmany(32768):
|
| 29 |
+
sys.stdout.write("".join(f"{t} {k} {v}\n" for t, k, v in rows))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def prepare_agents(path):
|
| 33 |
+
rows = []
|
| 34 |
+
|
| 35 |
+
def collect(session):
|
| 36 |
+
for request in session["requests"]:
|
| 37 |
+
rows.append((request["end_ms"], session["session_id"],
|
| 38 |
+
request["step"], request["provider_tokens"]["completion"]))
|
| 39 |
+
for call in request.get("tool_calls", []):
|
| 40 |
+
if call.get("subagent"):
|
| 41 |
+
collect(call["subagent"])
|
| 42 |
+
|
| 43 |
+
with subprocess.Popen(["zstd", "-dq", "-c", str(path)], stdout=subprocess.PIPE) as proc:
|
| 44 |
+
for line in proc.stdout:
|
| 45 |
+
collect(json.loads(line))
|
| 46 |
+
if proc.wait():
|
| 47 |
+
raise ValueError("could not decompress the agent trace")
|
| 48 |
+
keys = {key: idx for idx, key in enumerate(sorted({key for _, key, _, _ in rows}))}
|
| 49 |
+
for end_ms, key, step, completion in sorted(rows):
|
| 50 |
+
print(end_ms, keys[key], completion)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 55 |
+
parser.add_argument("trace", choices=["city", "agents"])
|
| 56 |
+
parser.add_argument("source", type=Path)
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
with args.source.open("rb") as source:
|
| 59 |
+
checksum = hashlib.file_digest(source, "sha256").hexdigest()
|
| 60 |
+
expected = CITY_HASH if args.trace == "city" else AGENT_HASH
|
| 61 |
+
if checksum != expected:
|
| 62 |
+
sys.exit(f"file does not match the published replay, got SHA-256 {checksum}")
|
| 63 |
+
(prepare_city if args.trace == "city" else prepare_agents)(args.source)
|
bench/results.csv
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
scenario,method,capacity,writes,reads,emitted,repetitions,min_ns_op,median_ns_op,max_ns_op,median_mixed_mops_s,median_cpu_ns_op,checksum
|
| 2 |
+
hot-lag,afterkey,16384,65536,512,8192,9,4.255,4.405,8.120,226.993,4.349,12967839164418113726
|
| 3 |
+
hot-lag,afterkey-journal,16384,65536,512,8192,9,12.234,13.088,43.211,76.404,12.795,12967839164418113726
|
| 4 |
+
hot-lag,cursor-log,16384,65536,512,8192,9,9.620,10.412,22.717,96.039,10.222,12967839164418113726
|
| 5 |
+
hot-lag,std-list,16384,65536,512,8192,9,5.345,6.060,12.524,165.021,5.812,12967839164418113726
|
| 6 |
+
hot-lag,stamp-scan,16384,65536,512,8192,9,74.792,139.596,191.814,7.164,80.563,12967839164418113726
|
| 7 |
+
uniform-lag,afterkey,16384,65536,512,971870,9,284.310,421.461,598.963,2.373,185.062,2092104819201245312
|
| 8 |
+
uniform-lag,afterkey-journal,16384,65536,512,971870,9,92.076,134.768,257.532,7.420,73.992,2092104819201245312
|
| 9 |
+
uniform-lag,cursor-log,16384,65536,512,971870,9,56.570,121.631,181.860,8.222,60.804,2092104819201245312
|
| 10 |
+
uniform-lag,std-list,16384,65536,512,971870,9,358.675,546.338,3795.730,1.830,231.665,2092104819201245312
|
| 11 |
+
uniform-lag,stamp-scan,16384,65536,512,971870,9,2157.193,2453.006,3773.446,0.408,1042.711,2092104819201245312
|
| 12 |
+
frequent,afterkey,16384,65536,16384,65533,9,5.183,7.016,24.758,142.537,5.691,7456709056433286627
|
| 13 |
+
frequent,afterkey-journal,16384,65536,16384,65533,9,7.607,14.352,36.768,69.677,7.846,7456709056433286627
|
| 14 |
+
frequent,cursor-log,16384,65536,16384,65533,9,3.127,8.312,66.611,120.307,3.454,7456709056433286627
|
| 15 |
+
frequent,std-list,16384,65536,16384,65533,9,11.085,32.250,604.908,31.008,12.408,7456709056433286627
|
| 16 |
+
frequent,stamp-scan,16384,65536,16384,65533,9,6379.704,8592.170,11731.227,0.116,2112.781,7456709056433286627
|
| 17 |
+
write-only,afterkey,16384,65536,0,0,9,3.490,5.582,6.760,179.142,5.603,2506348512446439253
|
| 18 |
+
write-only,afterkey-journal,16384,65536,0,0,9,8.516,10.406,83.995,96.101,10.442,2506348512446439253
|
| 19 |
+
write-only,cursor-log,16384,65536,0,0,9,1.690,2.573,20.088,388.626,2.538,2506348512446439253
|
| 20 |
+
write-only,std-list,16384,65536,0,0,9,11.245,16.713,387.553,59.835,16.371,2506348512446439253
|
| 21 |
+
write-only,stamp-scan,16384,65536,0,0,9,2.473,3.261,9.979,306.667,3.331,2506348512446439253
|
| 22 |
+
hot-lag,afterkey,1048576,65536,512,8192,5,4.849,5.601,6.750,178.528,5.709,9750821596537536702
|
| 23 |
+
hot-lag,afterkey-journal,1048576,65536,512,8192,5,12.422,20.465,23.496,48.864,16.159,9750821596537536702
|
| 24 |
+
hot-lag,cursor-log,1048576,65536,512,8192,5,10.597,11.452,15.043,87.318,11.644,9750821596537536702
|
| 25 |
+
hot-lag,std-list,1048576,65536,512,8192,5,5.998,6.423,71.395,155.702,6.510,9750821596537536702
|
| 26 |
+
hot-lag,stamp-scan,1048576,65536,512,8192,5,23584.908,28891.292,33217.523,0.035,9214.147,9750821596537536702
|
demo/index.html
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<meta name="theme-color" content="#f6f7f3">
|
| 7 |
+
<title>Afterkey · Incremental state catch-up for C++17</title>
|
| 8 |
+
<meta name="description" content="Compare two independent readers of one live state stream. Explore overwrite coalescing, inspect reproducible C++17 benchmarks, and download the header-only library.">
|
| 9 |
+
<style>
|
| 10 |
+
:root{color-scheme:light;--paper:#f6f7f3;--ink:#17221d;--line:#cdd5ce;--muted:#515e55;--accent:#165440;--mono:"IBM Plex Mono",ui-monospace,Menlo,Consolas,monospace;font:16px/1.45 "Inter",system-ui,sans-serif;color:var(--ink);background:var(--paper)}
|
| 11 |
+
*{box-sizing:border-box}body{margin:0}.wrap{width:min(100% - 2.75rem,1090px);margin:auto}header{border-bottom:1px solid var(--line)}nav,.brand,.toolbar,.panelHead,.readerFoot,.streamHead,.legend,.legend span{display:flex;align-items:center}.brand{gap:.6rem;font-size:1.15rem;letter-spacing:-.04em;font-weight:740}nav{height:3.7rem;justify-content:space-between}nav small,.eyebrow,th,.rev,.note,.cursor,.kind,.keycode,.feedback,.tile,.metric small{font-family:var(--mono)}nav small,.note,.feedback{font-size:.76rem;color:var(--muted)}.mark{display:inline-grid;grid-template-columns:repeat(3,4px);align-items:end;gap:3px;height:20px}.mark i{background:var(--accent);height:50%}.mark i:nth-child(2){height:75%}.mark i:last-child{height:100%}
|
| 12 |
+
main{padding:clamp(1.8rem,5vw,3.7rem) 0 2rem}h1,h2,h3,p{margin:0}h1{font-size:clamp(2.4rem,6vw,4.25rem);line-height:1.04;letter-spacing:-.065em;font-weight:690}h1+ p{margin-top:.75rem;max-width:64ch;font-size:1.05rem;color:var(--muted)}.controls{display:flex;flex-wrap:wrap;align-items:flex-end;justify-content:space-between;gap:1.1rem;margin:1.7rem 0 1rem}.toolbar{gap:.55rem;flex-wrap:wrap}fieldset{margin:0;padding:0;border:0}legend,.eyebrow{font-size:.72rem;font-family:var(--mono);line-height:1.4;letter-spacing:.035em;color:var(--muted)}legend{margin-bottom:.32rem;padding:0}.seg{display:inline-flex;border:1px solid var(--line);border-radius:5px;overflow:hidden;background:white}.seg label{cursor:pointer;padding:.42rem .68rem;font-size:.86rem}.seg input{position:absolute;opacity:0;width:1px;height:1px}.seg input:checked+label{background:#dce9de;color:#103d2d;font-weight:650}.seg input:focus-visible+label{outline:2px solid var(--accent);outline-offset:-3px}
|
| 13 |
+
button{font-family:inherit;line-height:1.4;font-size:.88rem;font-weight:620;cursor:pointer;background:white;color:var(--ink);border:1px solid #aab7ad;border-radius:5px;padding:.57rem .82rem}button:hover:not(:disabled){background:#eff2ec}button:focus-visible{outline:3px solid #6d9379;outline-offset:3px}button:disabled{opacity:.5;cursor:default}.primary{background:var(--accent);color:white;border-color:var(--accent)}.primary:hover:not(:disabled){background:#103f30}h2{font-size:1.18rem;letter-spacing:-.035em;line-height:1.25}.stream{background:#202e26;color:#f6f8f2;padding:1.25rem 1.3rem;border-radius:9px}.streamHead{justify-content:space-between;gap:.75rem}.rev{font-size:.83rem;color:#c2d0c4}.tiles{display:grid;grid-template-columns:repeat(24,minmax(0,1fr));gap:3px;margin:1.1rem 0 .68rem;list-style:none;padding:0}.tile{display:grid;place-items:center;min-height:2.5rem;border-bottom:3px solid #9cc0a8;background:#354a3c;color:#f3f7ed;font-size:.75rem;font-weight:600}.tile[data-band="1"]{background:#45563b;border-color:#b6bd8d}.tile[data-band="2"]{background:#354950;border-color:#9fbac7}.tile[data-band="3"]{background:#53463d;border-color:#c5a58a}.tile.deleted{border-bottom-style:dashed}.legend{justify-content:space-between;flex-wrap:wrap;gap:.3rem 1rem;font: .72rem/1.5 var(--mono);color:#cbd6c9}.readers{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem;margin:1rem 0}.reader{background:white;border:1px solid var(--line);border-radius:9px;overflow:hidden}.panelHead{padding:1.12rem 1.15rem .8rem;gap:.8rem;justify-content:space-between}.panelHead p{font-size:.83rem;color:var(--muted);margin-top:.18rem}.cursor{font-size:.76rem;white-space:nowrap;color:var(--muted)}.metrics{display:grid;grid-template-columns:1fr 1fr;gap:.5rem;margin:0 1.15rem 1rem}.metric{display:flex;align-items:baseline;gap:.42rem;flex-wrap:wrap}.metric strong{font-size:2rem;letter-spacing:-.065em;line-height:1.1;font-weight:660;font-variant-numeric:tabular-nums}.metric small{font-size:.72rem;color:var(--muted)}.tableWrap{margin:0 1.15rem;height:13rem;overflow:auto;border:1px solid #d9dfd8;border-radius:4px}table{width:100%;border-collapse:separate;border-spacing:0;text-align:left;font-size:.8rem}th{position:sticky;top:0;background:#f3f5f0;font-size:.72rem;color:var(--muted);font-weight:500}th,td{padding:.33rem .52rem;border-bottom:1px solid #e2e7e2}td{font-family:var(--mono);font-size:.77rem}.empty td{color:var(--muted);padding:.75rem}.readerFoot{padding:.85rem 1.15rem 1.1rem;gap:.65rem;align-items:center}.feedback{line-height:1.35}.feedback strong{font-weight:600;color:var(--accent)}.note{padding-top:.45rem;line-height:1.55}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
|
| 14 |
+
.resources{display:flex;align-items:center;flex-wrap:wrap;gap:.3rem 1.1rem;margin-top:1.05rem}.resources a{font-size:.87rem;font-weight:630;color:var(--accent);text-underline-offset:3px}.resources a:first-child{padding:.43rem .75rem;border:1px solid #a8b9ab;border-radius:5px;text-decoration:none;background:#fff}.resources a:hover{color:#092d20}.resources a:focus-visible{outline:3px solid #6d9379;outline-offset:3px}
|
| 15 |
+
@media(max-width:690px){.readers{grid-template-columns:1fr}.tiles{grid-template-columns:repeat(12,minmax(0,1fr))}.tile{min-height:1.8rem}.wrap{width:calc(100% - 1.5rem)}.controls{gap:.75rem}.tableWrap{height:10rem}.readerFoot{align-items:flex-start}.stream{padding:1rem}.metric strong{font-size:1.7rem}}
|
| 16 |
+
@media(prefers-reduced-motion:no-preference){button,.seg label{transition:background .12s ease}}
|
| 17 |
+
</style>
|
| 18 |
+
</head>
|
| 19 |
+
<body>
|
| 20 |
+
<header><nav class="wrap" aria-label="Product"><div class="brand"><span class="mark" aria-hidden="true"><i></i><i></i><i></i></span>Afterkey</div><small>Live reader demo</small></nav></header>
|
| 21 |
+
<main class="wrap">
|
| 22 |
+
<h1>Catch up by key.</h1>
|
| 23 |
+
<p>Two readers share one stream. Each receives the latest value or deletion for every key written since its own cursor.</p>
|
| 24 |
+
<div class="resources" aria-label="Release resources">
|
| 25 |
+
<a href="https://github.com/pgg898200-ship-it/streamsieve/tree/main/afterkey">Source & quickstart ↗</a>
|
| 26 |
+
<a href="https://github.com/pgg898200-ship-it/streamsieve/blob/main/afterkey/bench/results.csv">Benchmark results</a>
|
| 27 |
+
<a href="https://raw.githubusercontent.com/pgg898200-ship-it/streamsieve/main/afterkey/releases/afterkey-0.1.0.zip">Download v0.1.0 (ZIP)</a>
|
| 28 |
+
</div>
|
| 29 |
+
<section class="controls" aria-label="Producer controls">
|
| 30 |
+
<fieldset><legend>Write pattern</legend><div class="seg"><input type="radio" id="hot" name="pattern" value="hot" checked><label for="hot">Hot · 4 keys</label><input type="radio" id="wide" name="pattern" value="wide"><label for="wide">Wide · 24 keys</label></div></fieldset>
|
| 31 |
+
<div class="toolbar"><button id="reset" type="button">Reset</button><button id="burst" type="button" class="primary">Write 24 updates</button></div>
|
| 32 |
+
</section>
|
| 33 |
+
<section class="stream" aria-labelledby="streamTitle">
|
| 34 |
+
<div class="streamHead"><h2 id="streamTitle">Producer stream</h2><span class="rev" id="head"></span></div>
|
| 35 |
+
<ol class="tiles" id="tiles" aria-label="Most recent 24 writes, oldest first"></ol>
|
| 36 |
+
<div class="legend"><span id="range"></span><span>Key IDs · × marks deletion</span></div>
|
| 37 |
+
</section>
|
| 38 |
+
<section class="readers" id="readers" aria-label="Independent readers"></section>
|
| 39 |
+
<p class="note">Tables preview the exact rows each reader can consume, ordered by last write. Skipped writes were superseded for that reader. This JavaScript illustration shows delivery semantics. Timing benchmarks run against the C++17 index.</p>
|
| 40 |
+
<section style="margin-top:1.75rem;border-top:1px solid var(--line);padding-top:1.15rem" aria-labelledby="native-results">
|
| 41 |
+
<h2 id="native-results">What happens with 4,096 readers?</h2>
|
| 42 |
+
<p style="margin-top:.5rem;max-width:78ch">On a single thread with a million populated keys, p99 catch-up took <strong>1.67 µs</strong> for Afterkey and <strong>4.99 µs</strong> for a cursor log when writes moved among hot keys. With uniform writes, the log won at 75.92 µs against Afterkey’s 417.86 µs. Each measurement includes delivery to the in-process callback.</p>
|
| 43 |
+
<div class="resources"><a href="https://github.com/pgg898200-ship-it/streamsieve/blob/main/afterkey/bench/fanout.cpp">Run the native benchmark</a></div>
|
| 44 |
+
</section>
|
| 45 |
+
<p class="sr" role="status" id="status"></p>
|
| 46 |
+
</main>
|
| 47 |
+
<script>
|
| 48 |
+
'use strict';
|
| 49 |
+
const BURST_SIZE = 24;
|
| 50 |
+
const FAST_INTERVAL = 10;
|
| 51 |
+
const latest = new Map();
|
| 52 |
+
const recent = [];
|
| 53 |
+
const readers = [{name:'Fast reader', cadence:'Reads every 10 writes'}, {name:'Slow reader', cadence:'Reads on demand'}];
|
| 54 |
+
let revision = 0;
|
| 55 |
+
let writePattern = 'hot';
|
| 56 |
+
function pending(reader) {
|
| 57 |
+
return [...latest.values()].filter(entry => entry.rev > reader.cursor);
|
| 58 |
+
}
|
| 59 |
+
function readPending(reader) {
|
| 60 |
+
const rows = pending(reader);
|
| 61 |
+
const span = revision - reader.cursor;
|
| 62 |
+
reader.last = {rows: rows.length, skipped: span - rows.length, rev: revision};
|
| 63 |
+
reader.cursor = revision;
|
| 64 |
+
}
|
| 65 |
+
function burst() {
|
| 66 |
+
for (let i = 0; i < BURST_SIZE; i++) {
|
| 67 |
+
revision++;
|
| 68 |
+
const cardinality = writePattern === 'hot' ? 4 : 24;
|
| 69 |
+
const key = (7 * (revision - 1)) % cardinality;
|
| 70 |
+
const value = revision % 11 === 0 ? null : (13 * revision + 17 * key) % 100;
|
| 71 |
+
const entry = {key, value, rev: revision};
|
| 72 |
+
// Reinsertion preserves increasing last-write order, just like the index list.
|
| 73 |
+
latest.delete(key);
|
| 74 |
+
latest.set(key, entry);
|
| 75 |
+
recent.push(entry);
|
| 76 |
+
if (recent.length > BURST_SIZE) recent.shift();
|
| 77 |
+
if (revision % FAST_INTERVAL === 0) readPending(readers[0]);
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
function reset() {
|
| 81 |
+
latest.clear();
|
| 82 |
+
recent.length = 0;
|
| 83 |
+
revision = 0;
|
| 84 |
+
for (const reader of readers) { reader.cursor = 0; reader.last = null; }
|
| 85 |
+
burst();
|
| 86 |
+
}
|
| 87 |
+
function two(n) { return String(n).padStart(2,'0'); }
|
| 88 |
+
function row(entry) {
|
| 89 |
+
const value = entry.value === null ? 'deleted' : String(entry.value);
|
| 90 |
+
return '<tr><td>'+entry.rev+'</td><td>k'+two(entry.key)+'</td><td>'+value+'</td></tr>';
|
| 91 |
+
}
|
| 92 |
+
function renderReader(reader, index) {
|
| 93 |
+
const rows = pending(reader);
|
| 94 |
+
const skipped = revision - reader.cursor - rows.length;
|
| 95 |
+
const feedback = reader.last ? 'Last read at r'+reader.last.rev+'<br><strong>'+reader.last.rows+' delivered · '+reader.last.skipped+' skipped</strong>' : 'Awaiting first read';
|
| 96 |
+
const panel = document.getElementById('reader-'+index);
|
| 97 |
+
panel.querySelector('.cursor').textContent = 'Cursor r'+reader.cursor;
|
| 98 |
+
panel.querySelector('.count').textContent = rows.length;
|
| 99 |
+
panel.querySelector('.skipped').textContent = skipped;
|
| 100 |
+
panel.querySelector('tbody').innerHTML = rows.length ? rows.map(row).join('') : '<tr class="empty"><td colspan="3">Caught up through revision '+revision+'.</td></tr>';
|
| 101 |
+
panel.querySelector('.feedback').innerHTML = feedback;
|
| 102 |
+
panel.querySelector('button').disabled = rows.length === 0;
|
| 103 |
+
}
|
| 104 |
+
function render(message) {
|
| 105 |
+
document.getElementById('head').textContent = 'Head r'+revision;
|
| 106 |
+
document.getElementById('range').textContent = 'r'+recent[0].rev+' → r'+revision;
|
| 107 |
+
document.getElementById('tiles').innerHTML = recent.map(entry => {
|
| 108 |
+
const deleted = entry.value === null;
|
| 109 |
+
const label = 'Revision '+entry.rev+', key '+entry.key+', '+(deleted ? 'deleted' : 'value '+entry.value);
|
| 110 |
+
return '<li class="tile'+(deleted ? ' deleted' : '')+'" data-band="'+entry.key%4+'" title="'+label+'" aria-label="'+label+'">'+two(entry.key)+(deleted ? '×' : '')+'</li>';
|
| 111 |
+
}).join('');
|
| 112 |
+
readers.forEach(renderReader);
|
| 113 |
+
document.getElementById('status').textContent = message;
|
| 114 |
+
}
|
| 115 |
+
for (const [index, reader] of readers.entries()) {
|
| 116 |
+
const el = document.createElement('article');
|
| 117 |
+
el.className='reader';
|
| 118 |
+
el.id='reader-'+index;
|
| 119 |
+
el.innerHTML='<div class="panelHead"><div><h2>'+reader.name+'</h2><p>'+reader.cadence+'</p></div><span class="cursor"></span></div><div class="metrics"><div class="metric"><strong class="count"></strong><small>pending keys</small></div><div class="metric"><strong class="skipped"></strong><small>skippable writes</small></div></div><div class="tableWrap" tabindex="0" role="region" aria-label="'+reader.name+' pending changes"><table><thead><tr><th>Revision</th><th>Key</th><th>Latest value</th></tr></thead><tbody></tbody></table></div><div class="readerFoot"><button type="button" aria-label="Read pending changes for '+reader.name.toLowerCase()+'">Read pending</button><p class="feedback"></p></div>';
|
| 120 |
+
document.getElementById('readers').append(el);
|
| 121 |
+
el.querySelector('button').addEventListener('click', () => {
|
| 122 |
+
readPending(reader);
|
| 123 |
+
render(reader.name+' caught up to revision '+revision+'.');
|
| 124 |
+
});
|
| 125 |
+
}
|
| 126 |
+
document.getElementById('burst').addEventListener('click', () => { burst(); render('24 updates written. Head revision '+revision+'.'); });
|
| 127 |
+
document.getElementById('reset').addEventListener('click', () => { reset(); render('Reset with one initial burst of 24 writes.'); });
|
| 128 |
+
document.querySelectorAll('input[name=pattern]').forEach(input => input.addEventListener('change', () => {
|
| 129 |
+
writePattern=input.value;
|
| 130 |
+
document.getElementById('status').textContent='Next burst uses '+(writePattern==='hot'?'4 hot keys.':'24 distinct keys.');
|
| 131 |
+
}));
|
| 132 |
+
reset();
|
| 133 |
+
render('Initial burst of 24 writes.');
|
| 134 |
+
</script>
|
| 135 |
+
</body>
|
| 136 |
+
</html>
|
examples/quickstart.cpp
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "afterkey.hpp"
|
| 2 |
+
#include <cstdint>
|
| 3 |
+
#include <iostream>
|
| 4 |
+
|
| 5 |
+
int main() {
|
| 6 |
+
afterkey::Index<int> state(16);
|
| 7 |
+
state.put(7, 10);
|
| 8 |
+
const auto reader_cursor = state.version();
|
| 9 |
+
state.put(3, 20);
|
| 10 |
+
state.put(7, 11);
|
| 11 |
+
state.erase(3);
|
| 12 |
+
state.since(reader_cursor, [](std::uint64_t rev, std::uint32_t key, const int* value) {
|
| 13 |
+
std::cout << rev << ' ' << key << ' ';
|
| 14 |
+
if (value) std::cout << *value;
|
| 15 |
+
else std::cout << "deleted";
|
| 16 |
+
std::cout << '\n';
|
| 17 |
+
});
|
| 18 |
+
}
|
examples/streamsieve.cpp
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* Publish the most recent StreamSieve z-score for each channel. A live dashboard
|
| 3 |
+
* polls after four observations; a slower observer polls after twelve. Both
|
| 4 |
+
* independently reconstruct the latest scores, even if a hot channel changes
|
| 5 |
+
* several times between polls.
|
| 6 |
+
*
|
| 7 |
+
* From the StreamSieve repository root:
|
| 8 |
+
* c++ -O2 -std=c++20 -Icsrc -Iafterkey/include afterkey/examples/streamsieve.cpp csrc/streamsieve_capi.cpp -o /tmp/streamsieve-afterkey
|
| 9 |
+
* /tmp/streamsieve-afterkey
|
| 10 |
+
* Tested against StreamSieve 77a48776092056a7319d91961273abfdee3f7c7e.
|
| 11 |
+
*/
|
| 12 |
+
#include "afterkey.hpp"
|
| 13 |
+
#include "streamsieve_capi.h"
|
| 14 |
+
|
| 15 |
+
#include <array>
|
| 16 |
+
#include <cstdint>
|
| 17 |
+
#include <iostream>
|
| 18 |
+
#include <memory>
|
| 19 |
+
#include <stdexcept>
|
| 20 |
+
|
| 21 |
+
constexpr std::uint32_t channels = 3;
|
| 22 |
+
|
| 23 |
+
void check(int result) {
|
| 24 |
+
if (result != SS_OK) throw std::runtime_error("StreamSieve operation failed");
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
double z_score(ss_estream_t* stream, std::uint32_t key) {
|
| 28 |
+
ss_channel_status_t status{};
|
| 29 |
+
check(ss_estream_get_channel(stream, key, &status));
|
| 30 |
+
return status.z_score;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
struct Reader {
|
| 34 |
+
std::uint64_t cursor = 0;
|
| 35 |
+
std::array<double, channels> scores{};
|
| 36 |
+
std::size_t received = 0;
|
| 37 |
+
|
| 38 |
+
void poll(const afterkey::Index<double>& index, ss_estream_t* stream) {
|
| 39 |
+
index.since(cursor, [&](std::uint64_t, std::uint32_t key, const double* score) {
|
| 40 |
+
if (!score) throw std::logic_error("unexpected deletion");
|
| 41 |
+
scores[key] = *score;
|
| 42 |
+
++received;
|
| 43 |
+
});
|
| 44 |
+
cursor = index.version();
|
| 45 |
+
|
| 46 |
+
// Oracle for this example: compare the reader's materialized view with
|
| 47 |
+
// StreamSieve's current scores for *every* channel, including quiet ones.
|
| 48 |
+
for (std::uint32_t key = 0; key < channels; ++key) {
|
| 49 |
+
if (scores[key] != z_score(stream, key))
|
| 50 |
+
throw std::runtime_error("reader disagrees with StreamSieve");
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
int main() {
|
| 56 |
+
try {
|
| 57 |
+
ss_estream_config_t config{};
|
| 58 |
+
ss_estream_default_config(&config, channels);
|
| 59 |
+
config.warmup = 12;
|
| 60 |
+
std::unique_ptr<ss_estream_t, decltype(&ss_estream_destroy)> stream(
|
| 61 |
+
ss_estream_create(&config), ss_estream_destroy);
|
| 62 |
+
if (!stream) throw std::runtime_error("could not create StreamSieve engine");
|
| 63 |
+
|
| 64 |
+
for (std::uint32_t tick = 0; tick < config.warmup; ++tick) {
|
| 65 |
+
const double v = double(tick % 5) - 2.0;
|
| 66 |
+
std::array<double, channels> baseline{v, v + 1.0, v - 1.0};
|
| 67 |
+
check(ss_estream_update_row(stream.get(), baseline.data(), channels));
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
afterkey::Index<double> index(channels);
|
| 71 |
+
for (std::uint32_t key = 0; key < channels; ++key)
|
| 72 |
+
index.put(key, z_score(stream.get(), key));
|
| 73 |
+
|
| 74 |
+
Reader dashboard, observer;
|
| 75 |
+
constexpr std::array<std::uint32_t, 6> schedule{0, 0, 1, 0, 0, 2};
|
| 76 |
+
for (std::uint32_t tick = 1; tick <= 24; ++tick) {
|
| 77 |
+
const auto key = schedule[(tick - 1) % schedule.size()];
|
| 78 |
+
check(ss_estream_update_one(stream.get(), key, double(tick) / 4.0));
|
| 79 |
+
// Only the observed channel's local z-score can change on this tick.
|
| 80 |
+
// A cross-channel metric such as e-BH status requires a fresh panel.
|
| 81 |
+
index.put(key, z_score(stream.get(), key));
|
| 82 |
+
if (tick % 4 == 0) dashboard.poll(index, stream.get());
|
| 83 |
+
if (tick % 12 == 0) observer.poll(index, stream.get());
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
std::cout << "verified native StreamSieve scores across " << channels
|
| 87 |
+
<< " channels; revisions=" << index.version()
|
| 88 |
+
<< ", dashboard_rows=" << dashboard.received
|
| 89 |
+
<< ", observer_rows=" << observer.received << '\n';
|
| 90 |
+
} catch (const std::exception& e) {
|
| 91 |
+
std::cerr << e.what() << '\n';
|
| 92 |
+
return 1;
|
| 93 |
+
}
|
| 94 |
+
}
|
examples/zmq_catchup.cpp
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* Per-key catch-up for slow ZeroMQ readers. A client supplies its last applied
|
| 3 |
+
* revision and a fixed channel mask. The server replies with a high-water mark
|
| 4 |
+
* and one absolute value or deletion for each matching channel touched since.
|
| 5 |
+
*
|
| 6 |
+
* Build from afterkey/ with libzmq development headers installed:
|
| 7 |
+
* c++ -std=c++17 -O2 -Iinclude examples/zmq_catchup.cpp $(pkg-config --cflags --libs libzmq) -o /tmp/zmq-catchup
|
| 8 |
+
* /tmp/zmq-catchup
|
| 9 |
+
*
|
| 10 |
+
* This is a single-owner, three-key, in-process request/reply example. One REP
|
| 11 |
+
* socket serves both readers. A test driver interleaves requests and replies
|
| 12 |
+
* deterministically. Each reply fits in one frame. Topic masks filter rows
|
| 13 |
+
* during iteration, so CPU work scales with all changed keys. Cursors are valid
|
| 14 |
+
* only for one server instance and one mask. Clear client state and start at
|
| 15 |
+
* zero after either changes. A remote service needs an instance ID on the wire
|
| 16 |
+
* to detect restarts and a bound on aggregate response size.
|
| 17 |
+
*/
|
| 18 |
+
#include "afterkey.hpp"
|
| 19 |
+
#include <zmq.h>
|
| 20 |
+
|
| 21 |
+
#include <array>
|
| 22 |
+
#include <cstdint>
|
| 23 |
+
#include <iostream>
|
| 24 |
+
#include <memory>
|
| 25 |
+
#include <sstream>
|
| 26 |
+
#include <stdexcept>
|
| 27 |
+
#include <string>
|
| 28 |
+
|
| 29 |
+
namespace {
|
| 30 |
+
constexpr unsigned capacity = 3;
|
| 31 |
+
constexpr char endpoint[] = "inproc://afterkey";
|
| 32 |
+
using Handle = std::unique_ptr<void, decltype(&zmq_close)>;
|
| 33 |
+
|
| 34 |
+
void check(bool ok, const char* message) {
|
| 35 |
+
if (!ok) throw std::runtime_error(message);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
Handle socket(void* context, int type) {
|
| 39 |
+
Handle s(zmq_socket(context, type), zmq_close);
|
| 40 |
+
check(bool(s), "socket creation failed");
|
| 41 |
+
int linger = 0, timeout_ms = 2000;
|
| 42 |
+
check(zmq_setsockopt(s.get(), ZMQ_LINGER, &linger, sizeof(linger)) == 0 &&
|
| 43 |
+
zmq_setsockopt(s.get(), ZMQ_RCVTIMEO, &timeout_ms, sizeof(timeout_ms)) == 0 &&
|
| 44 |
+
zmq_setsockopt(s.get(), ZMQ_SNDTIMEO, &timeout_ms, sizeof(timeout_ms)) == 0,
|
| 45 |
+
"socket configuration failed");
|
| 46 |
+
const int rc = type == ZMQ_REP ? zmq_bind(s.get(), endpoint) : zmq_connect(s.get(), endpoint);
|
| 47 |
+
check(rc == 0, "could not bind or connect");
|
| 48 |
+
return s;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
void send(void* s, const std::string& frame) {
|
| 52 |
+
check(zmq_send(s, frame.data(), frame.size(), 0) == static_cast<int>(frame.size()),
|
| 53 |
+
"incomplete send");
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
std::string receive(void* s) {
|
| 57 |
+
std::array<char, 512> buf;
|
| 58 |
+
const int size = zmq_recv(s, buf.data(), buf.size(), 0);
|
| 59 |
+
check(size >= 0 && static_cast<std::size_t>(size) <= buf.size(), "invalid frame length");
|
| 60 |
+
return std::string(buf.data(), size);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
void serve_once(void* reply_socket, const afterkey::Index<int>& index) {
|
| 64 |
+
std::istringstream request(receive(reply_socket));
|
| 65 |
+
std::uint64_t cursor;
|
| 66 |
+
unsigned mask;
|
| 67 |
+
if (!(request >> cursor >> mask) || !(request >> std::ws).eof() ||
|
| 68 |
+
cursor > index.version() || mask >= (1u << capacity)) {
|
| 69 |
+
send(reply_socket, "ERR");
|
| 70 |
+
return;
|
| 71 |
+
}
|
| 72 |
+
std::ostringstream reply;
|
| 73 |
+
reply << index.version() << '\n';
|
| 74 |
+
index.since(cursor, [&](std::uint64_t rev, std::uint32_t key, const int* value) {
|
| 75 |
+
if (mask & (1u << key)) {
|
| 76 |
+
reply << rev << ' ' << key << ' ' << (value ? std::to_string(*value) : "deleted") << '\n';
|
| 77 |
+
}
|
| 78 |
+
});
|
| 79 |
+
send(reply_socket, reply.str());
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
struct Reader {
|
| 83 |
+
Handle connection;
|
| 84 |
+
unsigned mask;
|
| 85 |
+
std::uint64_t cursor = 0;
|
| 86 |
+
|
| 87 |
+
// The test consumer checks every returned row (including order) before
|
| 88 |
+
// committing the watermark. An application would apply these rows here.
|
| 89 |
+
void poll(void* server, const afterkey::Index<int>& index, const std::string& expected) {
|
| 90 |
+
send(connection.get(), std::to_string(cursor) + " " + std::to_string(mask));
|
| 91 |
+
serve_once(server, index);
|
| 92 |
+
const std::string reply = receive(connection.get());
|
| 93 |
+
check(reply == expected, "unexpected response");
|
| 94 |
+
cursor = std::stoull(reply.substr(0, reply.find('\n')));
|
| 95 |
+
}
|
| 96 |
+
};
|
| 97 |
+
} // namespace
|
| 98 |
+
|
| 99 |
+
int main() {
|
| 100 |
+
try {
|
| 101 |
+
std::unique_ptr<void, decltype(&zmq_ctx_term)> context(zmq_ctx_new(), zmq_ctx_term);
|
| 102 |
+
check(bool(context), "context creation failed");
|
| 103 |
+
auto server = socket(context.get(), ZMQ_REP);
|
| 104 |
+
Reader a{socket(context.get(), ZMQ_REQ), 0b011};
|
| 105 |
+
Reader b{socket(context.get(), ZMQ_REQ), 0b110};
|
| 106 |
+
afterkey::Index<int> index(capacity);
|
| 107 |
+
index.put(0, 10);
|
| 108 |
+
index.put(1, 23);
|
| 109 |
+
index.put(0, 11);
|
| 110 |
+
a.poll(server.get(), index, "3\n2 1 23\n3 0 11\n");
|
| 111 |
+
a.connection.reset();
|
| 112 |
+
|
| 113 |
+
index.erase(1);
|
| 114 |
+
index.put(2, 43);
|
| 115 |
+
index.put(0, 13);
|
| 116 |
+
index.put(2, 44);
|
| 117 |
+
a.connection = socket(context.get(), ZMQ_REQ);
|
| 118 |
+
a.poll(server.get(), index, "7\n4 1 deleted\n6 0 13\n");
|
| 119 |
+
b.poll(server.get(), index, "7\n4 1 deleted\n7 2 44\n");
|
| 120 |
+
a.poll(server.get(), index, "7\n");
|
| 121 |
+
index.put(2, 45);
|
| 122 |
+
a.poll(server.get(), index, "8\n");
|
| 123 |
+
b.poll(server.get(), index, "8\n8 2 45\n");
|
| 124 |
+
std::cout << "Verified 2 readers, 8 writes, 6 polls, 7 rows, 2 empty replies and 1 reconnect.\n";
|
| 125 |
+
} catch (const std::exception& e) {
|
| 126 |
+
std::cerr << e.what() << '\n';
|
| 127 |
+
return 1;
|
| 128 |
+
}
|
| 129 |
+
}
|
include/afterkey.hpp
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef AFTERKEY_HPP
|
| 2 |
+
#define AFTERKEY_HPP
|
| 3 |
+
|
| 4 |
+
#include <cstdint>
|
| 5 |
+
#include <limits>
|
| 6 |
+
#include <memory>
|
| 7 |
+
#include <optional>
|
| 8 |
+
#include <stdexcept>
|
| 9 |
+
#include <type_traits>
|
| 10 |
+
#include <utility>
|
| 11 |
+
#include <vector>
|
| 12 |
+
|
| 13 |
+
namespace afterkey {
|
| 14 |
+
|
| 15 |
+
// Latest state of a fixed key space [0, capacity). Every write, including
|
| 16 |
+
// erasing an absent key, consumes one revision. Each touched key retains one
|
| 17 |
+
// entry, including tombstones, until this index is destroyed.
|
| 18 |
+
//
|
| 19 |
+
// Index is single-threaded. Serialize access externally if threads share it.
|
| 20 |
+
// Cursors belong to the index instance that issued them. A callback may run
|
| 21 |
+
// nested reads. Its value pointer is borrowed for the duration of the call.
|
| 22 |
+
// As with standard containers, T's special members must not reenter the index.
|
| 23 |
+
template<class T>
|
| 24 |
+
class Index {
|
| 25 |
+
static_assert(std::is_nothrow_move_constructible_v<T>,
|
| 26 |
+
"Afterkey requires a noexcept move constructor for T");
|
| 27 |
+
static_assert(std::is_nothrow_destructible_v<T>,
|
| 28 |
+
"Afterkey requires a noexcept destructor for T");
|
| 29 |
+
|
| 30 |
+
using Key = std::uint32_t;
|
| 31 |
+
using Revision = std::uint64_t;
|
| 32 |
+
static constexpr Key end = std::numeric_limits<Key>::max();
|
| 33 |
+
|
| 34 |
+
struct Slot {
|
| 35 |
+
Revision revision = 0;
|
| 36 |
+
Key older = end;
|
| 37 |
+
Key newer = end;
|
| 38 |
+
std::optional<T> value;
|
| 39 |
+
};
|
| 40 |
+
|
| 41 |
+
// Restore the previous flag for both nested reads and throwing callbacks.
|
| 42 |
+
struct ReadScope {
|
| 43 |
+
bool& flag;
|
| 44 |
+
bool previous;
|
| 45 |
+
|
| 46 |
+
explicit ReadScope(bool& active) noexcept
|
| 47 |
+
: flag(active), previous(active) { flag = true; }
|
| 48 |
+
~ReadScope() { flag = previous; }
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
public:
|
| 52 |
+
explicit Index(Key capacity) : slots_(capacity) {}
|
| 53 |
+
Index(const Index&) = delete;
|
| 54 |
+
Index& operator=(const Index&) = delete;
|
| 55 |
+
Index(Index&&) = delete;
|
| 56 |
+
Index& operator=(Index&&) = delete;
|
| 57 |
+
|
| 58 |
+
Revision version() const noexcept { return revision_; }
|
| 59 |
+
|
| 60 |
+
Revision put(Key key, T value) {
|
| 61 |
+
Slot& slot = writable(key);
|
| 62 |
+
slot.value.emplace(std::move(value));
|
| 63 |
+
return advance(key, slot);
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
Revision erase(Key key) {
|
| 67 |
+
Slot& slot = writable(key);
|
| 68 |
+
slot.value.reset();
|
| 69 |
+
return advance(key, slot);
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
// Visit each key touched strictly after cursor exactly once, in increasing
|
| 73 |
+
// last-write revision order. Null denotes deletion. Cursor 0 includes all
|
| 74 |
+
// touched keys. Cost is O(1 + keys returned), with no temporary allocation.
|
| 75 |
+
template<class F>
|
| 76 |
+
void since(Revision cursor, F&& callback) const {
|
| 77 |
+
if (cursor > revision_) {
|
| 78 |
+
throw std::out_of_range("Afterkey cursor exceeds current revision");
|
| 79 |
+
}
|
| 80 |
+
if (cursor == revision_) return;
|
| 81 |
+
|
| 82 |
+
Key first = oldest_;
|
| 83 |
+
if (slots_[first].revision <= cursor) {
|
| 84 |
+
first = newest_;
|
| 85 |
+
Key older = slots_[first].older;
|
| 86 |
+
while (older != end && slots_[older].revision > cursor) {
|
| 87 |
+
first = older;
|
| 88 |
+
older = slots_[first].older;
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
const ReadScope scope(reading_);
|
| 92 |
+
Key next = first;
|
| 93 |
+
while (next != end) {
|
| 94 |
+
const Key key = next;
|
| 95 |
+
const Slot& slot = slots_[key];
|
| 96 |
+
callback(slot.revision, key,
|
| 97 |
+
slot.value ? std::addressof(*slot.value) : nullptr);
|
| 98 |
+
next = slot.newer;
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
private:
|
| 103 |
+
Slot& writable(Key key) {
|
| 104 |
+
if (reading_) {
|
| 105 |
+
throw std::logic_error("Afterkey cannot mutate during a read");
|
| 106 |
+
}
|
| 107 |
+
if (key >= slots_.size()) {
|
| 108 |
+
throw std::out_of_range("Afterkey key exceeds capacity");
|
| 109 |
+
}
|
| 110 |
+
if (revision_ == std::numeric_limits<Revision>::max()) {
|
| 111 |
+
throw std::overflow_error("Afterkey revision exhausted");
|
| 112 |
+
}
|
| 113 |
+
return slots_[key];
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
Revision advance(Key key, Slot& slot) noexcept {
|
| 117 |
+
if (key != newest_) {
|
| 118 |
+
// A touched non-tail entry has a successor. Unlink it before
|
| 119 |
+
// appending, leaving untouched entries out of the list entirely.
|
| 120 |
+
if (slot.revision != 0) {
|
| 121 |
+
slots_[slot.newer].older = slot.older;
|
| 122 |
+
if (slot.older == end) oldest_ = slot.newer;
|
| 123 |
+
else slots_[slot.older].newer = slot.newer;
|
| 124 |
+
}
|
| 125 |
+
slot.older = newest_;
|
| 126 |
+
slot.newer = end;
|
| 127 |
+
if (newest_ == end) oldest_ = key;
|
| 128 |
+
else slots_[newest_].newer = key;
|
| 129 |
+
newest_ = key;
|
| 130 |
+
}
|
| 131 |
+
slot.revision = ++revision_;
|
| 132 |
+
return slot.revision;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
std::vector<Slot> slots_;
|
| 136 |
+
Key oldest_ = end;
|
| 137 |
+
Key newest_ = end;
|
| 138 |
+
Revision revision_ = 0;
|
| 139 |
+
mutable bool reading_ = false;
|
| 140 |
+
};
|
| 141 |
+
|
| 142 |
+
} // namespace afterkey
|
| 143 |
+
|
| 144 |
+
#endif // AFTERKEY_HPP
|
include/afterkey_journal.hpp
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef AFTERKEY_JOURNAL_HPP
|
| 2 |
+
#define AFTERKEY_JOURNAL_HPP
|
| 3 |
+
|
| 4 |
+
#include <algorithm>
|
| 5 |
+
#include <cstddef>
|
| 6 |
+
#include <cstdint>
|
| 7 |
+
#include <limits>
|
| 8 |
+
#include <memory>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <stdexcept>
|
| 11 |
+
#include <type_traits>
|
| 12 |
+
#include <utility>
|
| 13 |
+
#include <vector>
|
| 14 |
+
|
| 15 |
+
namespace afterkey {
|
| 16 |
+
|
| 17 |
+
// Chronological journal for dense keys [0, capacity). Same catch-up semantics
|
| 18 |
+
// as Index: each key has one last write (possibly a deletion), reader cursors
|
| 19 |
+
// are scoped to this instance, and callback values are borrowed. Serialize
|
| 20 |
+
// shared access externally. Nested reads work; writes during reads throw.
|
| 21 |
+
// T's special members must not reenter the journal.
|
| 22 |
+
//
|
| 23 |
+
// A fixed array holds at most 2*capacity chronological key entries. Rewriting
|
| 24 |
+
// a key marks its old position empty. On filling the array we pack all live
|
| 25 |
+
// entries at the front and remember their original revisions. Every append
|
| 26 |
+
// after packing has an implicit revision given by its position.
|
| 27 |
+
//
|
| 28 |
+
// Writes are O(1) amortized with an O(capacity) compaction pause at most once
|
| 29 |
+
// per capacity writes. A recent cursor seeks in O(1); a pre-compaction cursor
|
| 30 |
+
// seeks in O(log(1 + capacity)). Traversal scans at most
|
| 31 |
+
// min(2*capacity, version()-cursor) entries, possibly including obsolete ones.
|
| 32 |
+
// Storage is O(capacity), independent of writes and number of readers.
|
| 33 |
+
// No allocations on reads or writes by the journal after construction.
|
| 34 |
+
template<class T>
|
| 35 |
+
class Journal {
|
| 36 |
+
static_assert(std::is_nothrow_move_constructible_v<T>,
|
| 37 |
+
"Afterkey requires a noexcept move constructor for T");
|
| 38 |
+
static_assert(std::is_nothrow_destructible_v<T>,
|
| 39 |
+
"Afterkey requires a noexcept destructor for T");
|
| 40 |
+
|
| 41 |
+
using Key = std::uint32_t;
|
| 42 |
+
using Revision = std::uint64_t;
|
| 43 |
+
static constexpr Key empty = std::numeric_limits<Key>::max();
|
| 44 |
+
static constexpr std::size_t unused = std::numeric_limits<std::size_t>::max();
|
| 45 |
+
|
| 46 |
+
struct Slot {
|
| 47 |
+
std::size_t position = unused;
|
| 48 |
+
std::optional<T> value;
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
struct ReadScope {
|
| 52 |
+
bool& flag;
|
| 53 |
+
bool previous;
|
| 54 |
+
|
| 55 |
+
explicit ReadScope(bool& active) noexcept
|
| 56 |
+
: flag(active), previous(active) { flag = true; }
|
| 57 |
+
~ReadScope() { flag = previous; }
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
static std::size_t journal_capacity(Key keys) {
|
| 61 |
+
if (keys > std::numeric_limits<std::size_t>::max() / 2) {
|
| 62 |
+
throw std::length_error("Afterkey journal capacity exceeds address space");
|
| 63 |
+
}
|
| 64 |
+
return std::size_t{keys} * 2;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
public:
|
| 68 |
+
explicit Journal(Key capacity)
|
| 69 |
+
: limit_(journal_capacity(capacity)), slots_(capacity),
|
| 70 |
+
keys_(new Key[limit_]), packed_revisions_(new Revision[capacity]) {}
|
| 71 |
+
|
| 72 |
+
Journal(const Journal&) = delete;
|
| 73 |
+
Journal& operator=(const Journal&) = delete;
|
| 74 |
+
Journal(Journal&&) = delete;
|
| 75 |
+
Journal& operator=(Journal&&) = delete;
|
| 76 |
+
|
| 77 |
+
Revision version() const noexcept { return revision_; }
|
| 78 |
+
|
| 79 |
+
Revision put(Key key, T value) {
|
| 80 |
+
Slot& slot = writable(key);
|
| 81 |
+
slot.value.emplace(std::move(value));
|
| 82 |
+
return append(key, slot);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
Revision erase(Key key) {
|
| 86 |
+
Slot& slot = writable(key);
|
| 87 |
+
slot.value.reset();
|
| 88 |
+
return append(key, slot);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
template<class F>
|
| 92 |
+
void since(Revision cursor, F&& callback) const {
|
| 93 |
+
if (cursor > revision_) {
|
| 94 |
+
throw std::out_of_range("Afterkey cursor exceeds current revision");
|
| 95 |
+
}
|
| 96 |
+
if (cursor == revision_) return;
|
| 97 |
+
|
| 98 |
+
const ReadScope scope(reading_);
|
| 99 |
+
std::size_t start = packed_count_;
|
| 100 |
+
if (cursor < packed_through_) {
|
| 101 |
+
const Revision* first = packed_revisions_.get();
|
| 102 |
+
const Revision* pos = std::upper_bound(first, first + packed_count_, cursor);
|
| 103 |
+
for (auto i = static_cast<std::size_t>(pos - first); i < packed_count_; ++i) {
|
| 104 |
+
emit(keys_[i], first[i], callback);
|
| 105 |
+
}
|
| 106 |
+
} else {
|
| 107 |
+
start += static_cast<std::size_t>(cursor - packed_through_);
|
| 108 |
+
}
|
| 109 |
+
for (auto i = start; i < count_; ++i) {
|
| 110 |
+
emit(keys_[i], tail_revision(i), callback);
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
private:
|
| 115 |
+
Slot& writable(Key key) {
|
| 116 |
+
if (reading_) {
|
| 117 |
+
throw std::logic_error("Afterkey cannot mutate during a read");
|
| 118 |
+
}
|
| 119 |
+
if (key >= slots_.size()) {
|
| 120 |
+
throw std::out_of_range("Afterkey key exceeds capacity");
|
| 121 |
+
}
|
| 122 |
+
if (revision_ == std::numeric_limits<Revision>::max()) {
|
| 123 |
+
throw std::overflow_error("Afterkey revision exhausted");
|
| 124 |
+
}
|
| 125 |
+
return slots_[key];
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
template<class F>
|
| 129 |
+
void emit(Key key, Revision revision, F& callback) const {
|
| 130 |
+
if (key != empty) {
|
| 131 |
+
const auto& value = slots_[key].value;
|
| 132 |
+
callback(revision, key, value ? std::addressof(*value) : nullptr);
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
Revision tail_revision(std::size_t position) const noexcept {
|
| 137 |
+
return packed_through_ + (position - packed_count_) + 1;
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
void compact() noexcept {
|
| 141 |
+
std::size_t dst = 0;
|
| 142 |
+
for (std::size_t src = 0; src < count_; ++src) {
|
| 143 |
+
const Key key = keys_[src];
|
| 144 |
+
if (key == empty) continue;
|
| 145 |
+
const Revision rev = src < packed_count_ ? packed_revisions_[src]
|
| 146 |
+
: tail_revision(src);
|
| 147 |
+
keys_[dst] = key;
|
| 148 |
+
packed_revisions_[dst] = rev;
|
| 149 |
+
slots_[key].position = dst++;
|
| 150 |
+
}
|
| 151 |
+
packed_count_ = dst;
|
| 152 |
+
count_ = dst;
|
| 153 |
+
packed_through_ = revision_;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
Revision append(Key key, Slot& slot) noexcept {
|
| 157 |
+
if (slot.position != unused) keys_[slot.position] = empty;
|
| 158 |
+
if (count_ == limit_) compact();
|
| 159 |
+
keys_[count_] = key;
|
| 160 |
+
slot.position = count_++;
|
| 161 |
+
return ++revision_;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
const std::size_t limit_;
|
| 165 |
+
std::vector<Slot> slots_;
|
| 166 |
+
std::unique_ptr<Key[]> keys_;
|
| 167 |
+
std::unique_ptr<Revision[]> packed_revisions_;
|
| 168 |
+
std::size_t count_ = 0;
|
| 169 |
+
std::size_t packed_count_ = 0;
|
| 170 |
+
Revision packed_through_ = 0;
|
| 171 |
+
Revision revision_ = 0;
|
| 172 |
+
mutable bool reading_ = false;
|
| 173 |
+
};
|
| 174 |
+
|
| 175 |
+
} // namespace afterkey
|
| 176 |
+
|
| 177 |
+
#endif // AFTERKEY_JOURNAL_HPP
|
index.html
CHANGED
|
@@ -1,19 +1,136 @@
|
|
| 1 |
<!doctype html>
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
</html>
|
|
|
|
| 1 |
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<meta name="theme-color" content="#f6f7f3">
|
| 7 |
+
<title>Afterkey · Incremental state catch-up for C++17</title>
|
| 8 |
+
<meta name="description" content="Compare two independent readers of one live state stream. Explore overwrite coalescing, inspect reproducible C++17 benchmarks, and download the header-only library.">
|
| 9 |
+
<style>
|
| 10 |
+
:root{color-scheme:light;--paper:#f6f7f3;--ink:#17221d;--line:#cdd5ce;--muted:#515e55;--accent:#165440;--mono:"IBM Plex Mono",ui-monospace,Menlo,Consolas,monospace;font:16px/1.45 "Inter",system-ui,sans-serif;color:var(--ink);background:var(--paper)}
|
| 11 |
+
*{box-sizing:border-box}body{margin:0}.wrap{width:min(100% - 2.75rem,1090px);margin:auto}header{border-bottom:1px solid var(--line)}nav,.brand,.toolbar,.panelHead,.readerFoot,.streamHead,.legend,.legend span{display:flex;align-items:center}.brand{gap:.6rem;font-size:1.15rem;letter-spacing:-.04em;font-weight:740}nav{height:3.7rem;justify-content:space-between}nav small,.eyebrow,th,.rev,.note,.cursor,.kind,.keycode,.feedback,.tile,.metric small{font-family:var(--mono)}nav small,.note,.feedback{font-size:.76rem;color:var(--muted)}.mark{display:inline-grid;grid-template-columns:repeat(3,4px);align-items:end;gap:3px;height:20px}.mark i{background:var(--accent);height:50%}.mark i:nth-child(2){height:75%}.mark i:last-child{height:100%}
|
| 12 |
+
main{padding:clamp(1.8rem,5vw,3.7rem) 0 2rem}h1,h2,h3,p{margin:0}h1{font-size:clamp(2.4rem,6vw,4.25rem);line-height:1.04;letter-spacing:-.065em;font-weight:690}h1+ p{margin-top:.75rem;max-width:64ch;font-size:1.05rem;color:var(--muted)}.controls{display:flex;flex-wrap:wrap;align-items:flex-end;justify-content:space-between;gap:1.1rem;margin:1.7rem 0 1rem}.toolbar{gap:.55rem;flex-wrap:wrap}fieldset{margin:0;padding:0;border:0}legend,.eyebrow{font-size:.72rem;font-family:var(--mono);line-height:1.4;letter-spacing:.035em;color:var(--muted)}legend{margin-bottom:.32rem;padding:0}.seg{display:inline-flex;border:1px solid var(--line);border-radius:5px;overflow:hidden;background:white}.seg label{cursor:pointer;padding:.42rem .68rem;font-size:.86rem}.seg input{position:absolute;opacity:0;width:1px;height:1px}.seg input:checked+label{background:#dce9de;color:#103d2d;font-weight:650}.seg input:focus-visible+label{outline:2px solid var(--accent);outline-offset:-3px}
|
| 13 |
+
button{font-family:inherit;line-height:1.4;font-size:.88rem;font-weight:620;cursor:pointer;background:white;color:var(--ink);border:1px solid #aab7ad;border-radius:5px;padding:.57rem .82rem}button:hover:not(:disabled){background:#eff2ec}button:focus-visible{outline:3px solid #6d9379;outline-offset:3px}button:disabled{opacity:.5;cursor:default}.primary{background:var(--accent);color:white;border-color:var(--accent)}.primary:hover:not(:disabled){background:#103f30}h2{font-size:1.18rem;letter-spacing:-.035em;line-height:1.25}.stream{background:#202e26;color:#f6f8f2;padding:1.25rem 1.3rem;border-radius:9px}.streamHead{justify-content:space-between;gap:.75rem}.rev{font-size:.83rem;color:#c2d0c4}.tiles{display:grid;grid-template-columns:repeat(24,minmax(0,1fr));gap:3px;margin:1.1rem 0 .68rem;list-style:none;padding:0}.tile{display:grid;place-items:center;min-height:2.5rem;border-bottom:3px solid #9cc0a8;background:#354a3c;color:#f3f7ed;font-size:.75rem;font-weight:600}.tile[data-band="1"]{background:#45563b;border-color:#b6bd8d}.tile[data-band="2"]{background:#354950;border-color:#9fbac7}.tile[data-band="3"]{background:#53463d;border-color:#c5a58a}.tile.deleted{border-bottom-style:dashed}.legend{justify-content:space-between;flex-wrap:wrap;gap:.3rem 1rem;font: .72rem/1.5 var(--mono);color:#cbd6c9}.readers{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem;margin:1rem 0}.reader{background:white;border:1px solid var(--line);border-radius:9px;overflow:hidden}.panelHead{padding:1.12rem 1.15rem .8rem;gap:.8rem;justify-content:space-between}.panelHead p{font-size:.83rem;color:var(--muted);margin-top:.18rem}.cursor{font-size:.76rem;white-space:nowrap;color:var(--muted)}.metrics{display:grid;grid-template-columns:1fr 1fr;gap:.5rem;margin:0 1.15rem 1rem}.metric{display:flex;align-items:baseline;gap:.42rem;flex-wrap:wrap}.metric strong{font-size:2rem;letter-spacing:-.065em;line-height:1.1;font-weight:660;font-variant-numeric:tabular-nums}.metric small{font-size:.72rem;color:var(--muted)}.tableWrap{margin:0 1.15rem;height:13rem;overflow:auto;border:1px solid #d9dfd8;border-radius:4px}table{width:100%;border-collapse:separate;border-spacing:0;text-align:left;font-size:.8rem}th{position:sticky;top:0;background:#f3f5f0;font-size:.72rem;color:var(--muted);font-weight:500}th,td{padding:.33rem .52rem;border-bottom:1px solid #e2e7e2}td{font-family:var(--mono);font-size:.77rem}.empty td{color:var(--muted);padding:.75rem}.readerFoot{padding:.85rem 1.15rem 1.1rem;gap:.65rem;align-items:center}.feedback{line-height:1.35}.feedback strong{font-weight:600;color:var(--accent)}.note{padding-top:.45rem;line-height:1.55}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
|
| 14 |
+
.resources{display:flex;align-items:center;flex-wrap:wrap;gap:.3rem 1.1rem;margin-top:1.05rem}.resources a{font-size:.87rem;font-weight:630;color:var(--accent);text-underline-offset:3px}.resources a:first-child{padding:.43rem .75rem;border:1px solid #a8b9ab;border-radius:5px;text-decoration:none;background:#fff}.resources a:hover{color:#092d20}.resources a:focus-visible{outline:3px solid #6d9379;outline-offset:3px}
|
| 15 |
+
@media(max-width:690px){.readers{grid-template-columns:1fr}.tiles{grid-template-columns:repeat(12,minmax(0,1fr))}.tile{min-height:1.8rem}.wrap{width:calc(100% - 1.5rem)}.controls{gap:.75rem}.tableWrap{height:10rem}.readerFoot{align-items:flex-start}.stream{padding:1rem}.metric strong{font-size:1.7rem}}
|
| 16 |
+
@media(prefers-reduced-motion:no-preference){button,.seg label{transition:background .12s ease}}
|
| 17 |
+
</style>
|
| 18 |
+
</head>
|
| 19 |
+
<body>
|
| 20 |
+
<header><nav class="wrap" aria-label="Product"><div class="brand"><span class="mark" aria-hidden="true"><i></i><i></i><i></i></span>Afterkey</div><small>Live reader demo</small></nav></header>
|
| 21 |
+
<main class="wrap">
|
| 22 |
+
<h1>Catch up by key.</h1>
|
| 23 |
+
<p>Two readers share one stream. Each receives the latest value or deletion for every key written since its own cursor.</p>
|
| 24 |
+
<div class="resources" aria-label="Release resources">
|
| 25 |
+
<a href="https://github.com/pgg898200-ship-it/streamsieve/tree/main/afterkey">Source & quickstart ↗</a>
|
| 26 |
+
<a href="https://github.com/pgg898200-ship-it/streamsieve/blob/main/afterkey/bench/results.csv">Benchmark results</a>
|
| 27 |
+
<a href="https://raw.githubusercontent.com/pgg898200-ship-it/streamsieve/main/afterkey/releases/afterkey-0.1.0.zip">Download v0.1.0 (ZIP)</a>
|
| 28 |
+
</div>
|
| 29 |
+
<section class="controls" aria-label="Producer controls">
|
| 30 |
+
<fieldset><legend>Write pattern</legend><div class="seg"><input type="radio" id="hot" name="pattern" value="hot" checked><label for="hot">Hot · 4 keys</label><input type="radio" id="wide" name="pattern" value="wide"><label for="wide">Wide · 24 keys</label></div></fieldset>
|
| 31 |
+
<div class="toolbar"><button id="reset" type="button">Reset</button><button id="burst" type="button" class="primary">Write 24 updates</button></div>
|
| 32 |
+
</section>
|
| 33 |
+
<section class="stream" aria-labelledby="streamTitle">
|
| 34 |
+
<div class="streamHead"><h2 id="streamTitle">Producer stream</h2><span class="rev" id="head"></span></div>
|
| 35 |
+
<ol class="tiles" id="tiles" aria-label="Most recent 24 writes, oldest first"></ol>
|
| 36 |
+
<div class="legend"><span id="range"></span><span>Key IDs · × marks deletion</span></div>
|
| 37 |
+
</section>
|
| 38 |
+
<section class="readers" id="readers" aria-label="Independent readers"></section>
|
| 39 |
+
<p class="note">Tables preview the exact rows each reader can consume, ordered by last write. Skipped writes were superseded for that reader. This JavaScript illustration shows delivery semantics. Timing benchmarks run against the C++17 index.</p>
|
| 40 |
+
<section style="margin-top:1.75rem;border-top:1px solid var(--line);padding-top:1.15rem" aria-labelledby="native-results">
|
| 41 |
+
<h2 id="native-results">What happens with 4,096 readers?</h2>
|
| 42 |
+
<p style="margin-top:.5rem;max-width:78ch">On a single thread with a million populated keys, p99 catch-up took <strong>1.67 µs</strong> for Afterkey and <strong>4.99 µs</strong> for a cursor log when writes moved among hot keys. With uniform writes, the log won at 75.92 µs against Afterkey’s 417.86 µs. Each measurement includes delivery to the in-process callback.</p>
|
| 43 |
+
<div class="resources"><a href="https://github.com/pgg898200-ship-it/streamsieve/blob/main/afterkey/bench/fanout.cpp">Run the native benchmark</a></div>
|
| 44 |
+
</section>
|
| 45 |
+
<p class="sr" role="status" id="status"></p>
|
| 46 |
+
</main>
|
| 47 |
+
<script>
|
| 48 |
+
'use strict';
|
| 49 |
+
const BURST_SIZE = 24;
|
| 50 |
+
const FAST_INTERVAL = 10;
|
| 51 |
+
const latest = new Map();
|
| 52 |
+
const recent = [];
|
| 53 |
+
const readers = [{name:'Fast reader', cadence:'Reads every 10 writes'}, {name:'Slow reader', cadence:'Reads on demand'}];
|
| 54 |
+
let revision = 0;
|
| 55 |
+
let writePattern = 'hot';
|
| 56 |
+
function pending(reader) {
|
| 57 |
+
return [...latest.values()].filter(entry => entry.rev > reader.cursor);
|
| 58 |
+
}
|
| 59 |
+
function readPending(reader) {
|
| 60 |
+
const rows = pending(reader);
|
| 61 |
+
const span = revision - reader.cursor;
|
| 62 |
+
reader.last = {rows: rows.length, skipped: span - rows.length, rev: revision};
|
| 63 |
+
reader.cursor = revision;
|
| 64 |
+
}
|
| 65 |
+
function burst() {
|
| 66 |
+
for (let i = 0; i < BURST_SIZE; i++) {
|
| 67 |
+
revision++;
|
| 68 |
+
const cardinality = writePattern === 'hot' ? 4 : 24;
|
| 69 |
+
const key = (7 * (revision - 1)) % cardinality;
|
| 70 |
+
const value = revision % 11 === 0 ? null : (13 * revision + 17 * key) % 100;
|
| 71 |
+
const entry = {key, value, rev: revision};
|
| 72 |
+
// Reinsertion preserves increasing last-write order, just like the index list.
|
| 73 |
+
latest.delete(key);
|
| 74 |
+
latest.set(key, entry);
|
| 75 |
+
recent.push(entry);
|
| 76 |
+
if (recent.length > BURST_SIZE) recent.shift();
|
| 77 |
+
if (revision % FAST_INTERVAL === 0) readPending(readers[0]);
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
function reset() {
|
| 81 |
+
latest.clear();
|
| 82 |
+
recent.length = 0;
|
| 83 |
+
revision = 0;
|
| 84 |
+
for (const reader of readers) { reader.cursor = 0; reader.last = null; }
|
| 85 |
+
burst();
|
| 86 |
+
}
|
| 87 |
+
function two(n) { return String(n).padStart(2,'0'); }
|
| 88 |
+
function row(entry) {
|
| 89 |
+
const value = entry.value === null ? 'deleted' : String(entry.value);
|
| 90 |
+
return '<tr><td>'+entry.rev+'</td><td>k'+two(entry.key)+'</td><td>'+value+'</td></tr>';
|
| 91 |
+
}
|
| 92 |
+
function renderReader(reader, index) {
|
| 93 |
+
const rows = pending(reader);
|
| 94 |
+
const skipped = revision - reader.cursor - rows.length;
|
| 95 |
+
const feedback = reader.last ? 'Last read at r'+reader.last.rev+'<br><strong>'+reader.last.rows+' delivered · '+reader.last.skipped+' skipped</strong>' : 'Awaiting first read';
|
| 96 |
+
const panel = document.getElementById('reader-'+index);
|
| 97 |
+
panel.querySelector('.cursor').textContent = 'Cursor r'+reader.cursor;
|
| 98 |
+
panel.querySelector('.count').textContent = rows.length;
|
| 99 |
+
panel.querySelector('.skipped').textContent = skipped;
|
| 100 |
+
panel.querySelector('tbody').innerHTML = rows.length ? rows.map(row).join('') : '<tr class="empty"><td colspan="3">Caught up through revision '+revision+'.</td></tr>';
|
| 101 |
+
panel.querySelector('.feedback').innerHTML = feedback;
|
| 102 |
+
panel.querySelector('button').disabled = rows.length === 0;
|
| 103 |
+
}
|
| 104 |
+
function render(message) {
|
| 105 |
+
document.getElementById('head').textContent = 'Head r'+revision;
|
| 106 |
+
document.getElementById('range').textContent = 'r'+recent[0].rev+' → r'+revision;
|
| 107 |
+
document.getElementById('tiles').innerHTML = recent.map(entry => {
|
| 108 |
+
const deleted = entry.value === null;
|
| 109 |
+
const label = 'Revision '+entry.rev+', key '+entry.key+', '+(deleted ? 'deleted' : 'value '+entry.value);
|
| 110 |
+
return '<li class="tile'+(deleted ? ' deleted' : '')+'" data-band="'+entry.key%4+'" title="'+label+'" aria-label="'+label+'">'+two(entry.key)+(deleted ? '×' : '')+'</li>';
|
| 111 |
+
}).join('');
|
| 112 |
+
readers.forEach(renderReader);
|
| 113 |
+
document.getElementById('status').textContent = message;
|
| 114 |
+
}
|
| 115 |
+
for (const [index, reader] of readers.entries()) {
|
| 116 |
+
const el = document.createElement('article');
|
| 117 |
+
el.className='reader';
|
| 118 |
+
el.id='reader-'+index;
|
| 119 |
+
el.innerHTML='<div class="panelHead"><div><h2>'+reader.name+'</h2><p>'+reader.cadence+'</p></div><span class="cursor"></span></div><div class="metrics"><div class="metric"><strong class="count"></strong><small>pending keys</small></div><div class="metric"><strong class="skipped"></strong><small>skippable writes</small></div></div><div class="tableWrap" tabindex="0" role="region" aria-label="'+reader.name+' pending changes"><table><thead><tr><th>Revision</th><th>Key</th><th>Latest value</th></tr></thead><tbody></tbody></table></div><div class="readerFoot"><button type="button" aria-label="Read pending changes for '+reader.name.toLowerCase()+'">Read pending</button><p class="feedback"></p></div>';
|
| 120 |
+
document.getElementById('readers').append(el);
|
| 121 |
+
el.querySelector('button').addEventListener('click', () => {
|
| 122 |
+
readPending(reader);
|
| 123 |
+
render(reader.name+' caught up to revision '+revision+'.');
|
| 124 |
+
});
|
| 125 |
+
}
|
| 126 |
+
document.getElementById('burst').addEventListener('click', () => { burst(); render('24 updates written. Head revision '+revision+'.'); });
|
| 127 |
+
document.getElementById('reset').addEventListener('click', () => { reset(); render('Reset with one initial burst of 24 writes.'); });
|
| 128 |
+
document.querySelectorAll('input[name=pattern]').forEach(input => input.addEventListener('change', () => {
|
| 129 |
+
writePattern=input.value;
|
| 130 |
+
document.getElementById('status').textContent='Next burst uses '+(writePattern==='hot'?'4 hot keys.':'24 distinct keys.');
|
| 131 |
+
}));
|
| 132 |
+
reset();
|
| 133 |
+
render('Initial burst of 24 writes.');
|
| 134 |
+
</script>
|
| 135 |
+
</body>
|
| 136 |
</html>
|
releases/afterkey-0.1.0.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3236bc6e1cb68ad0a28362b6b2afdb0daac4ef2b75c8a880b00ae76b70403402
|
| 3 |
+
size 39583
|
tests/test_afterkey.cpp
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "../include/afterkey.hpp"
|
| 2 |
+
#include "../include/afterkey_journal.hpp"
|
| 3 |
+
|
| 4 |
+
#include <algorithm>
|
| 5 |
+
#include <cstdint>
|
| 6 |
+
#include <cstdlib>
|
| 7 |
+
#include <iostream>
|
| 8 |
+
#include <limits>
|
| 9 |
+
#include <memory>
|
| 10 |
+
#include <optional>
|
| 11 |
+
#include <random>
|
| 12 |
+
#include <stdexcept>
|
| 13 |
+
#include <string>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace {
|
| 18 |
+
|
| 19 |
+
using Revision = std::uint64_t;
|
| 20 |
+
using Key = std::uint32_t;
|
| 21 |
+
using Change = std::tuple<Revision, Key, std::optional<int>>;
|
| 22 |
+
using Changes = std::vector<Change>;
|
| 23 |
+
|
| 24 |
+
void check(bool ok, const char* message) {
|
| 25 |
+
if (!ok) throw std::runtime_error(message);
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
template <typename F>
|
| 29 |
+
void expect_exception(F action, const char* message) {
|
| 30 |
+
try {
|
| 31 |
+
action();
|
| 32 |
+
} catch (const std::exception&) {
|
| 33 |
+
return;
|
| 34 |
+
}
|
| 35 |
+
throw std::runtime_error(message);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
template <typename Index>
|
| 39 |
+
Changes read(const Index& index, Revision since) {
|
| 40 |
+
Changes result;
|
| 41 |
+
index.since(since, [&](Revision rev, Key key, const int* value) {
|
| 42 |
+
result.emplace_back(rev, key, value ? std::optional<int>(*value) : std::nullopt);
|
| 43 |
+
});
|
| 44 |
+
return result;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// Retain every write, then independently compute last-write-wins in the query window.
|
| 48 |
+
Changes oracle(const Changes& history, Revision cursor, Key capacity) {
|
| 49 |
+
std::vector<bool> seen(capacity);
|
| 50 |
+
Changes answer;
|
| 51 |
+
for (auto it = history.rbegin(); it != history.rend(); ++it) {
|
| 52 |
+
const auto& [revision, key, value] = *it;
|
| 53 |
+
if (revision <= cursor) break;
|
| 54 |
+
if (!seen[key]) {
|
| 55 |
+
seen[key] = true;
|
| 56 |
+
answer.push_back(*it);
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
std::reverse(answer.begin(), answer.end());
|
| 60 |
+
return answer;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
template <typename Index>
|
| 64 |
+
void expect_read(const Index& index, Revision cursor, const Changes& expected, const char* source) {
|
| 65 |
+
const Changes actual = read(index, cursor);
|
| 66 |
+
auto mismatch = std::mismatch(expected.begin(), expected.end(), actual.begin(), actual.end());
|
| 67 |
+
if (mismatch.first != expected.end() || mismatch.second != actual.end()) {
|
| 68 |
+
auto describe = [](auto it, auto end) -> std::string {
|
| 69 |
+
if (it == end) return "<end>";
|
| 70 |
+
const auto& [rev, key, value] = *it;
|
| 71 |
+
return "(rev=" + std::to_string(rev) + ", key=" + std::to_string(key)
|
| 72 |
+
+ ", value=" + (value ? std::to_string(*value) : "tombstone") + ")";
|
| 73 |
+
};
|
| 74 |
+
throw std::runtime_error(std::string(source) + " at version " + std::to_string(index.version())
|
| 75 |
+
+ ", cursor " + std::to_string(cursor)
|
| 76 |
+
+ ", row " + std::to_string(mismatch.first - expected.begin())
|
| 77 |
+
+ ": expected " + describe(mismatch.first, expected.end())
|
| 78 |
+
+ ", found " + describe(mismatch.second, actual.end()));
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
template <typename Index>
|
| 83 |
+
void check_read(const Index& index, const Changes& history, Revision cursor, Key capacity) {
|
| 84 |
+
expect_read(index, cursor, oracle(history, cursor, capacity), "full-history comparison");
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
void compaction_boundaries() {
|
| 88 |
+
// Warm every key, then alternate sweeps (recent contiguous revisions) with
|
| 89 |
+
// repeated writes to one key (holes in both packed prefix and recent tail).
|
| 90 |
+
// Capacity one exercises a compaction whose entire previous prefix is stale.
|
| 91 |
+
for (Key capacity : {1u, 2u, 7u, 13u}) {
|
| 92 |
+
afterkey::Index<int> linked(capacity);
|
| 93 |
+
afterkey::Journal<int> journal(capacity);
|
| 94 |
+
Changes history;
|
| 95 |
+
for (Revision rev = 1; rev <= 23 * capacity; ++rev) {
|
| 96 |
+
const auto cycle = (rev - 1) / capacity;
|
| 97 |
+
Key key = static_cast<Key>((rev - 1) % capacity);
|
| 98 |
+
if (cycle % 3 == 1) key = static_cast<Key>(cycle % capacity);
|
| 99 |
+
std::optional<int> value;
|
| 100 |
+
if (rev % 4 == 0) {
|
| 101 |
+
linked.erase(key);
|
| 102 |
+
journal.erase(key);
|
| 103 |
+
} else {
|
| 104 |
+
value = static_cast<int>(rev);
|
| 105 |
+
linked.put(key, *value);
|
| 106 |
+
journal.put(key, *value);
|
| 107 |
+
}
|
| 108 |
+
history.emplace_back(rev, key, value);
|
| 109 |
+
// All cursors at every intermediate state include exact cuts on
|
| 110 |
+
// either side of each compaction and each subsequent tail append.
|
| 111 |
+
for (Revision cursor = 0; cursor <= rev; ++cursor) {
|
| 112 |
+
const Changes expected = oracle(history, cursor, capacity);
|
| 113 |
+
expect_read(linked, cursor, expected, "Index compaction workload");
|
| 114 |
+
expect_read(journal, cursor, expected, "Journal compaction workload");
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
template <template <typename> class Engine>
|
| 121 |
+
void lifecycle() {
|
| 122 |
+
Engine<int> index(4);
|
| 123 |
+
check(index.version() == 0 && read(index, 0).empty(), "initial state");
|
| 124 |
+
check(index.put(3, 9) == 1, "put returns its revision");
|
| 125 |
+
index.put(0, 1);
|
| 126 |
+
const Revision slow = index.version();
|
| 127 |
+
check(index.erase(3) == 3, "erase returns its revision");
|
| 128 |
+
const Revision fast = index.version();
|
| 129 |
+
index.erase(2); // previously absent
|
| 130 |
+
index.erase(2); // duplicate deletion still advances revision
|
| 131 |
+
index.put(3, 42);
|
| 132 |
+
check(index.version() == 6, "each write must advance revision");
|
| 133 |
+
check(read(index, fast) == Changes{{5, 2, std::nullopt}, {6, 3, 42}}, "fast cursor");
|
| 134 |
+
check(read(index, slow) == read(index, fast), "restored value coalesces deletion");
|
| 135 |
+
check(read(index, 0) == Changes{{2, 0, 1}, {5, 2, std::nullopt}, {6, 3, 42}},
|
| 136 |
+
"slowest cursor reports current state in revision order");
|
| 137 |
+
check(read(index, index.version()).empty(), "reader already caught up");
|
| 138 |
+
index.put(3, 42);
|
| 139 |
+
check(read(index, 6) == Changes{{7, 3, 42}}, "identical put still counts");
|
| 140 |
+
index.erase(3);
|
| 141 |
+
check(read(index, 7) == Changes{{8, 3, std::nullopt}}, "visible deletion");
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
template <template <typename> class Engine>
|
| 145 |
+
void random_history() {
|
| 146 |
+
constexpr Key capacity = 67;
|
| 147 |
+
for (unsigned seed : {0u, 19u, 351u}) {
|
| 148 |
+
std::mt19937 rng(seed);
|
| 149 |
+
Engine<int> index(capacity);
|
| 150 |
+
Changes history;
|
| 151 |
+
std::vector<Revision> readers(6);
|
| 152 |
+
for (Revision revision = 1; revision <= 1800; ++revision) {
|
| 153 |
+
// Interleave a hot key with sparse changes to many other keys.
|
| 154 |
+
Key key = (rng() % 4 == 0) ? 0 : static_cast<Key>(rng() % capacity);
|
| 155 |
+
std::optional<int> payload;
|
| 156 |
+
if (rng() % 3 == 0) {
|
| 157 |
+
index.erase(key);
|
| 158 |
+
} else {
|
| 159 |
+
payload = static_cast<int>(rng() % 4);
|
| 160 |
+
index.put(key, *payload);
|
| 161 |
+
}
|
| 162 |
+
history.emplace_back(revision, key, payload);
|
| 163 |
+
check(index.version() == revision, "version drift");
|
| 164 |
+
auto& reader = readers[rng() % readers.size()];
|
| 165 |
+
check_read(index, history, reader, capacity);
|
| 166 |
+
if (rng() % 3 == 0) reader = revision;
|
| 167 |
+
if (revision % 23 == 0) check_read(index, history, rng() % (revision + 1), capacity);
|
| 168 |
+
}
|
| 169 |
+
for (Revision cursor = 0; cursor <= history.size(); ++cursor)
|
| 170 |
+
check_read(index, history, cursor, capacity);
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
template <template <typename> class Engine>
|
| 175 |
+
void rejected_operations() {
|
| 176 |
+
Engine<int> empty(0);
|
| 177 |
+
check(empty.version() == 0 && read(empty, 0).empty(), "zero capacity");
|
| 178 |
+
expect_exception([&] { empty.put(0, 5); }, "put into zero capacity");
|
| 179 |
+
expect_exception([&] { empty.erase(0); }, "erase from zero capacity");
|
| 180 |
+
|
| 181 |
+
Engine<int> index(2);
|
| 182 |
+
index.put(1, 4);
|
| 183 |
+
const Changes expected{{1, 1, 4}};
|
| 184 |
+
for (Key key : {Key{2}, std::numeric_limits<Key>::max()}) {
|
| 185 |
+
expect_exception([&] { index.put(key, 8); }, "out-of-range put");
|
| 186 |
+
expect_exception([&] { index.erase(key); }, "out-of-range erase");
|
| 187 |
+
}
|
| 188 |
+
bool visited = false;
|
| 189 |
+
expect_exception([&] {
|
| 190 |
+
index.since(2, [&](auto, auto, const int*) { visited = true; });
|
| 191 |
+
}, "future cursor");
|
| 192 |
+
check(!visited && index.version() == 1 && read(index, 0) == expected,
|
| 193 |
+
"rejections must leave state intact");
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
template <template <typename> class Engine>
|
| 197 |
+
void callback_rules() {
|
| 198 |
+
struct Stop {};
|
| 199 |
+
Engine<int> index(4);
|
| 200 |
+
index.put(0, 10);
|
| 201 |
+
index.put(1, 20);
|
| 202 |
+
index.erase(2);
|
| 203 |
+
const Changes expected = read(index, 0);
|
| 204 |
+
int outer = 0;
|
| 205 |
+
index.since(0, [&](Revision, Key, const int*) {
|
| 206 |
+
++outer;
|
| 207 |
+
check(read(index, 0) == expected, "nested full read");
|
| 208 |
+
index.since(2, [&](Revision rev, Key key, const int* v) {
|
| 209 |
+
check(rev == 3 && key == 2 && v == nullptr, "nested read");
|
| 210 |
+
expect_exception([&] { index.put(0, 99); }, "put during nested read");
|
| 211 |
+
});
|
| 212 |
+
try {
|
| 213 |
+
index.since(0, [](Revision, Key, const int*) { throw Stop{}; });
|
| 214 |
+
} catch (Stop) {
|
| 215 |
+
expect_exception([&] { index.put(2, 9); }, "write after a nested callback throws");
|
| 216 |
+
}
|
| 217 |
+
expect_exception([&] { index.erase(3); }, "write after nested read");
|
| 218 |
+
});
|
| 219 |
+
check(outer == 3 && index.version() == 3 && read(index, 0) == expected,
|
| 220 |
+
"outer read disturbed by nested callbacks");
|
| 221 |
+
|
| 222 |
+
int calls = 0;
|
| 223 |
+
bool caught = false;
|
| 224 |
+
try {
|
| 225 |
+
index.since(0, [&](Revision, Key, const int*) {
|
| 226 |
+
if (++calls == 2) throw Stop{};
|
| 227 |
+
});
|
| 228 |
+
} catch (Stop) {
|
| 229 |
+
caught = true;
|
| 230 |
+
}
|
| 231 |
+
check(caught && calls == 2, "exception must propagate immediately");
|
| 232 |
+
index.put(0, 100);
|
| 233 |
+
check(read(index, 3) == Changes{{4, 0, 100}}, "write after interrupted read");
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
template <template <typename> class Engine>
|
| 237 |
+
void move_only() {
|
| 238 |
+
Engine<std::unique_ptr<int>> index(2);
|
| 239 |
+
index.put(0, std::make_unique<int>(1));
|
| 240 |
+
index.put(1, std::make_unique<int>(2));
|
| 241 |
+
index.put(0, std::make_unique<int>(3));
|
| 242 |
+
index.erase(1);
|
| 243 |
+
std::vector<int> values;
|
| 244 |
+
index.since(0, [&](Revision, Key, const std::unique_ptr<int>* p) {
|
| 245 |
+
values.push_back(p ? **p : -1);
|
| 246 |
+
});
|
| 247 |
+
check(values == std::vector<int>({3, -1}), "move-only replacement and erase");
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
template <template <typename> class Engine>
|
| 251 |
+
void failed_copy() {
|
| 252 |
+
struct CopyFails {
|
| 253 |
+
int value;
|
| 254 |
+
explicit CopyFails(int v) : value(v) {}
|
| 255 |
+
CopyFails(const CopyFails&) { throw std::runtime_error("copy failed"); }
|
| 256 |
+
CopyFails(CopyFails&&) noexcept = default;
|
| 257 |
+
};
|
| 258 |
+
Engine<CopyFails> index(1);
|
| 259 |
+
index.put(0, CopyFails{9});
|
| 260 |
+
const CopyFails next{11};
|
| 261 |
+
expect_exception([&] { index.put(0, next); }, "copy failure propagates");
|
| 262 |
+
int observed = 0;
|
| 263 |
+
index.since(0, [&](Revision, Key, const CopyFails* value) { observed = value->value; });
|
| 264 |
+
check(index.version() == 1 && observed == 9, "copy failure preserves previous state");
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
template <template <typename> class Engine>
|
| 268 |
+
void run_suite(const char* name) {
|
| 269 |
+
try {
|
| 270 |
+
lifecycle<Engine>();
|
| 271 |
+
random_history<Engine>();
|
| 272 |
+
rejected_operations<Engine>();
|
| 273 |
+
callback_rules<Engine>();
|
| 274 |
+
move_only<Engine>();
|
| 275 |
+
failed_copy<Engine>();
|
| 276 |
+
} catch (const std::exception& error) {
|
| 277 |
+
throw std::runtime_error(std::string(name) + ": " + error.what());
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
} // namespace
|
| 282 |
+
|
| 283 |
+
int main() {
|
| 284 |
+
try {
|
| 285 |
+
run_suite<afterkey::Index>("Index");
|
| 286 |
+
run_suite<afterkey::Journal>("Journal");
|
| 287 |
+
compaction_boundaries();
|
| 288 |
+
} catch (const std::exception& error) {
|
| 289 |
+
std::cerr << "Afterkey test failure: " << error.what() << '\n';
|
| 290 |
+
return EXIT_FAILURE;
|
| 291 |
+
}
|
| 292 |
+
std::cout << "Afterkey tests passed\n";
|
| 293 |
+
}
|