Skip to content

perf(store): skip the sweep entirely when there is nothing to sweep - #344

Closed
alisemut0711-dev wants to merge 1 commit into
flop-labs:mainfrom
alisemut0711-dev:perf/clean-text-ascii-table
Closed

alisemut0711-dev wants to merge 1 commit into
flop-labs:mainfrom
alisemut0711-dev:perf/clean-text-ascii-table

Conversation

@alisemut0711-dev

@alisemut0711-dev alisemut0711-dev commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

What

Gate clean_text's per-character sweep behind str.isprintable().

if not text.isprintable():
    text = "".join(" " if unicodedata.category(c) in INVISIBLE_CATEGORIES else c for c in text)
text = text.strip()

The walk itself is untouched. What changes is that it no longer runs for records
that have nothing to sweep, which is the overwhelming majority of them.

Why the gate is sound

Every category in INVISIBLE_CATEGORIES (Cc Cf Cs Co Zl Zp) is non-printable
by definition, so an isprintable() string cannot contain a character the
sweep would take. The converse does not hold — Zs and Cn are non-printable
but not swept — so a string that fails the gate merely pays for the walk it
would have done anyway. There is no input for which output changes.

That soundness is a property of the Unicode database, not of store.py, so it
is pinned by a test rather than a comment: INVISIBLE_CATEGORIES growing to
include a printable category (Zs, say) fails the whole codepoint space at
once instead of silently letting invisibles through.

Verification

  • All 1,114,112 codepoints: zero characters are both swept and printable.
  • Byte-equivalence vs the old implementation: 0 mismatches over every
    codepoint individually, plus 40,000 random strings drawn from ASCII, C0
    controls, Cf, the U+E0000 tag block, surrogates and mixed pools —
    identical output and identical StoreError raises.
  • Full suite: 636 passed (the +1 is the codepoint test below).
  • sz.py --check, ruff check, ruff format --check clean.

Numbers

input before after
ASCII 4050 B 2.1111 ms 0.0260 ms 81x
ASCII 180 B 0.1088 ms 0.0017 ms 66x
clean unicode 300 ch 0.1571 ms 0.0025 ms 64x
ZWSP every 20 ch 0.4598 ms 0.4439 ms unchanged
all-C0 4050 B 1.4919 ms 1.4891 ms unchanged

Dirty input still walks, as it must. The win is that clean input stops paying
for the hazard it does not carry.

Size

core/store.py stays at 935 code lines — same as baseline. sz.py --check
passes without touching sz-baseline.json:

core/store.py              2544    935       583      7.74
core total (code)                 2256
check ok: core code-lines <= baseline (2256)

Test

tests/unit/test_parse_properties.py::test_nothing_the_sweep_takes_can_pass_for_printable
— asserts no codepoint is simultaneously in INVISIBLE_CATEGORIES and
printable. RED confirmed by adding "Zs" to the tuple:

AssertionError: printable but swept: ['0x20']

GREEN on the real tuple, and the existing sweep properties
(test_clean_text_sweeps_trims_and_is_idempotent, the hostile-input HTTP test,
the stateful model) pass unchanged.

Refs #322

@henrybennett123

Copy link
Copy Markdown

Filed #322; flagging a staleness problem here rather than opening anything competing — this is the approach I'd want to see land.

The baseline bump is against numbers that have moved. This sets core/store.py to 845 and core_total to 2132. Current main (169ca89) is at:

              code   cap
core/store.py  933   933
core_total    2240  2240

sz-baseline.json has gone 2069 → 2240 in two days. The checklist above also cites 431/431 tests; main is at 487.

Every core file now sits exactly at its cap — zero headroom anywhere. So the patch needs +4 on both, not the +4-from-841 this bump assumes. Measured against 169ca89 with the change applied:

              code   cap   headroom
core/store.py  937   933         -4
core_total    2244  2240         -4

For what it's worth I re-ran the whole thing on 169ca89: 487 passed, ruff check, ruff format --check and ty check clean, output still byte-identical. The optimisation itself is unaffected by anything that has merged since — nothing has touched clean_text or INVISIBLE_CATEGORIES, so the equivalence result and the timings still stand.

