Skip to content

sminos 1.6.1: the canonical encoder writes strings in C, byte for byte as before - #328

Merged
SSFSKIM merged 2 commits into
mainfrom
codes-fast
Oct 21, 2026
Merged

SSFSKIM merged 2 commits into
mainfrom
codes-fast

Conversation

@SSFSKIM

@SSFSKIM SSFSKIM commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

The uplink's main thread verifies the code of every event the hub sends, and that code covers the event's RFC 8785 text, which sminos_codes.string wrote one character at a time in Python. The desk open-fast band re-run (#327) found an open made right after the hub stream resumed waiting behind that check: 10 of the 14 py-spy dumps of the wait were inside it. This makes the encoder fast and keeps its output byte for byte.

The change (sminos_codes.py)

  • string() quotes with the json module's own function (json.encoder.encode_basestring, ensure_ascii off; C in every CPython). It escapes exactly what JSON.stringify does: ", \, the five short escapes, and every other control as \u00xx in lower-case hex. Every other character, U+007F, U+2028/2029 and astral characters included, is written as itself. The lone-surrogate refusal is unchanged, but skipped for an ASCII string, which cannot hold a surrogate.

  • canonical():

    • A str is tested first.
    • An object whose keys are all exact str and ASCII is sorted by the keys themselves, which is their UTF-16 order, without encoding each one. Objects with other keys keep the UTF-16 sort, with surrogates refused before the sort. The "exact str" condition is the second commit: the review showed that a str subclass with its own __lt__ would otherwise be sorted by that method.
  • number(): an int whose magnitude is at most 2^53 is written as its own digits, which is what the float path produced for it. Floats, bools and larger ints take the same path as before.

  • The joins stay generators. A list comprehension was tried and measured: Python 3.12+ inlines it (PEP 709), which doubled the nesting depth at which canonical() raises RecursionError (498 → 996 on 3.12/3.14, 331 → 497 on 3.10). With generators, the depth for string leaves under the C quoting is identical to before on 3.10, 3.12 and 3.14. A comment at the join records this.

    The review found it can still move by a level at the edge: an ASCII key no longer spends the frames string() did, and the pure-Python quoting fallback spends one more. That is left as is. The boundary already moves with the caller's own stack depth, and the only difference at it is whether a ~330–500-deep event's code gets checked.

Frame handling is not touched.

Before / after, CPU-s per MiB of events as the hub sends them

Measured with sminos/tests/bench_codes.py (new; run against any copy of the scripts) on the MacBook (M1 Max, Python 3.12.3). Each figure is the median of 3 rounds, each round the best of 7.

backlog measured before (origin/main) after factor
a4: 6 MiB, 96 say events of 64 KiB ASCII (bench_open's Uploader, the band's A4 pair) the code check (failure) 0.0457 0.0038 12.0×
canonical() alone 0.0447 0.0036
HubLog.take, frames of 8 events 0.0563 0.0137 4.1×
mixed: 6 MiB, 4,315 events of a busy log (11 writers incl. hub/, log-normal texts, 30% Korean, Markdown, controls, emoji, U+2028) the code check 0.0597 0.0135 4.4×
canonical() alone 0.0558 0.0093
HubLog.take 0.1979 0.1438 1.4×
reference json.dumps of the same events 0.0029 (a4), 0.0040 (mixed)

On a4, canonical() now costs about what json.dumps costs on the same events. What is left of take is the append (append_verbatim): it dumps each event again, then re-reads and parses the file's last line.

What share of the measured wait this removes

At load 150 the open after the resume took 4.36 s, and py-spy put 10 of 14 dumps of the wait in the check and 12 of 14 in take.

  • Read from the samples alone: the check's CPU falls by 92%, and take's by 76%. Both readings remove about 65% of the wait: 10/14 × 92%, or 12/14 × 76%.
  • Modelled: the open goes 1 s after the resume, queued behind what remains of the backlog's take; its own work is the unloaded 0.035 s. Calibrated on the before figures (4.36 s at 150, 7.24 s at 280), the main thread's share is 0.070 at 150 and 0.045 at 280, both counted in MacBook-CPU terms. The model's non-take part at 150, 0.50 s, matches the 2 of 14 dumps outside take. After the fix the 6 MiB backlog drains in 1.18 s at 150, so the open would take about 0.68 s (84% of the wait removed), under the 1 s bound. At 280 it drains in 1.82 s, and the open would take about 1.59 s (78% removed), still over the bound; about half of that is the open's own work at that share.
  • Not re-run: this is not measured on the band; no band host was raised for this change.

Equality evidence

Kept in the suite. codes_parity.py now also holds the encoder to its definition, written out beside it in the test: a per-character JSON.stringify writer, keys sorted by UTF-16 code units, and an integer written as the double it is. It checks:

  • every Unicode scalar value alone (1,112,064)
  • every scalar value in runs of 61 beside its neighbours
  • every surrogate code point alone and amid ASCII, Latin-1, Hangul and astral text, refused
  • 30,000 random strings drawn from controls, escapes, U+007F, U+2028/2029, BMP and astral characters
  • 3,000 random strings with a lone surrogate, refused
  • 10,000 random nested values with ASCII keys and with any keys
  • 500 shuffles of keys whose UTF-16 and code-point orders differ
  • 5,214 integers around 2^53, 10^21, past the largest double, and of every bit length to 64
  • an object whose keys are a str subclass with an order of its own (fails on the first commit, passes on origin/main and on the head)

It runs in about 2 s and passes on Python 3.10.20, 3.11, 3.12, 3.13 and 3.14, and with the json module's pure-Python quoting in place of the C one.

One-off, old function against new, at volume (origin/main's module loaded beside the head's):

ok   string: every scalar value alone (U+0000..U+10FFFF less surrogates)      1112064 values, 0 differ (0.9 s)
ok   string: every scalar value between ASCII, Latin-1, astral and LF         1112064 values, 0 differ (1.7 s)
ok   string: one string of all 1,112,064 scalar values                              1 values, 0 differ (0.2 s)
ok   string: every scalar value in runs of 97                                   11486 values, 0 differ (0.4 s)
ok   string: every 3-sequence of 31 named characters (controls, escapes, 7F, 2028/9, astral, ...)     29791 values, 0 differ (0.0 s)
ok   string: every surrogate code point alone (refused)                          2048 values, 0 differ (0.0 s)
ok   string: every surrogate in five contexts, a 70,000-character one too (refused)     10240 values, 0 differ (1.5 s)
ok   canonical: every surrogate in a key (refused)                               2048 values, 0 differ (0.0 s)
ok   canonical: every surrogate nested in a value (refused)                      2048 values, 0 differ (0.0 s)
ok   string: random strings from ten character classes                        1000000 values, 0 differ (12.6 s)
ok   string: random strings up to 8,192 characters                              10000 values, 0 differ (12.2 s)
ok   canonical: random values (objects of ASCII keys and of any keys)          200000 values, 0 differ (33.7 s)
ok   canonical: 16 keys where UTF-16 and code point order differ, shuffled      20000 values, 0 differ (1.5 s)
ok   number: integers at the boundaries and of every bit length to 90           90021 values, 0 differ (0.2 s)
ok   number: doubles of random bit patterns, and named ones                    202009 values, 0 differ (1.3 s)
ok   covered bytes and code of the bench's 12 MiB of events                      4411 values, 0 differ (2.5 s)
ok   the hub's canonicalize (MAWS canonical.ts under node) = new               366267 values, 0 differ (7.4 s)
all equal

The last line runs the hub's own canonicalize (MAWS apps/desk-hub/src/protocol/canonical.ts at origin/master, under node 22) on a corpus of 366,267 values, compared with the new encoder.

Negative controls. The same evidence catches each of two mutants:

  • Sorting every object by code point: 20,000 of the shuffled-key objects differ, 7,422 of the hub corpus, and every surrogate in a key goes unrefused.
  • Escaping U+2028: one scalar value differs, 2,472 of the 4,411 bench events, and 29,450 of the hub corpus.

The extended codes_parity.py passes on origin/main's module and fails on both mutants (7 and 9 FAIL lines, the DX1 vectors among them).

Review

doperpowers:reviewer-low was asked to look at byte-equality of the canonical text. It returned incorrect on the first commit, for two findings:

  • str subclass keys sorted by their own __lt__: fixed in the second commit, with a test.
  • The RecursionError boundary moving by a level at the edge: left as is; see the joins bullet above.

It found no mismatch for wire-decoded values. It reran the parity checks on Python 3.10–3.14 with both quoting implementations, and the volume run including the hub's 366,267 comparisons.

Should a subscribe be taken ahead of queued events?

Not now.

  • The band's backlog shape: the fix leaves the 6 MiB backlog 0.083 CPU-s of take, which drains about 0.18 s into the open's wait at 150. A subscribe taken ahead would save only that. At 280 it would save about 0.82 s, but the remaining 0.77 s is the open's own work at a 0.045 share. That is the same CPU starvation behind A2 and A6 at 280, and reordering does not fix it.
  • Many small events (what a long offline spell sends at the next hello): take is still 0.1438 CPU-s per MiB, about 200 µs an event. The check is now 9% of that; the rest is the append's per-event file work (three opens, two flocks, a mkdir and a tail read). Unloaded, 1,000 such events cost about 0.20 s. At the band's 150 share, 1 MiB of them would hold an open for about 2.1 s.
  • If that case matters, batching the append per writer per frame attacks the cost directly and keeps the log-before-subscribe order. Reordering is the step after that, if batching is not enough.

Sminos-Session: smns-erb-71#b4948247 (doperpowers on macbook)

…e as before

The uplink verifies the code of every event the hub sends on its main
thread, and the code's RFC 8785 text was written one character at a time in
Python: 0.046 CPU-s per MiB of the band's backlog on the MacBook, against
0.003 for json.dumps. The band re-run (#327) found a desk open made right
after the hub stream resumed waiting on that check in 10 of 14 py-spy dumps.

- string(): the json module's own quoting (json.encoder.encode_basestring,
  ensure_ascii off), which escapes exactly what JSON.stringify does; the
  lone-surrogate scan is skipped for an ASCII string, which cannot hold one.
- canonical(): a str is tested first; an object whose keys are all ASCII is
  sorted by its keys themselves (their UTF-16 order) without encoding them.
- number(): an integer no larger in magnitude than 2^53 is its own digits.
- The joins stay generators: a list comprehension, inlined since Python
  3.12, would double the nesting depth at which canonical() refuses.

The code check falls from 0.046 to 0.0038 CPU-s per MiB on the band's
64 KiB-event backlog and from 0.060 to 0.0135 on a mixed one; HubLog.take
from 0.056 to 0.0137 and from 0.198 to 0.144.

codes_parity.py now also holds the encoder to its definition, written out
beside it: every Unicode scalar value alone and in runs, every surrogate
refused, random strings and values, keys whose UTF-16 and code point orders
differ, integers about 2^53. bench_codes.py measures the check and
HubLog.take per MiB against any copy of the scripts.

Sminos-Session: smns-erb-71#b4948247 (doperpowers on macbook)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-21T11:10:01.433246Z 1db4ff5 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

The review of the fast canonical encoder found that the all-ASCII-keys path
sorted with the keys' own comparison, which a str subclass may override; the
old encoder sorted every key by its UTF-16 code units. That path now takes
exact str keys only, and codes_parity.py holds an object of case-folding
keys to the definition. The test's special characters are written as
escapes again (an editor had turned U+2028, U+FEFF, U+FFFF and U+E000 into
the characters themselves).

Sminos-Session: smns-erb-71#b4948247 (doperpowers on macbook)
@SSFSKIM
SSFSKIM merged commit 3ccc619 into main Oct 21, 2026
10 checks passed
SSFSKIM added a commit that referenced this pull request Oct 21, 2026
spec: desk open-fast, A4's machine-side cost addressed by #328
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant