pgg-engineering commited on
Commit
c11c9e3
·
verified ·
1 Parent(s): 1cb6a3e

Publish the KthWake threshold timeline, C++ kit and tested example

Browse files
Files changed (8) hide show
  1. LICENSE +202 -0
  2. README.md +53 -6
  3. SHA256SUMS +2 -0
  4. art/share.png +0 -0
  5. deadline-arrivals.svg +48 -0
  6. index.html +305 -18
  7. kthwake-0.1.0.tar.gz +3 -0
  8. kthwake.hpp +453 -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,57 @@
1
  ---
2
- title: Kthwake
3
- emoji: 🐠
4
- colorFrom: gray
5
- colorTo: blue
 
 
 
 
6
  sdk: static
7
- pinned: false
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: KthWake · Sliding-window threshold scheduler
3
+ emoji: ⏱️
4
+ license: apache-2.0
5
+ tags:
6
+ - cpp
7
+ - stream-processing
8
+ - time-series
9
+ - multi-agent
10
  sdk: static
11
+ app_file: index.html
12
+ short_description: Turn rolling event counts into callbacks and idle deadlines
13
+ colorFrom: gray
14
+ colorTo: gray
15
+ thumbnail: https://huggingface.co/spaces/pgg-engineering/kthwake/resolve/main/art/share.png
16
  ---
17
 