The rebase will not be the last one. This is #254's mechanism exactly: a sz-baseline.json bump is correct only until the next core merge, and at ~160 PRs in two days that is hours, not days. Worth regenerating the baseline as the final step before a maintainer merges rather than carrying a number that ages this fast — otherwise this PR rebases indefinitely against a file it cannot win.

Happy to leave the cap question where it belongs, which is with the maintainers: it is +4 over two ceilings, and #322 has the measurement for judging whether that is the right price.

@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from 2341055 to 82681be Compare August 29, 2026 22:28
@alisemut0711-dev

Copy link
Copy Markdown
Contributor Author

Thank you for the detailed re-basing analysis — you were right on every number, and the branch is now regenerated exactly as you described.

What changed in the latest push:

  • Rebased onto main (169ca89), so the conflict with the interim core merges is gone.
  • sz-baseline.json regenerated against that base with sz.py --update-baseline, with the caps raised +4 on the two numbers you identified: core/store.py 933 → 937, core_total 2240 → 2244 — matching your measured 937/933 and 2244/2240 exactly. Measured on the rebased tree: uv run sz.py --check → check ok: core code-lines <= baseline (2244).
  • Equivalence re-verified against the rebased tree, since clean_text moved: all 1,114,112 single codepoints plus 30,000 random strings weighted toward Cc/Cf/Co/Zl/Zp and the U+E0000 tag block produce byte-identical output on the fast path and the general path — zero mismatches.
  • Tests green on the rebased branch: tests/unit/test_store.py 63 passed, ruff check, ruff format --check, ty check all clean.

On the rebase-churn point: agreed, and this time the baseline bump is the final step — it was generated after the rebase onto 169ca89 rather than carried forward from the old base, so it reflects the tree as it stands. If another core merge lands before review, I'll regenerate again the same way rather than hand-adjust.

@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from 82681be to beb1333 Compare August 30, 2026 06:33
@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from beb1333 to 0180034 Compare August 30, 2026 15:57
@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from 0180034 to f44e589 Compare August 31, 2026 00:41
@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch 2 times, most recently from 751a570 to 2128c89 Compare August 31, 2026 07:29
@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from 2128c89 to f70f6a8 Compare August 31, 2026 09:30
@alisemut0711-dev

Copy link
Copy Markdown
Contributor Author

Updated for compatibility with #158 (keep Brahmic joiners U+200C/U+200D in clean_text).

The ASCII fast path here never touches the joiners (they are non-ASCII, so the isascii() gate keeps them out of the translate table by construction), but the general path swept all Cf characters — which would have silently overridden #158's exemption for non-ASCII text. This PR now carries the same SWEEP_EXEMPT set and applies it in the general path, so the two changes compose instead of conflicting. Equivalence fast-vs-general over ASCII is unchanged (0 mismatches), and a regression test pins the joiner behavior.

Verified: ruff/format/ty clean, 64 store tests + signer + dupe-filter tests pass, full-codepoint sweep check 0 issues.

@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from 45f42a1 to e91a062 Compare September 2, 2026 07:31
@alisemut0711-dev alisemut0711-dev changed the title perf(store): sweep ASCII text with a translate table, fall back per codepoint otherwise perf(store): skip the sweep entirely when there is nothing to sweep Sep 2, 2026
@alisemut0711-dev

Copy link
Copy Markdown
Contributor Author

Rewritten from scratch — the approach in the old body is gone, so reading this from the top is worth it.

What was wrong with it. Two things, and the second is the serious one.

  1. It bumped sz-baseline.json. That file is now protected by CI (protected-files), so the old shape cannot land at all. @henrybennett123's point above about the bump aging out was right, and the resolution turned out to be not bumping.

  2. The last revision carried SWEEP_EXEMPT for fix(store): keep ZWJ and ZWNJ so Brahmic text round-trips and signs #158's Brahmic joiners. fix(store): keep ZWJ and ZWNJ so Brahmic text round-trips and signs #158 never merged, so that exemption is not in main — but main does have a test asserting the opposite:

# tests/http/test_humans.py::test_invisible_characters_cannot_smuggle_instructions
"zero-width joiner": "a\u200db"   ->  assert clean_text(value) == "a b"

Verified against three trees, same input:

pr344 (SWEEP_EXEMPT)   ZWJ -> 'a\u200db'   upstream test: FAIL
main                   ZWJ -> 'a b'        upstream test: PASS
this revision          ZWJ -> 'a b'        upstream test: PASS

The old branch was carrying a security regression on behalf of an unmerged PR. Dropped.

What replaces it. The str.translate table is gone too. It only ever helped ASCII, cost 4 core lines, and needed the isascii() gate to stay correct. str.isprintable() subsumes it: every swept category is non-printable by definition, so the gate is exact, it covers non-ASCII text as well, and it costs zero net core lines — core/store.py stays at 935, no baseline change, protected-files green.

It is also faster than the table was, because the win is skipping the walk rather than speeding it up: 81x on 4050-byte ASCII (2.1111 ms -> 0.0260 ms) vs the ~1.15x the table measured. Dirty input is unchanged, which is correct — it still has to be swept.

Equivalence is re-verified against main after the rebase: 0 mismatches over all 1,114,112 codepoints and 40,000 random strings, 636 passed, all gates clean.

The soundness claim is now a test rather than a docstring assertion — adding "Zs" to INVISIBLE_CATEGORIES fails it immediately (printable but swept: ['0x20']), so the gate cannot rot silently if that tuple grows.

@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown

Open pull requests citing the same issues:

If one already covers this change, review or build on it instead of racing it (CONTRIBUTING.md "Overlapping work").

@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch 7 times, most recently from 46bb7a3 to ade93ee Compare September 3, 2026 09:05
clean_text walked every character of every stored record to look for
invisibles, even though the overwhelming majority of records contain
none. Gate the walk behind str.isprintable(), which answers "is there
anything in here to sweep?" in C over the string's internal kind.

The gate is sound because every category in INVISIBLE_CATEGORIES is
non-printable by definition, so an isprintable() string cannot contain
one. Verified over all 1,114,112 codepoints: zero characters are both
swept and printable. The converse does not hold (Zs and Cn are
non-printable but not swept), so a false gate only costs the walk it
would have done anyway.

Output is unchanged for every input: 0 mismatches against the old
implementation over all codepoints and 40,000 random strings drawn from
C0, Cf, tag-block and surrogate pools.

    ASCII 4050B    2.1111 ms -> 0.0260 ms   81x
    ASCII 180B     0.1088 ms -> 0.0017 ms   66x
    unicode clean  0.1571 ms -> 0.0025 ms   64x
    dirty input    unchanged (walk still runs)

core/store.py stays at 935 code lines, so no baseline change is needed.

Refs flop-labs#322
@alisemut0711-dev
alisemut0711-dev force-pushed the perf/clean-text-ascii-table branch from ade93ee to 2618589 Compare September 4, 2026 04:19

@luch91 luch91 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 2618589. The str.isprintable() fast path is causally limited to inputs that cannot contain the swept Unicode categories; dirty inputs still execute the existing sweep. The added whole-codepoint invariant test pins that property, while the PR reports byte-equivalence over all Unicode codepoints and randomized pools, full tests, Ruff, formatting, and size checks clean. GitHub reports lint/tests/image, OpenAPI, and MCP worker-bundle checks successful. No blocker found.

@sv sv added the nit Minor: wording, cosmetic, test-only, unreachable, or negligible impact label Oct 19, 2026
@sv

sv commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Nit fold: tracked in #1004 instead of holding its own queue slot. The branch and diff stay put — reopen this (or comment on the fold) to have it reviewed standalone.

@sv sv closed this Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

help wanted Extra attention is needed nit Minor: wording, cosmetic, test-only, unreachable, or negligible impact optimization

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants