Skip to content

Blacklist regexes run on RE2 off the event loop, and the email and JWT detectors run in linear time - #307

Merged
zlareb1 merged 25 commits into
mainfrom
sec/linear-write-regexes
Nov 7, 2026
Merged

zlareb1 merged 25 commits into
mainfrom
sec/linear-write-regexes

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Critical Bug Fix (data loss, cross-tenant read, auth bypass)

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

Blacklist regexes run on RE2 on every write, as they already did in the sweep: a pattern RE2 cannot run (a backreference, lookaround, \Z), one that compiles to more than 300 RE2 instructions, or one that would take its scope's regexes past 3,000 together is refused at blacklist.add; the match runs on the blacklist's own threads, off the event loop, and a value too long to check against the regexes that apply (bytes times instructions past 250 million) is refused as BLACKLISTED with an empty pattern_id. Sensitivity detection of emails and JWTs runs in linear time on any value, and a write reads a value past 16 KiB in overlapping windows with a turn for the event loop between them.

Why

Three regexes run on the event loop for every value a writer stores, before the insert:

  • A blacklist.add regex ran on Python's backtracking engine. Its guard was a shape check for nested quantifiers plus timed probes built from the pattern's own literals; a pattern whose exponential part is reached only after characters the probes never contain passes both and then backtracks exponentially on a matching value. A writer adds a namespace pattern, so any writer could block a server for every tenant it serves.
  • The sensitivity email pattern had an unbounded local part, so a long run of local-part characters with no @ was rescanned from every word boundary: quadratic, 41 s for a 200 KB value on the measuring host.
  • The JWT pattern started at every eyJ after a - inside one long run of token characters and rescanned the run each time: quadratic, 2.3 s for 100 KB.

Design

  • blacklist_guard.compile_regex is the one way a regex row becomes a matcher, at add and at cache load: the length cap, a compile through server.core.caller_regex.compile_caller_regex (RE2, the engine code.grep and the ClickHouse sweep use) with . matching a newline as ClickHouse compiles, and a cap of 300 RE2 instructions. RE2 is linear in the value, but its cost per character grows with the program once its DFA cannot cache the states (a counted class such as [ab]{400} cost 1.7 s per MB), so the program is capped; 300 admits any ASCII literal up to the 256-character limit (a non-ASCII character compiles to one instruction per UTF-8 byte, so a long non-ASCII literal belongs in a substring pattern). A scope's regexes (namespace, org or global) together compile to at most 3,000 instructions (REGEX_PROGRAM_PER_SCOPE): summed from the cache at add for a clear 422, and enforced again at cache load, keeping the oldest that fit (active_patterns returns oldest first, ties by pattern id, so every replica keeps the same set; a row RE2 refuses takes no room), since racing adds, a lagging replica or an older build can store more.
  • One request's regex work is bounded: a ContextVar the transports bind at each op (blacklist_guard.begin_request_budget, from _common.begin_request) carries the UTF-8 bytes times RE2 instructions its blacklist checks spent, so a bulk write's entries share one budget; a worker binds none, so its passes, which replay several tenants' rows, check per value. Past REGEX_WORK_BUDGET (250 million, about a second of one matcher thread at the worst measured cost of 4 to 5.5 ns per byte per instruction), find_match first checks the substring patterns, which cost nothing, and returns one that matches; otherwise it refuses the value as a matched pattern is (pattern id empty, the widest scope that holds a regex, a message that says the request's values are too long to check, also under a narrowed token), without searching; the error reference says so. A namespace with a few ordinary patterns (10 to 30 instructions each) checks requests of several megabytes; one whose scopes hold 9,000 instructions checks about 27 KB per request. A bulk entry refused this way answers blacklist_unchecked, told apart from blacklisted: sent in a smaller request it is checked. The search runs on four matcher threads per process (MATCHER_THREADS); one org takes at most half of them at once (MATCHERS_PER_ORG = MATCHER_THREADS // 2, per process, so N replicas give an org 2N), its other searches waiting their turn on the event loop, so a burst from one org leaves threads for the others. A search holds its org's turn and its thread's until the thread is done, even when its request is cancelled (the executor future is shielded and releases on completion), since RE2 cannot be stopped mid-search. A search that waits more than MATCHER_WAIT_S (5 s, a few times the longest search the budget allows) for its turns refuses the write with 503 OVERLOADED, as a ClickHouse pool wait does; the write is never stored unchecked. Each org keeps one semaphore for the process's life (orgs come from verified tokens, so they are few). A value whose own size times the applicable program is past the budget is told to shorten the value, since no smaller request checks it; under a narrowed token the message leaves out the instruction count, which sums other principals' patterns. Once an entry of a key is answered blacklist_unchecked, _bulk_build_rows answers every later entry of that key so too, before its skip gate, so a later restatement, merge or identity duplicate of the key cannot land ahead of the earlier value; a caller that sends a key's unchecked entries again in order leaves it at its last value. A caller that does not send them again keeps the key's earlier value, where before a later entry that fit the budget would have landed; no server-side caller sends them again, since the budget bounds one request's work and a second pass in the same request would double it (memory.set_from_messages lists such facts in refused, memory.import in its results). The Python SDK's coalescer sends the entries answered blacklist_unchecked again, in order, in batches the size of the value bytes the last request checked (_entries_within; only rows the blacklist read count, so a skipped restatement or a pinned or locked key adds no room, and a request that checked nothing leaves the rest to go one at a time; each entry's size is computed once), so a burst of 200 sets of 2 KB under an 80 KB budget takes six bulk requests, not about 160 point sets; one still unchecked at the front of a request is too long even first in one and goes as a memory.set alone, which answers what a set alone does (written, or the 422 that says to shorten it). The server rule keeps a key's entries in order across rounds, so the coalescer keeps no bookkeeping of which entries landed. A window's first sets (sent alone, side by side) start after the identity's last flush, and the window's flush starts after that flush and its own first sets (_after), so a set sent again cannot land after a newer set of its key; a window whose time is up when the next set arrives, before its timer runs, is flushed first. A failed bulk request fails every set of its flush still waiting with that error, and nothing more of the flush goes out. Nothing in the SDK cancels a flush task; one cancelled from outside cancels its callers' futures (a done callback on its task). A first set's caller that stops waiting leaves the set going (asyncio.shield), so the window's flush still follows it. flush() (and so Agent.close()) closes the open windows and waits for every flush and first set still out, with asyncio.wait, twice: the sets there when it starts, then those made while they went out, so it returns while a writer keeps setting, and cancelling it leaves the writes going. Agent.close() always runs flush() a second time in its finally, under the transport's request timeout, so sets made while the ambient run completed, or after a cancelled close began, are written too; the transport closes in a nested finally even if that wait is cancelled. Every window gets its timer when it opens, so one with only its first sets ends at its time and the open windows stay bounded; a window's first-set list is handed to its flush, if it has one, and cleared. A flush that fails outside a request (a value the JSON encoder refuses) gives that error to every set of the flush still waiting. The refusal is a plain BlacklistPattern with an empty pattern_id, the one way every caller tells it from a match; _over_budget builds its reason and the narrowed_reason a token narrowed to one user is shown (without the instruction count, which sums other principals' patterns) before it builds the value. blacklist.add reads the scope's held program fresh from ClickHouse, so two adds on one replica cannot both pass on a stale cache; two on two replicas can, and cache load then keeps the oldest.
  • A substring check holds the GIL for one in (about 10 ms over 32 MB), so it runs on the event loop only while the value's length times the substring patterns that apply stays within 1 MiB (SUBSTRINGS_ON_LOOP_BYTES), and on the matcher threads past it, with the org's turns, where the loop gets the GIL between patterns; the over-budget substring check takes the same path. The number of substring patterns a scope holds is not capped; that was so before this change and is left for a follow-up.
  • A blacklist regex compiles with no capture groups (a yes/no search) and at most 256 KiB of RE2 memory (REGEX_MAX_MEMORY; the default is 8 MiB, most of it DFA cache that fills and stays). Measured with 120 patterns of a[ab]{20}-shape over 80 KB random values: 367 MB resident at the default, 11 MB at 256 KiB, and the search ran faster (3.4 s to 1.3 s for all 120). A DFA that runs out falls back to RE2's NFA, which the work budget below prices.
  • find_match runs the patterns on the blacklist's own four threads when any applicable one is a regex, in the cache's order, so precedence and the first match are unchanged: RE2 releases the GIL while it searches (measured: another thread kept its full rate during a 1.7 s search), so a long value under many patterns waits for those threads, never the event loop or the shared default pool that logins and health checks use. The value is encoded to UTF-8 once and every regex searches those bytes (an unpaired surrogate reads as ? rather than raising); substrings match the value as sent.
  • The email shape keeps RFC 5321's lengths (64, 253, 24) and is found from its @ (sensitivity.has_email): one regex finds @ and a domain, then the local part is the run of local-part characters among the 64 before it, an email when a word boundary starts it (str.rstrip and one \b search, both in C). A regex that starts at every word boundary rescanned up to 64 characters, and the domain again, from each start (0.52 s per MB of ("a-"*32 + "@" + "ab1."*63)*k, 0.78 s of ("@" + "a."*126 + "1")*k); found from @, 0.007 s and 0.008 s. It answers what \b[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}\b answers on 200,000 fuzzed strings with no difference. A single-run anchored regex ((?<![...])(?>[...]*?\b)[...]{1,64}@...) was faster still but differed on 569 of them: it starts only at the first word boundary of a run, so "a-"*40 + "[email protected]" read as no email. The sweep's email and phone shapes use the same has_email and PHONE. The JWT pattern starts only where a run of its characters starts ((?<![A-Za-z0-9_-])eyJ), so each run is scanned once. A whole value still needs all three parts, so whole-value labelling and high_spans are unchanged; a window of a long value (detect_window_sensitivity) also reads _JWT_START, a header of at most 1,000 characters and the first 10 of the payload, so a long token the window's edge cuts is found from its first 1,017 characters. A two-part eyJ….eyJ… therefore reads high in a window and not as a whole value: a window can read higher than the whole, never lower but for the three named gaps.
  • Detection as a whole still reads up to about 1.2 s per MB (one pass per shape; a card-number scan is the largest share), so a 32 MiB request could hold the event loop for tens of seconds, and a worker thread would not help: Python's re and the detector's Python code hold the GIL, and asyncio.to_thread shares the default pool. sensitivity_level.resolve_level instead reads a request's values past 16 KiB (a value of at most 16 KiB is read whole after a turn, so its label does not depend on its place in the request; a longer one is read in windows; ON_LOOP_CHARS, about 20 ms of detection at worst; a bulk write's entries counted together) in windows of that size from sensitivity.detection_windows, with await asyncio.sleep(0) before each and the levels combined by max (stopping at high). Windows overlap by SHAPE_SPAN (1,024 characters), and every shape is found from a prefix no longer than that: an email in at most 343 characters, a JWT in a window in 1,017 (_JWT_START), a key, private key block, card, SSN, phone number or IBAN in fewer. Three are not, and a window's edge can split them, reading lower than the whole value: a stated PIN with about 1,000 characters of whitespace or qualifier words before its value, a password= assignment with about 1,000 characters of whitespace around its =, and a JWT whose header passes 1,000 characters. A window ends after whitespace no digit or dash touches, looked for in the 256 characters before the cut, so no card, phone or SSN run is split, and an edge reads as the whitespace it stands for, every shape's lookbehind and lookahead being one character; with no such whitespace near, the cut falls where it is, and a shape at it can read higher than the whole value. decoded_text runs detector_text's key walk the same way: detector_lines yields the decoded lines, and a turn comes every 16 KiB or 2,000 lines; parsing the JSON is one call (about 10 ms for 8 MB). memory.set, memory.bulk_set, memory.update and decision.record call both; the workers keep calling the detector directly.

Scope and risk

server/memory/app/blacklist_guard.py, server/memory/app/blacklist.py, server/memory/store/blacklist.py (the read order), server/transport/_common.py (binds the budget), server/memory/app/bulk_rows.py and memory_import.py with models_bulk.py (the new verdict), server/core/caller_regex.py (a dot_nl option), field and op comments with their reference page, docs/reference/errors.md, server/memory/domain/sensitivity.py, server/memory/app/sensitivity_level.py (new) with its callers in write.py, bulk_rows.py, update.py and decision.py, the sweep's probe pattern, shapes and docstring, server/core/errors.py (OVERLOADED names the matchers), tests and the refusal docs. Where RE2 and Python's engine differ:

  • RE2 has no backreferences, lookaround, \Z (RE2 spells it \z), (?x), \uXXXX, or atomic and possessive forms: such a pattern is refused at add, and a stored one is dropped from the write path at cache load with a warning (blacklist: dropping regex pattern), as a pattern failing validation already was. The sweep could never run one.
  • $ matches only at the very end, not before a trailing newline; \d, \w and \b are ASCII. This matters only on the write paths that pass raw text (decisions, observations, learnings); memory.set matches the JSON-encoded value, whose newlines are escaped.
  • A JWT right after a - no longer reads as high; an email whose local part is an unbroken run of more than 64 characters no longer reads as medium.

Compatibility, rollout and rollback

  • Wire: a write whose request's values are too long for the blacklist regexes that apply answers 422 BLACKLISTED with an empty pattern_id; a bulk entry refused this way has conflict_verdict: blacklist_unchecked and is listed in skipped_blacklisted, an extracted fact refused this way is in memory.set_from_messages's refused with verdict: blacklist_unchecked, memory.import reports it with reason blacklist_unchecked, and memory.import_evidence counts it in a new unchecked field (also in skipped): new values.
  • Wire: blacklist.add with a regex RE2 cannot compile, one over 300 instructions, or one past its scope's 3,000 answers 422 BLACKLIST_PATTERN_INVALID naming the reason; a regex the old guard refused for its shape is now accepted.
  • Operator steps: find stored regexes this build drops (SELECT pattern_id, pattern FROM loom.blacklist FINAL WHERE pattern_type = 'regex' AND tombstoned_at IS NULL, then loom logs blacklist: dropping regex pattern at cache load) and replace each with an RE2 form.
  • Rolling upgrade: while builds N-1 and N serve together, a pattern N accepts that N-1's shape check refused (such as (a+)+$) refuses writes only on N replicas, and an RE2-only spelling (\z, \pL, [[:digit:]]) means something else, or nothing, on N-1. The exposure to a hostile pattern does not grow: N-1 already accepted one.
  • Wire: a write that waits more than 5 s for its org's share of the matcher threads answers 503 OVERLOADED (retryable, retry_after_s 1), not a stored row.
  • Older Python SDKs map blacklist_unchecked on a coalesced set to a successful no-op: against this server, a coalesced set refused for the budget is silently dropped by an older SDK (its caller sees noop). Upgrading the SDK sends it again alone; a caller on an older SDK that needs the write should check conflict_verdict or pass Agent(coalesce_sets=False).
  • Rollback: patterns stored by this build keep their RE2 spelling, which the older build's Python engine reads as above.

Tests

pytest tests/unit/test_blacklist_authority.py tests/unit/test_memory_sensitivity.py tests/unit/test_sdk_set_coalescer.py tests/unit/test_bulk_rows_carry_labels.py tests/unit/test_assistant_learnings.py: backtracking shapes, including one the old guard accepted, search 4x-longer hostile values in under 8x the time; patterns with a backreference, lookaround or \Z are refused at add (422) and dropped at cache load, while a stored \bssn\b still refuses a matching value through find_match and passes another; on the matcher threads a namespace regex wins over a global substring that also matches, and a lone surrogate is read; a scope near its program budget refuses another regex but not a substring; scope_program sums the regexes at exactly the scope; the cache keeps a scope's oldest regexes within its budget and a row RE2 refuses takes no room; a value past the work budget is refused without a search, its size counted in UTF-8 bytes; a request's entries share one budget, a worker pass checks each value on its own, and past the budget a matching substring pattern still names itself; a bulk entry refused for the budget answers blacklist_unchecked, and so does a memory.import entry, while another entry of the same import is written; a coalesced SDK set answered blacklist_unchecked is sent again alone and its caller gets that answer; while one org's six searches block, another org's search finishes and the first org never runs more than two at once, and both orgs keep their semaphore with every turn back; two searches cancelled mid-search keep their turns until their threads finish, so two later searches of the org wait and the org never runs more than two (fails when the slot is released on cancel); a search that waits past MATCHER_WAIT_S refuses the write with OVERLOADED and every turn comes back (fails with no deadline); an unchecked coalesced set and a later set of its key that the server answers unchecked too (a merge, say) both go again, older first; when the newer is refused alone the older is still written; 200 sets of 2 KB under an 80 KB budget take at most six bulk requests, in order, with no point sets (fails on the previous one-set-per-entry resend); entries unchecked at the front of a request go alone; twelve values each past the budget alone take one bulk request and twelve point sets (fails on the previous head, which resent the whole rest each round); a skipped 40 KB restatement adds no room, so three unchecked entries behind it go alone after one bulk request (fails when every answered row counts); the first window's unchecked set sent again lands before the next window's set of its key; a window's first set of a key lands before its own flushed sets of that key (fails when a window's first sets are not in the chain); a set after a window's time, before its timer runs, lands after the expired window's set of its key (fails when the expired window is not flushed first); a flush whose second bulk request fails gives that error to the sets of that request and to the ones not yet sent, with no further requests (fails when the rest go as point sets); a flush cancelled while it waits behind a held one gives its callers CancelledError (fails when the cancel is handled inside the flush); a window's two first sets go out side by side, one landing while the other is held (fails when they wait for each other); Agent.close() waits for a first set queued behind a flush before the transport closes (fails when first sets are not waited for); sets made while Agent.close() waits are written before it returns (fails when flush() waits once); a cancelled Agent.close() leaves the transport open until the held writes land (fails when the transport closes at once); Agent.close() returns while a writer keeps setting (fails when flush() waits until no write is left); a set made after a cancelled close began is written before the transport closes (fails when the cancelled close only waits for the writes already out); the transport closes when a cancelled close is cancelled again (fails without the nested finally); 200 identities' first-set windows are gone once their time is up (fails when a window with no gathered sets is kept); a first set whose caller cancels still lands before the window's flushed set of its key (fails without the shield); cancelling flush_sets() leaves the writes going (fails with gather); a flush whose value the JSON encoder refuses (a datetime) gives its sets that TypeError (fails when the error is left on the flush task); these use events in the fake transport and bounded loops, not fixed sleeps; a cancelled flush cancels its callers and stays cancelled (fails on the previous head); in memory.bulk_set, after an entry over the budget, a later changed value and a later restatement of the same key are both answered blacklist_unchecked while another key's entry is written (fails without the per-key rule); a value too long alone is told to shorten it and one that fits alone to send less, and a narrowed token's message carries no instruction count; has_email answers what the bounded email regex answers on 20,000 fuzzed strings, a local part counted over the last 64 characters before @; on the two crafted worst cases it costs under 20 times one plain regex pass over the same text (about 1x to 2x measured; the regex form costs 100x to 160x, and the test fails with it); a 188 KB value is labelled in reads of at most ON_LOOP_CHARS, at least one per window, with another task running before each (no wall-clock bound); a long JSON value is decoded to detector_text's text while another task takes turns; windowed detection gives the whole value's level on 240 fuzzed values with 0 to 2 shapes, a 3 KB JWT among them, placed across a window's edge (fails with no overlap); the 3 KB JWT across a whitespace-free cut and an email after a 6,000-character run with no whitespace read high and medium both ways (the JWT fails with the previous pattern), and the three named gaps read high whole and '' windowed; a two-part JWT reads '' whole and high in a window, with its signature high both ways; detection_windows refuses a window under 4 * SHAPE_SPAN (ValueError); a short two-part JWT reads '' at a bulk write's first entry and after 20,000 characters of earlier entries (the second fails when position decides windowing); a long substring scan runs on the matcher threads, a short one on the loop, and past the regex budget the substring check still names its hit (fails with the scan on the loop); a bulk write's entries count together; the assistant-learnings tests run the guard's real find_match over a cache built from their patterns (they patched _matches, which this change removed); . matches a newline and the search runs on the matcher threads; a 400-repeat class is refused for its program; detection of email-shaped, @-shaped and JWT-shaped runs stays linear (the file's 4n/n ratio check), and an email and a JWT still read as before. In the integration suite, test_a_namespace_admin_cannot_write_or_remove_a_wider_pattern probes add-time bounds with (a+)\1 (RE2 has no backreferences) and [ab]{400} (over 300 instructions) instead of (a+)+$, which RE2 runs in linear time and this change accepts. The linear-time tests fail on main. pytest over the blacklist, sensitivity, bulk, import, evidence-import, tunable-constant, docs-reference, package-contract, transport-layering, doc-link, public-copy, no-secrets, assistant-learnings, write-path, update, decision, observe, sweep, export and agent-instruction unit files and every test_sdk_* file (76 files, no -n) passed on 87052b0: 1,750 tests; the last change touched only the SDK, and every test_sdk_* file with the copy and agent-instruction files passes on this head (706 tests). The sweep's dry-run email probe now carries the detector's \b anchors as well as its bounds, so the two count alike.

Measured with python on the branch, 8 MB values through decoded_text then resolve_level, a 10 ms ticker running, on a host at load 50: prose took 2.96 s with a longest gap of 69 ms; ("a-"*32 + "@" + "ab1."*63 + " ")*k 6.11 s, 92 ms; "x"*8_000_000 (no whitespace, hard cuts) 2.06 s, 69 ms. Read whole, each holds the loop for the whole time. Measured on one host before the change: validate_regex(r"q?(\d|\d)*z") returned None and the search of 22 digits took 0.54 s, doubling per digit; detection of "a-" * 40_000 took 5.6 s and of "eyJ-" * 25_000 2.3 s. After: 0.0003 s for the regex on 100,000 digits; under 0.1 s for detection of each 200 KB input.

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code. I measured both regexes before and after and checked RE2's refusal of the constructs it lacks.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/reference/ tables (python scripts/codegen/docs_reference.py), the reach manifest, schemas/schema.sql (make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

@zlareb1 zlareb1 changed the title Blacklist regexes run on RE2 and the email detector is bounded, so no write value can stall a server Blacklist regexes run on RE2 off the event loop, and the email and JWT detectors run in linear time Nov 6, 2026
zlareb1 and others added 14 commits November 7, 2026 06:37
… write value can stall a server

A blacklist regex ran on Python's backtracking engine on every covered write, guarded by a shape check and timed probes that a crafted pattern passes. It now runs on RE2, the engine the sweep's ClickHouse match() already uses. The sensitivity email pattern rescanned a long run with no @ from every word boundary; its parts are bounded by RFC 5321's lengths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
… start the JWT detector only at a run's start

RE2 is linear in the value but costs more per character as its program grows past what its DFA can cache, so a regex compiles to at most 300 instructions, and the match runs in a thread (RE2 releases the GIL). Blacklist regexes compile with . matching newlines, as ClickHouse match() does. The JWT pattern started at every eyJ after a dash inside one run and rescanned the run each time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…s own threads

With the program cap, the per-scope count bounds what one write runs; the matcher threads keep a long value under many patterns away from the event loop and the shared pool. A lone surrogate in a raw-text write is read, not an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…e's first regexes past the cap at cache load

A value whose length times the RE2 instructions its scopes' regexes hold passes a budget is refused as a matched pattern is, before any search. The per-scope cap is enforced again when the cache loads, in pattern-id order so every replica keeps the same rows. Substrings match the value as sent; regexes match it with unpaired surrogates replaced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…te's regex work in bytes

A scope's regexes together compile to at most 3,000 RE2 instructions, checked at add and at cache load (oldest kept; a row RE2 refuses takes no room); one write's bytes times instructions are bounded to about a second of a matcher thread, the refusal naming the widest scope that holds a regex. Tests cover . across newlines and that the search runs on the matcher threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…a value is too long to check

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…y, and search the UTF-8 bytes once

Each compiled pattern kept up to 8 MiB of DFA cache; 256 KiB bounds what a scope's regexes hold (measured: 120 patterns over 80 KB values went from 367 MB to 11 MB, and searched faster). A yes/no search keeps no capture groups. The value's UTF-8 bytes go to every regex, not a re-encoded string per pattern.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ies share it

A bulk write checked each entry against the per-value budget, so one request could spend a thousand writes' worth of matcher time. The request's work bag now carries the bytes times instructions spent; past the budget a substring pattern that matches still names itself, and the refusal says the request's values are too long to check together.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…entry the blacklist could not check apart from a match

The work bag is also bound once per worker pass, so a pass's jobs from several tenants shared one budget; the budget is its own ContextVar the transports bind at each op, and a worker is per value. A bulk entry refused for the budget answers blacklist_unchecked. blacklist.add reads the scope's program fresh.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…use the detector's email shape, and test the transport binds the budget

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
memory.import names it blacklist_unchecked and import_evidence counts it in unchecked; the SDK's bulk_set docstring names the new verdict.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…gs and the import result

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ist could not check is sent alone, and a value too long alone says so

The SDK coalescer resends a blacklist_unchecked entry as its own memory.set rather than reporting a no-op. find_match takes a per-org turn (MATCHERS_PER_ORG) on the matcher threads. A value past the budget by itself is told to shorten, not to send less; a narrowed token's message drops the instruction count. Log lines name the unchecked case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…es out as overloaded, and an unchecked coalesced set never overwrites a newer one

- The matcher's org and thread turns are held until the executor future
  finishes (shielded), so a cancelled request never lets an org run more than
  MATCHERS_PER_ORG searches; a search waiting more than MATCHER_WAIT_S refuses
  the write with 503 OVERLOADED. Each org keeps one semaphore.
- The over-budget refusal is an OverBudget value that builds its message per
  audience instead of cutting the counts out of a formatted string.
- The Python SDK coalescer reads a batch from the last entry back: an unchecked
  entry with a later written or resent entry of its key is a no-op, and only
  the last unchecked entry of a key is resent.
- Email detection is found from its `@` (has_email), with the same answers as
  the bounded regex and about 1-2x one regex pass on the worst cases measured
  (the regex: 100-160x); a write's sensitivity detection runs on a worker
  thread once its values pass 64 KiB.
- The assistant-learnings tests run the guard's real find_match; the
  cross-principal integration test probes RE2's add-time bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the sec/linear-write-regexes branch from 0ef7d96 to f0aa864 Compare November 7, 2026 07:18
zlareb1 and others added 11 commits November 7, 2026 07:52
…coalesced sets go out again in order as smaller batches

- Detection holds the GIL, so a worker thread did not free the loop: a
  request's values past 16 KiB are read in windows that overlap by more than
  the longest shape and end after whitespace no digit or dash touches, with a
  turn between windows; detector_text yields its lines the same way.
- The Python SDK coalescer sends the entries the blacklist could not check
  again, in order, as a smaller memory.bulk_set until each is answered; one
  unchecked at the front of a request goes alone. An unchecked entry a later
  entry of its key wrote over answers noop with verdict clear.
- The over-budget refusal is a BlacklistPattern with an empty pattern_id and
  a narrowed_reason, built once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…nchecked key are unchecked too, and the SDK resends each unchecked set alone

- The JWT shape matches a header of up to 1,000 characters and the start of
  its payload (running on through the rest for spans); a longer header still
  needs all three parts, so a whole read finds what it did. The shapes a
  window edge can still split are named: a stated PIN or an assignment with
  about 1,000 characters of whitespace, a JWT header past 1,000.
- memory.bulk_set answers every later entry of a key blacklist_unchecked once
  one was, so a merge or restatement cannot land ahead of the earlier value;
  the SDK coalescer sends each unchecked entry again as a memory.set, in
  order, with no reverse-scan bookkeeping and no rounds.
- The event-loop tests bound read size and check another task runs between
  reads instead of timing; docs rewrapped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…quest checked, and a whole value's JWT keeps its signature

- The SDK coalescer resends the entries answered blacklist_unchecked in
  order, in batches of the value bytes the last request checked, and one
  unchecked at the front of a request alone; the server's per-key rule keeps
  a key's entries in order, so no landed bookkeeping is kept.
- A whole value's JWT needs its signature, as on main; a window of a long
  value also reads a header and the start of its payload
  (detect_window_sensitivity), since its edge may cut the signature off.
- detection_windows refuses a window under 4 * SHAPE_SPAN; the docs say a
  caller that does not send unchecked entries again keeps the earlier value
  and why the server sends none again; test fixes and two new tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…d nothing sends the rest alone, and long substring scans leave the event loop

- The SDK coalescer chains each identity's flushes, and a window's first
  sets wait for the flush in progress, so a set sent again cannot land after
  a newer set of its key. Room for the next batch counts only rows the
  blacklist read; a request that checked nothing leaves the rest to go one at
  a time. Sizes are computed once; a cancelled flush cancels its callers.
- A value of at most 16 KiB is read whole whatever its place in a request.
- A substring scan past 1 MiB of value times patterns runs on the matcher
  threads, over budget too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
… and a failed flush request fails the sets still waiting

- A window's first sets go through the identity's chain too, so the
  window's flush waits for them, and a window whose time is up is flushed
  before the next window starts.
- A failed bulk request gives its error to every set of the flush still
  waiting, instead of sending the rest as point sets.
- Tests use events in the fake transport instead of sleeps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
… flush cancelled in its queue tells its callers

- A window's first sets wait only for the identity's last flush; the
  window's flush waits for that flush and its own first sets.
- A done callback on the flush task cancels its callers' futures when the
  task was cancelled, running or still waiting its turn.
- The class docstring is reflowed and the module comment says when the
  first sets go out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ps the identity behind the flush ahead

- First-set tasks join the in-flight set, so flush() and Agent.close() wait
  for them before the transport closes; flush() waits with asyncio.wait, so
  cancelling it leaves the writes going.
- A flush cancelled before its turn hands the identity's last flush back to
  the one it followed, and anything waiting on it waits for that one.
- A first set's caller that cancels leaves the set going (shield), so the
  window's flush still follows it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…s the writes land first

- The cancelled-flush restore and its predecessor map are gone: nothing in
  the SDK cancels a flush task; one cancelled from outside still cancels its
  callers' futures.
- flush() closes the windows and waits again until no write is left, so a
  set made during close() is waited for.
- A cancelled Agent.close() waits for the coalesced writes still out, up to
  the request timeout, before the transport closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…d every coalescing window ends at its time

- flush() closes the windows and waits twice, so a writer that keeps setting
  does not hold close() open.
- A cancelled Agent.close() runs flush() again under the request timeout,
  so a set made after the cancel is written, and the transport closes in a
  nested finally even if that wait is cancelled; _SetCoalescer.wait is gone.
- Every window gets its timer when it opens, so one with only its first
  sets ends at its time; its first-set list is handed to its flush.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…eads its last wait from the transport

- When a flush task ends with an error (a value the JSON encoder refuses),
  every set of it still waiting gets that error.
- Agent.close() always runs flush_sets() again under the transport's request
  timeout, and says why; _wait_for_sets and the duplicate timeout are gone.
- The window tests wait in bounded loops instead of fixed sleeps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 merged commit 8742bc4 into main Nov 7, 2026
36 of 38 checks passed
@zlareb1
zlareb1 deleted the sec/linear-write-regexes branch November 7, 2026 10:34
@zlareb1 zlareb1 mentioned this pull request Nov 12, 2026
3 tasks done
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