18
+ # KthWake · Sliding-window threshold scheduler
19
+
20
+ Wake a waiting task when three tool results finish in 20 ms. KthWake sits between an ordered stream of completions and a scheduler. Feed it a timestamp and an arrival count. It returns the IDs and new states of rules that changed. The scheduler can set one timer for the next expiry, even when no more results arrive.
21
+
22
+ ![A three-in-20-ms rule turns on at 5 ms. It turns off at 20 ms on an idle stream, or at 25 ms if two more results arrive at 20 ms.](https://huggingface.co/spaces/pgg-engineering/kthwake/resolve/main/deadline-arrivals.svg)
23
+
24
+ [Open the timeline](https://pgg-engineering-kthwake.static.hf.space/) · [C++ source kit](https://huggingface.co/spaces/pgg-engineering/kthwake/resolve/main/kthwake-0.1.0.tar.gz) · [Single header](https://huggingface.co/spaces/pgg-engineering/kthwake/resolve/main/kthwake.hpp) · [Checksums for these two files](https://huggingface.co/spaces/pgg-engineering/kthwake/resolve/main/SHA256SUMS)
25
+
26
+ ## Replay a deadline
27
+
28
+ The timeline starts with two completions at 0 ms and one at 5 ms. The third completion turns rule 0 on. Choose **Next callback** to watch it turn off at 20 ms, when the first two completions leave the window.
29
+
30
+ To try the second run, enter `0, 0, 5, 20, 20` under **Completion times (ms)** and choose **Apply trace**. Arrivals and expiries at the same timestamp count together. At 20 ms, the first pair expires and the new pair arrives. Three completions still qualify, so the rule stays on. The next callback turns it off at 25 ms.
31
+
32
+ The browser timeline runs in JavaScript. Both traces above also ran against the released C++17 implementation. The Python binding and JSONL CLI use the native index.
33
+
34
+ ## Install the Python binding
35
+
36
+ Build the binding with CPython, a C++17 compiler, wheel and setuptools.
37
+
38
+ ```sh
39
+ python -m pip install --no-build-isolation 'git+https://github.com/pgg898200-ship-it/chronosieve.git@7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f#subdirectory=companions/kthwake'
40
+ ```
41
+
42
+ ```python
43
+ from kthwake import Index
44
+ ix = Index([(3, 20)])
45
+ assert ix.step(100, 2) == []
46
+ assert ix.step(105, 1) == [(0, True)]
47
+ assert ix.next_expiry() == 120
48
+ assert ix.step(120) == [(0, False)]
49
+ ```
50
+
51
+ The [release downloads](https://github.com/pgg898200-ship-it/chronosieve/tree/f6df7cdb54362fea22003a814ac83fcc7b179a8f/companions/kthwake/downloads/v0.1.0) include the source archive, header, CPython 3.12 Linux x86-64 wheel, native Linux x86-64 CLI and benchmark results. The file named `SHA256SUMS` lists the digest for each download.
52
+
53
+ ## Benchmarks and contributions
54
+
55
+ The runnable release includes recorded arrivals from Mooncake and an Azure code-serving holdout, with three modeled policy registries per trace. It also includes million-subscriber synthetic cases, a timestamp-aware correctness oracle and competing native implementations. Evaluations distinguish observation-time snapshots from every timer-driven crossing. On the Azure individual-rate workload, KthWake delivered 330,890 timestamped transitions in 37.1 ms. The fastest of three native heap alternatives took 75.0 ms. The heap won the other two Azure timer workloads.
56
+
57
+ [Performance evidence](https://github.com/pgg898200-ship-it/chronosieve/blob/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake/EVIDENCE.md) · [Source files](https://github.com/pgg898200-ship-it/chronosieve/tree/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake) · [Independent benchmark instructions](https://github.com/pgg898200-ship-it/chronosieve/blob/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake/REPRODUCE.md) · [Community](https://huggingface.co/spaces/pgg-engineering/kthwake/discussions)
SHA256SUMS ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ dcf3ac61cdd7638c509de61b7e33da43aaef0d6e0ea38cc462021ffce7c8b1bf kthwake-0.1.0.tar.gz
2
+ cbe5699dc92016fe49bd0d003836ef6d7916d11bd07cbc746874d6ad5109287b kthwake.hpp
art/share.png ADDED
deadline-arrivals.svg ADDED
index.html CHANGED
@@ -1,19 +1,306 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
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="color-scheme" content="light">
7
+ <meta name="description" content="Explore how a C++17 scheduler turns timestamped events into sliding-window threshold callbacks and wakes on idle expiry.">
8
+ <title>KthWake · Sliding-window threshold scheduler</title>
9
+ <style>
10
+ :root {
11
+ color-scheme: light;
12
+ --paper: #fff3d7; --ink: #171729; --blue: #384cfa; --red: #ef543c;
13
+ --rule: rgb(23 23 41 / 28%);
14
+ --sans: Barlow,"Helvetica Neue",Arial,sans-serif;
15
+ --mono: ui-monospace,SFMono-Regular,Consolas,monospace;
16
+ }
17
+ * { box-sizing: border-box; }
18
+ body { margin: 0; background: var(--paper); color: var(--ink); font: 16px/1.5 var(--sans); }
19
+ main,header,footer { width: min(1120px,calc(100% - 64px)); margin-inline: auto; }
20
+ header,.brand,.topnav,.top,.trace-head,.range-head,.release-links,.buttons,.legend,.legend span { display: flex; align-items: center; }
21
+ header { min-height: 66px; justify-content: space-between; gap: 12px; border-bottom: 2px solid var(--ink); }
22
+ .brand { gap: 7px; font-weight: 780; font-size: 1.36rem; letter-spacing: -.045em; }
23
+ .brand svg { width: 42px; height: 42px; flex: none; }
24
+ .topnav,.release-links,.buttons,.legend { gap: 8px 17px; flex-wrap: wrap; }
25
+ a { color: var(--blue); text-underline-offset: .18em; }
26
+ a:hover { text-decoration-thickness: 2px; }
27
+ .topnav a { color: var(--ink); font-size: .92rem; font-weight: 650; }
28
+ .hero { display: grid; grid-template-columns: 1.18fr .92fr; gap: clamp(20px,5vw,66px); align-items: end; padding: clamp(32px,5vw,65px) 0 30px; }
29
+ .hero .category { margin: 0 0 10px; font: 600 .82rem/1.4 var(--mono); color: var(--blue); }
30
+ h1,h2,h3,p,dl { margin: 0; }
31
+ .hero h1 { font-size: clamp(3rem,6.5vw,5.6rem); line-height: .96; letter-spacing: -.067em; }
32
+ .hero .intro { max-width: 42ch; font-size: clamp(1rem,1.65vw,1.17rem); }
33
+ .grid { display: grid; grid-template-columns: minmax(0,1fr) 270px; gap: 18px; align-items: start; }
34
+ .panel { border: 1px solid var(--ink); border-top: 4px solid var(--ink); }
35
+ .top,.trace-head,.aside,.playbar,.release { padding: 15px 20px; }
36
+ .top,.trace-head,.range-head { justify-content: space-between; gap: 12px; }
37
+ .top,.trace-head { border-bottom: 1px solid var(--rule); }
38
+ h2 { font-size: 1.35rem; letter-spacing: -.035em; line-height: 1.16; }
39
+ .clock,.counter,.label,.legend,.status,output,td,.code,.snippet { font-family: var(--mono); }
40
+ .clock,.counter,.label,.legend { font-size: .77rem; }
41
+ .plot { padding: 5px 10px 0; }
42
+ .state-marker { transform-box: fill-box; transform-origin: center; }
43
+ .plot svg { width: 100%; height: auto; display: block; }
44
+ .legend { padding: 0 18px 12px; }
45
+ .legend span { gap: 6px; }
46
+ .mark { width: 9px; height: 9px; border: 1px solid var(--ink); background: var(--red); border-radius: 50%; }
47
+ .bar { width: 15px; height: 3px; background: var(--blue); }
48
+ .needle { height: 12px; border-left: 2px dashed var(--ink); }
49
+ .readout { padding: 10px 18px; background: rgb(56 76 250 / 7%); border-left: 4px solid var(--blue); }
50
+ input[type=range] { width: 100%; margin: 9px 0 15px; accent-color: var(--blue); cursor: pointer; }
51
+ .range-head output { font-weight: bold; }
52
+ .buttons { gap: 7px; }
53
+ button,input,textarea { font: inherit; }
54
+ button,.download { min-height: 40px; padding: 8px 12px; background: var(--paper); color: var(--ink); border: 1px solid var(--ink); border-radius: 2px; font-size: .91rem; font-weight: 650; cursor: pointer; }
55
+ button.primary { background: var(--ink); color: var(--paper); }
56
+ button:hover:enabled { color: var(--blue); border-color: var(--blue); }
57
+ button.primary:hover:enabled { background: var(--blue); color: var(--paper); }
58
+ button:disabled { opacity: .52; cursor: default; }
59
+ :is(button,input,textarea,summary,a):focus-visible { outline: 3px solid var(--blue); outline-offset: 3px; }
60
+ .aside { border-top-color: var(--blue); }
61
+ .aside h2 { margin-bottom: 15px; }
62
+ .fields { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
63
+ .field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 13px; }
64
+ .field label { font-size: .85rem; }
65
+ input[type=number],textarea { display: block; width: 100%; min-height: 40px; padding: 7px 9px; border: 1px solid var(--ink); border-radius: 2px; font: .91rem/1.45 var(--mono); color: var(--ink); background: var(--paper); }
66
+ textarea { resize: vertical; }
67
+ .hint,.errors { margin: 9px 0 0; font-size: .83rem; }
68
+ .errors { padding-left: 8px; border-left: 3px solid var(--red); font-weight: 650; }
69
+ .summary { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); border-top: 1px solid var(--rule); }
70
+ .stat { padding: 10px 14px; }
71
+ .stat + .stat { border-left: 1px solid var(--rule); }
72
+ .stat dt { font-size: .79rem; }
73
+ .stat dd { margin: 2px 0 0; font: 600 1.16rem/1.4 var(--mono); }
74
+ .stat .on,.state-up { color: var(--blue); font-weight: bold; }
75
+ .trace,.release { margin-top: 20px; }
76
+ table { width: 100%; border-collapse: collapse; font-size: .87rem; text-align: left; }
77
+ th,td { padding: 7px 18px; border-bottom: 1px solid var(--rule); }
78
+ th { font-weight: 600; }
79
+ .trace-empty,details { padding: 10px 18px; }
80
+ details { border-top: 1px solid var(--rule); font-size: .91rem; }
81
+ summary { cursor: pointer; }
82
+ details p,.release p { margin: 8px 0; max-width: 78ch; }
83
+ .code,.snippet { display: block; white-space: pre-wrap; overflow-wrap: anywhere; margin: 8px 0; padding: 10px 13px; background: rgb(56 76 250 / 6%); border-left: 3px solid var(--blue); font-size: .86rem; }
84
+ .release h3 { margin: 19px 0 0; font-size: 1.1rem; }
85
+ .release-links { margin-block: 8px; font-size: .9rem; }
86
+ footer { margin-top: 24px; padding: 16px 0 26px; border-top: 1px solid var(--ink); font-size: .85rem; }
87
+ .a11y { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip-path: inset(50%); }
88
+ [hidden] { display: none !important; }
89
+ @media(max-width:780px) {
90
+ main,header,footer { width: calc(100% - 30px); }
91
+ header { padding: 8px 0; }
92
+ .topnav { gap: 6px 12px; justify-content: flex-end; }
93
+ .topnav a { font-size: .84rem; }
94
+ .hero,.grid { grid-template-columns: 1fr; }
95
+ .hero { gap: 12px; }
96
+ .top,.trace-head,.aside,.playbar,.release { padding-inline: 12px; }
97
+ .legend { padding-inline: 12px; }
98
+ .stat { padding: 8px; }
99
+ .stat dt { font-size: .73rem; }
100
+ th,td { padding: 6px 10px; }
101
+ }
102
+ </style>
103
+ </head>
104
+ <body>
105
+ <header><div class="brand"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" aria-hidden="true" focusable="false">
106
+ <g transform="rotate(7 128 128)">
107
+ <path d="M55 35H201V52H193C189 81 166 105 141 128C163 150 191 176 193 204H201V222H55V204H63C65 175 93 149 115 128C91 104 67 82 63 52H55Z" fill="#171729"/>
108
+ <path d="M78 53H179C174 75 158 95 128 120C101 98 83 77 78 53Z" fill="#fff3d7"/>
109
+ <path d="M128 137C111 153 91 175 83 197H174C164 171 145 151 128 137Z" fill="#384cfa"/>
110
+ <g fill="#ef543c"><circle cx="113" cy="72" r="10.7"/><circle cx="142" cy="72" r="10.7"/><circle cx="128" cy="94" r="10.7"/></g>
111
+ <path d="M128 142V164" stroke="#fff3d7" stroke-width="6"/><circle cx="128" cy="183" r="7" fill="#fff3d7"/>
112
+ <path d="M55 35H201V41H55ZM55 204H201V211H55Z" fill="#ef543c"/>
113
+ </g>
114
+ </svg>KthWake</div><nav class="topnav" aria-label="Project"><a href="https://github.com/pgg898200-ship-it/chronosieve/tree/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake">Source</a><a href="#release">Use in your scheduler ↓</a></nav></header>
115
+ <main>
116
+ <section class="hero">
117
+ <div><p class="category">Sliding-window threshold scheduler</p><h1>Wake on the third result.</h1></div>
118
+ <p class="intro">Give KthWake an ordered stream of tool completions. It tells your event loop when a rule turns on and when it will turn off if no more results arrive.</p>
119
+ </section>
120
+ <div class="grid">
121
+ <div class="panel">
122
+ <div class="top"><h2>Tool completion timeline</h2><span class="clock">Rule #0</span></div>
123
+ <div class="plot"><svg id="chart" viewBox="0 0 680 172" role="img" aria-labelledby="svg-title svg-description"><title id="svg-title">Arrivals and callback state over time</title><desc id="svg-description"></desc><g id="plot"></g></svg></div>
124
+ <div class="legend"><span><i class="mark"></i>Arrival</span><span><i class="bar"></i>Threshold met</span><span><i class="needle"></i>Clock</span></div>
125
+ <p id="readout" class="readout"></p>
126
+ <div class="playbar">
127
+ <div class="range-head"><label class="label" for="clock">Replay time</label><output id="clock-out" for="clock"></output></div>
128
+ <input id="clock" type="range" min="0" step="1" value="5" max="26">
129
+ <div class="buttons"><button class="primary" type="button" id="next">Next callback →</button><button type="button" id="tick">+1 ms</button><button type="button" id="push">Add arrival now</button></div>
130
+ </div>
131
+ <dl class="summary"><div class="stat"><dt>Window count</dt><dd id="count"></dd></div><div class="stat"><dt>Threshold met</dt><dd id="state"></dd></div><div class="stat"><dt>Clears if idle</dt><dd id="expiry"></dd></div></dl>
132
+ </div>
133
+ <form id="configure" class="panel aside">
134
+ <h2>Edit the rule</h2>
135
+ <div class="fields"><div class="field"><label for="k">Results required</label><input id="k" type="number" min="1" max="256" step="1" value="3" required></div>
136
+ <div class="field"><label for="w">Window (ms)</label><input id="w" type="number" min="1" max="100000" step="1" value="20" required></div></div>
137
+ <div class="field"><label for="arrivals">Completion times (ms)</label><textarea id="arrivals" rows="2" spellcheck="false">0, 0, 5</textarea></div>
138
+ <p class="errors" id="error" role="alert" hidden></p>
139
+ <div class="buttons"><button type="submit">Apply trace</button><button type="button" class="quiet" id="reset">Reset example</button></div>
140
+ <p class="hint">Separate times with commas. Repeat a time for results that finish together.</p>
141
+ </form>
142
+ </div>
143
+ <section class="panel trace"><div class="trace-head"><h2>Callback log</h2><span id="total" class="counter"></span></div>
144
+ <table id="log"><thead><tr><th scope="col">Time (ms)</th><th scope="col">State</th><th scope="col">Trigger</th></tr></thead><tbody></tbody></table><p class="trace-empty" id="empty" hidden>No callbacks through this tick.</p>
145
+ <details><summary>Read callback log as JSONL</summary><pre class="snippet"><code id="jsonl"></code></pre></details>
146
+ <details><summary>Drive the C++ index</summary><p>Pass each timestamp’s arrivals together. Use the next expiry to drive the clock during idle periods. At a shared timestamp, a single step applies expirations and arrivals before reporting changes.</p><code class="code">index.step(t, arrivals, callback);<br>auto deadline = index.next_expiry();</code></details>
147
+ </section>
148
+ <section class="panel release" id="release" aria-labelledby="release-title">
149
+ <h2 id="release-title">Use KthWake in your event loop</h2>
150
+ <p>Put one index after an ordered event stream. Pass the arrival count to <code>step</code>, dispatch the changed rule IDs, and arm one timer for the next idle deadline.</p>
151
+ <div class="release-links"><a class="download" href="https://raw.githubusercontent.com/pgg898200-ship-it/chronosieve/f6df7cdb54362fea22003a814ac83fcc7b179a8f/companions/kthwake/downloads/v0.1.0/kthwake-0.1.0.tar.gz" download>Download source v0.1.0 ↓</a><a href="https://raw.githubusercontent.com/pgg898200-ship-it/chronosieve/f6df7cdb54362fea22003a814ac83fcc7b179a8f/companions/kthwake/downloads/v0.1.0/kthwake.hpp" download>Download kthwake.hpp</a><a href="https://raw.githubusercontent.com/pgg898200-ship-it/chronosieve/f6df7cdb54362fea22003a814ac83fcc7b179a8f/companions/kthwake/downloads/v0.1.0/kthwake-linux-x86_64" download>Linux x86-64 CLI</a><a href="https://raw.githubusercontent.com/pgg898200-ship-it/chronosieve/f6df7cdb54362fea22003a814ac83fcc7b179a8f/companions/kthwake/downloads/v0.1.0/kthwake-0.1.0-cp312-cp312-linux_x86_64.whl" download>CPython 3.12 Linux wheel</a></div>
152
+ <h3>37.1 ms for 330,890 transitions</h3><p>On a held-out Azure trace with 4,096 modeled individual-rate policies, the fastest tested alternative took 75.0 ms. A dedicated heap won the other two Azure timer workloads. <a href="https://github.com/pgg898200-ship-it/chronosieve/blob/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake/EVIDENCE.md">Inspect all results</a>.</p>
153
+ <h3>Run the example</h3><p>In the extracted source directory, run the bundled trace through the native CLI.</p>
154
+ <pre class="snippet"><code>make example</code></pre>
155
+ <div class="release-links"><a href="https://github.com/pgg898200-ship-it/chronosieve/blob/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake/EVIDENCE.md">Benchmark results and limits ↗</a><a href="https://github.com/pgg898200-ship-it/chronosieve/tree/releases/kthwake-0.1.0/companions/kthwake#use-from-python">Python and C++ integration ↗</a><a href="https://raw.githubusercontent.com/pgg898200-ship-it/chronosieve/f6df7cdb54362fea22003a814ac83fcc7b179a8f/companions/kthwake/downloads/v0.1.0/SHA256SUMS">SHA-256 checksums</a><a href="https://github.com/pgg898200-ship-it/chronosieve/blob/7cca93890a5bfa1e120f6aaabda8d1b8d7957b1f/companions/kthwake/REPRODUCE.md">Share an independent result</a></div>
156
+ </section>
157
+ <div class="a11y" id="announcement" role="status" aria-live="polite"></div>
158
+ </main>
159
+ <footer>Interactive JavaScript illustration of the C++ index’s semantics. The explorer uses milliseconds. The native index accepts any consistent integer time unit. At tick t, the window includes arrivals after t − W through t. Runtime measurements belong to the native benchmark.</footer>
160
+ <script>
161
+ 'use strict';
162
+ const byId = id => document.getElementById(id);
163
+ const initial = {k:3, w:20, times:[0,0,5], now:5};
164
+ let config = {...initial, times:[...initial.times]};
165
+ let transitions = [];
166
+ let horizon = 0;
167
+ let previousState = null;
168
+ const MAX_EVENTS = 256, MAX_TICK = 100000;
169
+
170
+ function calculateTrace(times,k,w) {
171
+ const changes = new Map();
172
+ for (const t of times) {
173
+ for(const [tick,field] of [[t,'in'],[t+w,'out']]) {
174
+ if (!changes.has(tick)) changes.set(tick,{in:0,out:0});
175
+ changes.get(tick)[field]++;
176
+ }
177
+ }
178
+ let count = 0;
179
+ const result = [];
180
+ for (const t of [...changes.keys()].sort((a,b)=>a-b)) {
181
+ const batch = changes.get(t), before = count>=k;
182
+ count += batch.in - batch.out;
183
+ if ((count>=k)!==before) result.push({t,on:count>=k,in:batch.in,out:batch.out});
184
+ }
185
+ return result;
186
+ }
187
+ function reindex() {
188
+ transitions = calculateTrace(config.times,config.k,config.w);
189
+ horizon = Math.max(config.w+1,(config.times.at(-1) ?? 0)+config.w+1,config.now);
190
+ byId('clock').max = String(horizon);
191
+ }
192
+ function svg(tag,attrs,content) {
193
+ const el=document.createElementNS('http://www.w3.org/2000/svg',tag);
194
+ for (const [k,v] of Object.entries(attrs)) el.setAttribute(k,String(v));
195
+ if (content!==undefined) el.textContent=String(content);
196
+ byId('plot').append(el);
197
+ return el;
198
+ }
199
+ function draw() {
200
+ byId('plot').replaceChildren();
201
+ const width = Math.max(290,Math.round(byId('chart').getBoundingClientRect().width));
202
+ const right=width-18, left=15, x=t=>left+(right-left)*t/horizon;
203
+ const ink='#384cfa', amber='#ef543c', soft='#171729', line='rgba(23,23,41,.28)';
204
+ byId('chart').setAttribute('viewBox',`0 0 ${width} 172`);
205
+ const label=(tx,ty,s,anchor='start')=>svg('text',{x:tx,y:ty,fill:soft,'font-size':10,'font-family':'monospace','text-anchor':anchor},s);
206
+ for (let i=0;i<=4;i++) {
207
+ const tick=Math.round(i*horizon/4);
208
+ if(i>0 && tick===Math.round((i-1)*horizon/4)) continue;
209
+ svg('line',{x1:x(tick),x2:x(tick),y1:16,y2:145,stroke:line,'stroke-dasharray':'2 4'});
210
+ label(x(tick),161,tick,i===0?'start':i===4?'end':'middle');
211
+ }
212
+ svg('rect',{x:x(Math.max(0,config.now-config.w)),y:9,width:Math.max(0,x(config.now)-x(Math.max(0,config.now-config.w))),height:128,fill:ink,opacity:.055});
213
+ label(left,20,'COMPLETIONS');label(left,88,'STATE');
214
+ svg('line',{x1:left,x2:right,y1:52,y2:52,stroke:line});
215
+ const groups=new Map();
216
+ for(const t of config.times) groups.set(t,(groups.get(t)||0)+1);
217
+ for(const [t,n] of groups) {
218
+ const past=t<=config.now, cx=x(t);
219
+ svg('line',{x1:cx,x2:cx,y1:52,y2:59,stroke:amber,opacity:past?1:.45});
220
+ for(let j=0;j<Math.min(3,n);j++)
221
+ svg('circle',{cx,cy:49-j*7,r:3.4,fill:past?amber:'#fff3d7',stroke:'#171729',opacity:past?1:.65});
222
+ }
223
+ function stepPath(start,end) {
224
+ let on=false;
225
+ for(const c of transitions) if(c.t<=start) on=c.on;
226
+ const y=s=>s?101:131;
227
+ let path=`M${x(start)} ${y(on)}`;
228
+ for(const c of transitions) if(c.t>start && c.t<=end) path+=` H${x(c.t)} V${y(c.on)}`;
229
+ return path+` H${x(end)}`;
230
+ }
231
+ svg('path',{d:stepPath(0,config.now),stroke:ink,'stroke-width':2.6,fill:'none'});
232
+ svg('path',{d:stepPath(config.now,horizon),stroke:ink,'stroke-width':1.6,fill:'none',opacity:.48,'stroke-dasharray':'4 4'});
233
+ const cx=x(config.now);
234
+ svg('line',{x1:cx,x2:cx,y1:4,y2:145,stroke:'#171729','stroke-dasharray':'3 4'});
235
+ svg('path',{d:`M${cx-3.5} 3h7l-3.5 5z`,fill:'#171729'});
236
+ const active = transitions.filter(change => change.t <= config.now).at(-1)?.on;
237
+ return svg('circle', {cx, cy: active ? 101 : 131, r: 4, fill: '#384cfa',
238
+ stroke: '#fff3d7', 'stroke-width': 1.5, class: 'state-marker'});
239
+
240
+ }
241
+ function render() {
242
+ const {times,k,w,now}=config;
243
+ const windowTimes=times.filter(t=>t<=now&&t>now-w), on=windowTimes.length>=k;
244
+ const deadline=on?windowTimes[windowTimes.length-k]+w:null;
245
+ const history=transitions.filter(c=>c.t<=now);
246
+ byId('clock').value=now;
247
+ byId('clock-out').textContent=now+' ms';
248
+ byId('count').textContent=windowTimes.length;
249
+ byId('state').textContent=on?'true':'false';
250
+ byId('state').classList.toggle('on',on);
251
+ byId('expiry').textContent=deadline===null?'—':deadline+' ms';
252
+ const rule = k+' or more results in '+w+' ms';
253
+ byId('readout').textContent=on
254
+ ? 'Rule met · '+rule+'. With no more completions, the callback clears at '+deadline+' ms.'
255
+ : 'Waiting for '+rule+'. '+windowTimes.length+' in the window now.';
256
+ byId('jsonl').textContent=history.map(c=>JSON.stringify({t:c.t,id:0,active:c.on})).join('\n');
257
+ byId('expiry').title='Tick when the threshold clears if no more arrivals occur';
258
+ byId('total').textContent=history.length+' through '+now+' ms';
259
+ byId('next').disabled=!transitions.some(c=>c.t>now);
260
+ byId('tick').disabled=now>=horizon;
261
+ byId('push').disabled=now>MAX_TICK||times.length>=MAX_EVENTS;
262
+ byId('empty').hidden=history.length!==0;
263
+ byId('log').hidden=!history.length;
264
+ const tbody=byId('log').tBodies[0];tbody.replaceChildren();
265
+ for(const c of history.slice().reverse()){
266
+ const tr=tbody.insertRow();
267
+ tr.insertCell().textContent=c.t;
268
+ const state=tr.insertCell();state.textContent=c.on?'true':'false';state.className=c.on?'state-up':'state-down';
269
+ tr.insertCell().textContent=c.in&&c.out?'Arrival + expiry':c.in?'Arrival':'Idle expiry';
270
+ }
271
+ const desc=`At ${now} ms, ${windowTimes.length} arrivals are in the window. The threshold is ${on?'met':'unmet'}. ${history.length} callbacks so far.`;
272
+ byId('svg-description').textContent=desc+' Dotted state segments preview the scheduled input.';
273
+ byId('announcement').textContent=desc;
274
+ const marker = draw();
275
+ // Connect the state change to its location on the time axis.
276
+ if (previousState !== null && previousState !== on && typeof marker.animate === 'function' &&
277
+ window.matchMedia && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
278
+ marker.animate([{ transform: 'scale(2)' }, { transform: 'scale(1)' }], {
279
+ duration: 250, easing: 'ease-out'
280
+ });
281
+ }
282
+ previousState = on;
283
+ }
284
+ function setNow(t){config.now=t;render();}
285
+ function fields(){byId('k').value=config.k;byId('w').value=config.w;byId('arrivals').value=config.times.join(', ');}
286
+ function showError(message=''){byId('error').textContent=message;byId('error').hidden=!message;}
287
+ byId('configure').addEventListener('submit',e=>{
288
+ e.preventDefault();
289
+ const raw=byId('arrivals').value.trim();
290
+ const items=raw===''?[]:raw.split(/[\s,]+/);
291
+ if(items.length>MAX_EVENTS || items.some(t=>!/^\d+$/.test(t)||!Number.isSafeInteger(Number(t))||Number(t)>MAX_TICK)){
292
+ showError('Enter up to 256 whole-number completion times from 0 to 100000 ms.');return;
293
+ }
294
+ showError();
295
+ config={k:Number(byId('k').value), w:Number(byId('w').value),times:items.map(Number).sort((a,b)=>a-b),now:0};
296
+ fields();reindex();render();
297
+ });
298
+ byId('clock').addEventListener('input',e=>setNow(Number(e.target.value)));
299
+ byId('tick').addEventListener('click',()=>setNow(Math.min(horizon,config.now+1)));
300
+ byId('next').addEventListener('click',()=>{const next=transitions.find(c=>c.t>config.now);if(next)setNow(next.t);});
301
+ byId('push').addEventListener('click',()=>{config.times.push(config.now);config.times.sort((a,b)=>a-b);fields();showError();reindex();render();});
302
+ byId('reset').addEventListener('click',()=>{config={...initial,times:[...initial.times]};fields();showError();reindex();render();});
303
+ window.addEventListener('resize',draw);
304
+ reindex();render();
305
+ </script>
306
+ </body></html>
kthwake-0.1.0.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcf3ac61cdd7638c509de61b7e33da43aaef0d6e0ea38cc462021ffce7c8b1bf
3
+ size 114245
kthwake.hpp ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef KTHWAKE_HPP
2
+ #define KTHWAKE_HPP
3
+
4
+ #include <algorithm>
5
+ #include <cstddef>
6
+ #include <cstdint>
7
+ #include <deque>
8
+ #include <exception>
9
+ #include <limits>
10
+ #include <optional>
11
+ #include <stdexcept>
12
+ #include <vector>
13
+ #include <unordered_set>
14
+
15
+ namespace kthwake {
16
+
17
+ struct Guard {
18
+ std::uint32_t k;
19
+ std::uint64_t window;
20
+ };
21
+
22
+ // A single ordered event stream. Guard IDs are zero-based input indices.
23
+ // Calls and callbacks run synchronously on one thread. A callback must not
24
+ // reenter this index. Equal timestamps across calls are allowed.
25
+ class Index {
26
+ public:
27
+ explicit Index(const std::vector<Guard>& guards) {
28
+ if (!guards.empty() &&
29
+ guards.size() - 1 > std::numeric_limits<std::uint32_t>::max()) {
30
+ throw std::length_error("guard ID exceeds uint32_t");
31
+ }
32
+ std::vector<Entry> entries;
33
+ entries.reserve(guards.size());
34
+ for (std::size_t i = 0; i < guards.size(); ++i) {
35
+ const auto& g = guards[i];
36
+ if (!g.k || !g.window) {
37
+ throw std::invalid_argument("k and window must both be positive");
38
+ }
39
+ entries.push_back({g.window, static_cast<std::uint32_t>(i), g.k});
40
+ }
41
+ std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) {
42
+ if (a.k != b.k) return a.k < b.k;
43
+ if (a.window != b.window) return a.window < b.window;
44
+ return a.id < b.id;
45
+ });
46
+ for (std::size_t begin = 0; begin < entries.size();) {
47
+ const auto k = entries[begin].k;
48
+ auto end = begin + 1;
49
+ while (end < entries.size() && entries[end].k == k) ++end;
50
+ groups_.push_back({begin, end, end, k, 0, 0});
51
+ begin = end;
52
+ }
53
+ if (groups_.empty()) return;
54
+ max_k_ = groups_.back().k;
55
+ // Sorting by rank is sufficient when only a few ranks are present.
56
+ // Look for a significantly smaller window partition before building
57
+ // the alternative layout. Stop counting widths as soon as it loses.
58
+ if (groups_.size() >= 4) {
59
+ std::unordered_set<std::uint64_t> widths;
60
+ const auto limit = groups_.size() / 4;
61
+ for (const auto& e : entries) {
62
+ widths.insert(e.window);
63
+ if (widths.size() > limit) break;
64
+ }
65
+ if (widths.size() <= limit) {
66
+ std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) {
67
+ if (a.window != b.window) return a.window < b.window;
68
+ if (a.k != b.k) return a.k < b.k;
69
+ return a.id < b.id;
70
+ });
71
+ for (std::size_t begin = 0; begin < entries.size();) {
72
+ const auto w = entries[begin].window;
73
+ auto end = begin + 1;
74
+ while (end < entries.size() && entries[end].window == w) ++end;
75
+ windows_.push_back({begin, end, begin, w, 0});
76
+ begin = end;
77
+ }
78
+ std::vector<Group>().swap(groups_);
79
+ flatten(entries);
80
+ return;
81
+ }
82
+ }
83
+ if (groups_.size() >= 32) timers_.resize(groups_.size());
84
+ if (max_k_ <= 1024) {
85
+ std::size_t capacity = 1;
86
+ while (capacity < max_k_) capacity *= 2;
87
+ ring_.resize(capacity);
88
+ }
89
+ flatten(entries);
90
+ }
91
+
92
+ // Evaluate the post-batch snapshot. Each occurrence is stamped 'now'.
93
+ // An occurrence at s counts iff now-s < window. Emit (ID, new_state)
94
+ // exactly once per changed guard. The initial snapshot is all false.
95
+ // If a callback throws, the new snapshot is committed, subsequent
96
+ // callbacks are skipped, and the original exception is rethrown.
97
+ template<class Emit>
98
+ void step(std::uint64_t now, std::uint64_t arrivals, Emit&& emit) {
99
+ if (now < clock_) throw std::invalid_argument("time moved backward");
100
+ if (!arrivals && (now == clock_ || (!dirty_ && (!expiry_ || now < *expiry_)))) {
101
+ clock_ = now;
102
+ return;
103
+ }
104
+ if (arrivals && max_k_) {
105
+ if (ring_.empty()) append(now, arrivals);
106
+ else append_small(now, arrivals);
107
+ }
108
+ clock_ = now;
109
+ expiry_.reset();
110
+ dirty_ = !deadlines_requested_ && arrivals != 0;
111
+ std::exception_ptr failure;
112
+ auto notify = [&](std::size_t first, std::size_t last, bool active) {
113
+ if (failure) return;
114
+ try {
115
+ for (auto i = first; i < last; ++i) emit(ids_[i], active);
116
+ } catch (...) {
117
+ failure = std::current_exception();
118
+ }
119
+ };
120
+
121
+ const bool scheduled = deadlines_requested_ && !timers_.empty();
122
+ if (scheduled && !arrivals) {
123
+ expire_ranks(now, notify);
124
+ } else if (!windows_.empty()) {
125
+ step_windows(now, notify);
126
+ } else if (!arrivals) {
127
+ step_ranks<true>(now, [](Group& g) { return g.stamp; }, notify);
128
+ } else if (!ring_.empty()) {
129
+ const auto mask = ring_.size() - 1;
130
+ if (ring_explicit_ == retained_) {
131
+ auto stamp = [&](Group& g) { return ring_[(ring_head_ - g.k) & mask]; };
132
+ if (dirty_ || scheduled) step_ranks<false>(now, stamp, notify);
133
+ else step_ranks<true>(now, stamp, notify);
134
+ } else {
135
+ auto stamp = [&](Group& g) {
136
+ return g.k <= ring_explicit_ ? ring_[(ring_head_ - g.k) & mask] : bulk_stamp_;
137
+ };
138
+ if (dirty_ || scheduled) step_ranks<false>(now, stamp, notify);
139
+ else step_ranks<true>(now, stamp, notify);
140
+ }
141
+ } else {
142
+ auto stamp = [&](Group& g) { return kth_stamp(g); };
143
+ if (dirty_ || scheduled) step_ranks<false>(now, stamp, notify);
144
+ else step_ranks<true>(now, stamp, notify);
145
+ }
146
+ if (scheduled && arrivals) rebuild_timers();
147
+ if (failure) std::rethrow_exception(failure);
148
+ }
149
+
150
+ // Assuming no more arrivals, first representable future tick at which a
151
+ // guard becomes false. A deadline equal to UINT64_MAX is representable.
152
+ [[nodiscard]] std::optional<std::uint64_t> next_expiry() const noexcept {
153
+ deadlines_requested_ = true;
154
+ if (!timers_.empty() && !timers_ready_) {
155
+ rebuild_timers();
156
+ dirty_ = false;
157
+ } else if (dirty_) {
158
+ if (windows_.empty()) {
159
+ for (const auto& g : groups_) {
160
+ if (g.k > retained_) break;
161
+ if (g.split < g.end) consider(g.stamp, keys_[g.split]);
162
+ }
163
+ } else {
164
+ for (const auto& w : windows_) consider_window(w);
165
+ }
166
+ dirty_ = false;
167
+ }
168
+ return expiry_;
169
+ }
170
+
171
+ private:
172
+ struct Entry {
173
+ std::uint64_t window;
174
+ std::uint32_t id;
175
+ std::uint32_t k;
176
+ };
177
+ struct Group {
178
+ std::size_t begin, end, split;
179
+ std::uint32_t k;
180
+ std::uint64_t run_serial, stamp;
181
+ };
182
+ struct WindowGroup {
183
+ std::size_t begin, end, split;
184
+ std::uint64_t window, left_serial;
185
+ };
186
+ struct Run {
187
+ std::uint64_t stamp;
188
+ std::uint64_t end; // cumulative occurrence count at end of run, modulo 2^64
189
+ };
190
+
191
+ void flatten(const std::vector<Entry>& entries) {
192
+ keys_.reserve(entries.size());
193
+ ids_.reserve(entries.size());
194
+ for (const auto& e : entries) {
195
+ keys_.push_back(windows_.empty() ? e.window : e.k);
196
+ ids_.push_back(e.id);
197
+ }
198
+ }
199
+
200
+ struct Timer {
201
+ std::uint64_t due;
202
+ std::size_t group;
203
+ };
204
+ // One deadline per rank. The heap's root can only move forward on
205
+ // idle ticks, so replacing it needs a single downward sift. Rebuild
206
+ // bottom-up on arrivals, which can change every supporting timestamp.
207
+ void sift_timer(std::size_t i, Timer item) const noexcept {
208
+ auto child = i * 2 + 1;
209
+ while (child < timer_count_) {
210
+ if (child + 1 < timer_count_ && timers_[child + 1].due < timers_[child].due) ++child;
211
+ if (item.due <= timers_[child].due) break;
212
+ timers_[i] = timers_[child];
213
+ i = child;
214
+ child = i * 2 + 1;
215
+ }
216
+ timers_[i] = item;
217
+ }
218
+ bool rank_deadline(const Group& g, std::uint64_t& due) const noexcept {
219
+ if (g.split == g.end) return false;
220
+ const auto w = keys_[g.split];
221
+ if (w > std::numeric_limits<std::uint64_t>::max() - g.stamp) return false;
222
+ due = g.stamp + w;
223
+ return true;
224
+ }
225
+ void refresh_minimum() const noexcept {
226
+ if (timer_count_) expiry_ = timers_[0].due;
227
+ else expiry_.reset();
228
+ }
229
+ void rebuild_timers() const noexcept {
230
+ timer_count_ = 0;
231
+ for (std::size_t i = 0; i < groups_.size(); ++i) {
232
+ const auto& g = groups_[i];
233
+ if (g.k > retained_) break;
234
+ std::uint64_t due;
235
+ if (rank_deadline(g, due)) timers_[timer_count_++] = {due, i};
236
+ }
237
+ for (auto i = timer_count_ / 2; i > 0; --i) sift_timer(i - 1, timers_[i - 1]);
238
+ timers_ready_ = true;
239
+ refresh_minimum();
240
+ }
241
+ template<class Emit>
242
+ void expire_ranks(std::uint64_t now, Emit& emit) {
243
+ while (timer_count_ && timers_[0].due <= now) {
244
+ auto timer = timers_[0];
245
+ auto& g = groups_[timer.group];
246
+ adjust(g, now - g.stamp, false, emit);
247
+ if (rank_deadline(g, timer.due)) sift_timer(0, timer);
248
+ else if (--timer_count_) sift_timer(0, timers_[timer_count_]);
249
+ }
250
+ refresh_minimum();
251
+ }
252
+
253
+ void consider(std::uint64_t stamp, std::uint64_t window) const noexcept {
254
+ if (window <= std::numeric_limits<std::uint64_t>::max() - stamp) {
255
+ const auto due = stamp + window;
256
+ if (!expiry_ || due < *expiry_) expiry_ = due;
257
+ }
258
+ }
259
+
260
+ // The active set is a prefix for window groups and a suffix for rank
261
+ // groups. Sparse crossings walk adjacent keys. A distant crossing uses
262
+ // binary search, followed by one contiguous callback pass.
263
+ template<class Partition, class Emit>
264
+ void adjust(Partition& g, std::uint64_t threshold, bool prefix, Emit& emit) {
265
+ auto cut = g.split;
266
+ if (cut < g.end && keys_[cut] <= threshold) {
267
+ if (g.end - cut > 8 && keys_[cut + 8] <= threshold) {
268
+ auto end = std::upper_bound(keys_.begin() + cut + 9, keys_.begin() + g.end,
269
+ threshold);
270
+ cut = static_cast<std::size_t>(end - keys_.begin());
271
+ } else {
272
+ do { ++cut; } while (cut < g.end && keys_[cut] <= threshold);
273
+ }
274
+ emit(g.split, cut, prefix);
275
+ } else if (cut > g.begin && keys_[cut - 1] > threshold) {
276
+ if (cut - g.begin > 8 && keys_[cut - 9] > threshold) {
277
+ auto end = std::upper_bound(keys_.begin() + g.begin, keys_.begin() + cut - 9,
278
+ threshold);
279
+ cut = static_cast<std::size_t>(end - keys_.begin());
280
+ } else {
281
+ do { --cut; } while (cut > g.begin && keys_[cut - 1] > threshold);
282
+ }
283
+ emit(cut, g.split, !prefix);
284
+ }
285
+ g.split = cut;
286
+ }
287
+
288
+ template<bool Deadlines, class Stamp, class Emit>
289
+ void step_ranks(std::uint64_t now, Stamp stamp, Emit& emit) {
290
+ for (auto& g : groups_) {
291
+ if (g.k > retained_) break;
292
+ g.stamp = stamp(g);
293
+ const auto age = now - g.stamp;
294
+ adjust(g, age, false, emit);
295
+ if constexpr (Deadlines) {
296
+ if (g.split < g.end) consider(g.stamp, keys_[g.split]);
297
+ }
298
+ }
299
+ }
300
+
301
+ template<class Emit>
302
+ void step_windows(std::uint64_t now, Emit& emit) {
303
+ for (auto& w : windows_) {
304
+ // A window's first live run only advances. Check its cursor and
305
+ // neighbor first, then binary-search across large time jumps.
306
+ auto offset = w.left_serial - first_serial_;
307
+ std::size_t left = offset <= history_.size() ? static_cast<std::size_t>(offset) : 0;
308
+ if (left < history_.size() && now - history_[left].stamp >= w.window) {
309
+ ++left;
310
+ if (left < history_.size() && now - history_[left].stamp >= w.window) {
311
+ auto hi = history_.size();
312
+ ++left;
313
+ while (left < hi) {
314
+ auto mid = left + (hi - left) / 2;
315
+ if (now - history_[mid].stamp >= w.window) left = mid + 1;
316
+ else hi = mid;
317
+ }
318
+ }
319
+ }
320
+ w.left_serial = first_serial_ + left;
321
+ auto count = left == 0 ? retained_ : tail_ - history_[left - 1].end;
322
+ adjust(w, count, true, emit);
323
+ if (!dirty_) consider_window(w);
324
+ }
325
+ }
326
+
327
+ void consider_window(const WindowGroup& w) const noexcept {
328
+ if (w.split == w.begin) return;
329
+ // The largest active rank has the oldest supporting occurrence.
330
+ // Its expiry is exactly the first falling edge for this window.
331
+ const auto k = static_cast<std::uint32_t>(keys_[w.split - 1]);
332
+ const auto left = static_cast<std::size_t>(w.left_serial - first_serial_);
333
+ consider(history_[rank_position(k, left)].stamp, w.window);
334
+ }
335
+
336
+ void append_small(std::uint64_t now, std::uint64_t n) {
337
+ // A batch covering every requested rank is a constant-time reset.
338
+ if (n >= max_k_) {
339
+ retained_ = max_k_;
340
+ ring_explicit_ = 0;
341
+ ring_head_ = 0;
342
+ bulk_stamp_ = now;
343
+ return;
344
+ }
345
+ // Expand at most 64 timestamps per call. An interior batch larger
346
+ // than that switches once to compressed history, with at most 1024
347
+ // previous timestamps to import, independent of input multiplicity.
348
+ if (n > 64) {
349
+ auto mask = ring_.size() - 1;
350
+ std::deque<Run> imported;
351
+ std::uint64_t end = 0;
352
+ auto add = [&](std::uint64_t stamp, std::uint64_t count) {
353
+ end += count;
354
+ if (!imported.empty() && imported.back().stamp == stamp) imported.back().end = end;
355
+ else imported.push_back({stamp, end});
356
+ };
357
+ if (retained_ > ring_explicit_) add(bulk_stamp_, retained_ - ring_explicit_);
358
+ for (auto k = ring_explicit_; k > 0; --k) {
359
+ add(ring_[(ring_head_ - k) & mask], 1);
360
+ }
361
+ history_.swap(imported);
362
+ tail_ = end;
363
+ std::vector<std::uint64_t>().swap(ring_);
364
+ append(now, n);
365
+ return;
366
+ }
367
+ auto count = static_cast<std::size_t>(n);
368
+ auto first = std::min(count, ring_.size() - ring_head_);
369
+ std::fill_n(ring_.begin() + ring_head_, first, now);
370
+ std::fill_n(ring_.begin(), count - first, now);
371
+ ring_head_ = (ring_head_ + count) & (ring_.size() - 1);
372
+ ring_explicit_ = std::min<std::uint64_t>(max_k_, ring_explicit_ + n);
373
+ retained_ = std::min<std::uint64_t>(max_k_, retained_ + n);
374
+ }
375
+
376
+ void append(std::uint64_t now, std::uint64_t arrivals) {
377
+ // Only the most recent max_k occurrences can affect any guard.
378
+ // A whole batch adds at most one run, even for UINT64_MAX arrivals.
379
+ const auto n = std::min<std::uint64_t>(arrivals, max_k_);
380
+ const auto next_end = tail_ + n;
381
+ if (history_.empty() || history_.back().stamp != now) {
382
+ history_.push_back({now, next_end});
383
+ } else {
384
+ history_.back().end = next_end;
385
+ }
386
+ tail_ = next_end;
387
+ retained_ = std::min<std::uint64_t>(max_k_, retained_ + n);
388
+ // Oldest retained endpoint can lag by at most 2*max_k before pruning.
389
+ // Modular subtraction therefore gives its exact bounded age on wrap.
390
+ while (tail_ - history_.front().end >= max_k_) {
391
+ history_.pop_front();
392
+ ++first_serial_;
393
+ }
394
+ }
395
+
396
+ std::uint64_t kth_stamp(Group& group) const {
397
+ const auto size = history_.size();
398
+ std::size_t pos;
399
+ if (size == retained_) {
400
+ // All retained occurrences occupy different timestamp runs.
401
+ pos = size - group.k;
402
+ } else {
403
+ // A rank's run can only move forward. Its old position (or the
404
+ // oldest retained run after eviction) usually needs zero or one
405
+ // adjustment. For a larger jump find the first run with fewer
406
+ // than k newer occurrences by binary search.
407
+ const auto offset = group.run_serial - first_serial_;
408
+ pos = offset < size ? static_cast<std::size_t>(offset) : 0;
409
+ pos = rank_position(group.k, pos);
410
+ }
411
+ group.run_serial = first_serial_ + pos;
412
+ return history_[pos].stamp;
413
+ }
414
+
415
+ std::size_t rank_position(std::uint32_t k, std::size_t pos) const noexcept {
416
+ if (tail_ - history_[pos].end < k) return pos;
417
+ ++pos;
418
+ if (tail_ - history_[pos].end < k) return pos;
419
+ auto hi = history_.size() - 1;
420
+ ++pos;
421
+ while (pos < hi) {
422
+ const auto mid = pos + (hi - pos) / 2;
423
+ if (tail_ - history_[mid].end >= k) pos = mid + 1;
424
+ else hi = mid;
425
+ }
426
+ return pos;
427
+ }
428
+
429
+ std::vector<WindowGroup> windows_;
430
+ std::vector<std::uint64_t> ring_;
431
+ std::size_t ring_head_ = 0;
432
+ std::uint64_t ring_explicit_ = 0;
433
+ std::uint64_t bulk_stamp_ = 0;
434
+ mutable std::vector<Timer> timers_;
435
+ mutable std::size_t timer_count_ = 0;
436
+ mutable bool timers_ready_ = false;
437
+ mutable bool dirty_ = false;
438
+ mutable bool deadlines_requested_ = false;
439
+ std::vector<std::uint64_t> keys_;
440
+ std::vector<std::uint32_t> ids_;
441
+ std::vector<Group> groups_;
442
+ std::deque<Run> history_;
443
+ std::uint32_t max_k_ = 0;
444
+ std::uint64_t tail_ = 0;
445
+ std::uint64_t retained_ = 0;
446
+ std::uint64_t first_serial_ = 0;
447
+ std::uint64_t clock_ = 0;
448
+ mutable std::optional<std::uint64_t> expiry_;
449
+ };
450
+
451
+ } // namespace kthwake
452
+
453
+ #endif // KTHWAKE_HPP