Repository navigation
fix(platform): make the PII scrubber load, scan whole and tell the truth - #3229
Merged
Merged
Conversation
The pii data loader resolved its root from an explicit option or a walk-up to the repo checkout's configs/platform/system/pii — and nothing else. A shipped image has no checkout: the Dockerfile bakes the tree at /app/system and sets TALE_CONFIG_SYSTEM_DIR, which the providers and connectors readers honour and this loader ignored. So in every container createScrubberFromConfig threw, pii_gate caught it and indexed each document unscrubbed behind a per-document warning, and an org's block/mask policy was void. One resolver now serves all three readers (lib/shared/config/ system-root.ts): explicit root, then an absolute TALE_CONFIG_SYSTEM_DIR, then the walk-up. The loader also checks the resolved tree exists and names the path and the remedy when it does not. Boot probes the tree once per process and logs (never fails) when it is missing, so an image built without it says so before the first policy hit. Finding: lib-utils-pii-1.
Scrubber.scrub clamps its input to the 50 KB chat-message cap before any regex runs, and pii_gate indexed whatever came back: under mask or tokenize a match in the first 50 KB meant only the first 50 KB was chunked, embedded and hashed as the document's identity, and under every mode an identifier past byte 50,000 was never seen. The engine's `truncated` flag existed for exactly this and its only consumer never read it. lib/pii gains scrubDocument(scrubber, text): the text is cut into windows that stay under the clamp (preferring paragraph, line, then space boundaries), each window is scrubbed, a window that still reports truncated is halved and rescanned, and the verdicts are joined — any blocked window blocks, a step error surfaces, rewritten windows replace their text in order. The gate uses it, and its silent step-error branch now says that it indexed unscrubbed. Finding: lib-utils-pii-2.
createTokenizer materialized its own pattern list with a private copy of the scrubber's factory walk — and that copy skipped the admin's custom patterns, so a policy in tokenize mode masked an employee-id pattern at the indexing gate but let the same value through when the chat guardrail tokenized a prompt. The two entry points also drifted in how they reported an unknown pattern name. `materializePatterns` (lib/pii/engine/materialize.ts) is now the one resolution from ScrubberOptions to the compiled list — locale union, enabled factories in toggle order, then vetted custom patterns — and both createScrubber and createTokenizer consume it. The tokenizer's public surface (createTokenizer / detokenize / TokenEntry) is unchanged: the chat guardrail's tokenize filter restores model output through it, so the mode's promise is backed by a real round trip. Finding: lib-utils-pii-3.
applyPiiPolicyForIndexing called createScrubberFromConfig for every document: a readdir + stat walk of the data tree, a JSON digest of every locale's address and phone blocks, and a fresh RegExp per national-id spec and custom pattern — on the indexing worker's event loop, once per document of a sync backlog, although the policy changes only when an admin saves it and the engine's own contract says build once and reuse. pii_gate now keeps a bounded per-process cache keyed by the policy's content; a changed policy gets a fresh scrubber on its next document. A construction failure is not cached — it is reported once per policy at error level (a missing data tree is a packaging defect, not a per-document event) and retried on the next document so a repaired tree heals without a restart. Finding: lib-utils-pii-4.
…calls buildFolderView / isInFolder (with FolderRow / FolderView) and stripLeadingPunctuation (with LEADING_PUNCTUATION_RE) lost their last consumers in the #2857 rewrite; only their own tests still imported them. normalizeFolderPath, the one folder-tree export with live callers, is already re-implemented where it is used, so the module goes with it. Findings: lib-utils-pii-5, lib-utils-pii-6.
Three byte formatters coexisted in lib/utils: format-bytes.ts (guarded, B/KB/MB), format/number.ts formatBytes (localized, to PB, no guard) and format/file.ts formatFileSize (toFixed, B/KB/MB). The documents feature showed the same size two ways depending on the dialog, and the most-used copy rendered a negative or sub-byte value as "NaN undefined". format/number.ts formatBytes is now the one formatter: a non-finite or negative value renders as an em dash, a sub-byte value as 0 B, and the unit index is clamped so a size beyond PB grows the number instead of losing its unit. format-bytes.ts is gone and its callers re-pointed; formatFileSize delegates to it so chat attachments and document lists agree. Finding: lib-utils-pii-7.
loadDayjsLocale swallowed an import failure in an empty catch, so a renamed chunk or a CDN 404 left every date rendering in English with no signal anywhere — against the repo's no-empty-catch rule. The handler now warns with the locale and the error; the fallback itself is unchanged. pendingLoads is typed. Finding: lib-utils-pii-8.
Contributor
Author
|
Integration proof, run 1 (
|
scrubDocument cut its windows at MAX_MESSAGE_BYTES / 4 code units on the premise that normalization cannot grow a window past the clamp. It can: the engine runs NFC before it clamps, and a composition-excluded code point decomposes under NFC (U+0958 becomes U+0915 U+093C, three UTF-8 bytes become six), so a window of them doubled inside scrub and was clamped there. scrub reported the clamp only on a modified, flagged or blocked verdict; with no match in the clamped prefix it returned a bare pass, scrubDocument took that as a clean window, and the unscanned tail with any identifier in it was indexed verbatim. A crafted document walked past a block policy, and mask mode indexed the raw tail. The pass verdict now carries `truncated` like every other kind, scrub sets it on the no-match path, and scrubDocument treats any truncated verdict as unscanned and halves the window. The header's NFC premise is corrected. Tests: a window headed by 12,000 U+0958 followed by a card number blocks under block and masks under mask; scrub alone reports a clamped no-match input as truncated; the gate refuses the same document under block and masks it under mask. Finding: lib-utils-pii-2.
createScrubberFromConfig evaluated its default registry parameter, PatternRegistry.fromDefaults(), before it looked at the policy, so a disabled policy still loaded the data tree and, in an image without one, raised the packaging error for an organization that had switched the filter off. The default is now resolved inside the enabled branch, so a disabled policy's null verdict never depends on the tree being there. Finding: lib-utils-pii-1 (review follow-up).
scrubberForPolicy capped its scrubber cache at 32 policies but kept the set of policies whose construction failure it had already reported unbounded, so a stream of distinct failing policies grew it without limit. Both now share one eviction helper and one limit; an evicted policy reports once more, which is the price of the bound. The module header also says that tokenize-mode indices are numbered per scanned window, not per document, so nobody reads them as an identity. Finding: lib-utils-pii-4 (review follow-up).
Contributor
Author
|
Integration proof, run 3 — on the repair tip
The |
One unbroken 50k-char word sends the email pattern quadratic (every position scans ahead for a @ that never comes): ~5s on a loaded CI runner, over vitest's 5s budget. Same bytes, same clamp, same verdict.
This was referenced Sep 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes the eight confirmed findings of the backend deep review's pii theme (lib/utils + lib/pii slice). The PII scrubber now loads its data tree in a shipped image (
TALE_CONFIG_SYSTEM_DIR, through one resolver shared with the providers and connectors readers), scans a whole document at the indexing gate instead of the first 50 KB (and never indexes a window the engine clamped, whatever verdict the clamped prefix produced), resolves the tokenizer's patterns from the same walk as the scrubber (custom patterns included) so the tokenize mode's round trip is real, builds one scrubber per policy per process instead of one per document, and — in the same lib/utils slice — drops two dead helpers, converges three byte formatters on one, and logs the dayjs locale-import failure the empty catch swallowed.Findings fixed
lib/shared/config/system-root.tsis the one resolver (explicit root → absolute$TALE_CONFIG_SYSTEM_DIR→ repo walk-up) behindloadPiiData,providers/load_system_config.tsandconnectors/catalog.ts; the loader checks the tree exists and names the path + remedy;backend/main.tsprobesPatternRegistry.fromDefaults()once at boot (logs + Sentry, never fails boot). Tests:lib/shared/config/system-root.test.ts,tests/pii/loader.test.ts(env tree found outside a checkout, relative env ignored, neither → throws naming the path).scrubDocument(scrubber, text)(lib/pii/engine/document.ts) cuts the text into windows under the clamp (paragraph → line → space boundaries, surrogate-safe), halves and rescans any window that comes backtruncated, and joins the verdicts (any blocked blocks; a step error surfaces; rewritten windows replace their text in order).pii_gateuses it. Repair (review blocking 1): the engine runs NFC before it clamps and a composition-excluded code point doubles under NFC (U+0958 → U+0915 U+093C, 3 → 6 bytes), so a window cut under the clamp could still be clamped insidescrub()— andscrub()returned a barepasswhen the clamped prefix had no match, so the halving never engaged and the unscanned tail was indexed (a crafted document walked past a block policy).FilterPassOutcomenow carriestruncated?like every other kind,scrub()sets it on the no-match path,scanPiecetreats any truncated verdict as unscanned, and the header's false NFC premise is corrected. Tests:tests/pii/document.test.ts(12,000 × U+0958 + card →blockedunder block,[CREDIT_CARD]under mask; a fake scrubber's truncatedpassis halved),tests/pii/smoke.test.ts(scrub()on a clamped no-match input →pass(true); under the clamp → no flag),pii_gate.test.ts(the same document →refuseunder block, masked under mask) plus the existing 120 KB documents with PII in the first and last paragraph and only past byte 60,000.materializePatterns(lib/pii/engine/materialize.ts) is the single ScrubberOptions → pattern-list resolution;createScrubberandcreateTokenizerboth consume it, so the tokenizer no longer drops the admin's custom patterns. The tokenizer surface (createTokenizer/detokenize/TokenEntry) is kept: the chat-turn theme'sbackend/core/chat/guardrails.tsbuildscreateTokenizerand detokenizes model output through it, which is what backs the "restore in the reply" copy. Test:tests/pii/tokenizer.test.tscustom-pattern round trip. Dependency, stated plainly: on this PR alonecreateTokenizer/detokenizehave no production consumer; the "restore the original details in the reply" promise is backed by the chat-governance PR (fix/chat-guardrails-policy-wiring), which should land first or together with this one. What this PR fixes at the root is that the tokenizer resolved a different pattern list than the scrubber.pii_gate.scrubberForPolicycaches one scrubber per distinct policy (content-keyed, bounded at 32); a construction failure is reported once per policy at error level and retried on the next document. Tests: same instance for equal policies, new one for a changed mode, disabled verdict cached, failure logged once across two documents. Review follow-ups: the reported-failure ledger is bounded by the same limit and eviction helper as the cache (test: 32 further distinct failing policies evict the first, which then reports once more); the module header says tokenize-mode indices are per scanned window, not per document;createScrubberFromConfigresolves its default registry only for an enabled policy, so a disabled policy never touches the data tree (test:PatternRegistry.fromDefaultsnot called for a disabled policy, called once for an enabled one).lib/utils/folder-tree.ts(+ test) deleted:buildFolderView/isInFolderwere test-only since feat(platform): rewrite the AI backend on a minimal YAML-config core #2857; the livenormalizeFolderPathcallers usebackend/domains/folders/paths.ts.stripLeadingPunctuation/LEADING_PUNCTUATION_REdeleted fromlib/utils/string.ts(+ its describe block).lib/utils/format/number.ts formatBytesis the one byte formatter: non-finite/negative →—, sub-byte →0 B, unit index clamped;format-bytes.tsdeleted and its three callers re-pointed;formatFileSizedelegates to it.file-preview-card.test.tsxre-pinned to the converged rendering (2 KB/1 KB/3 MB, wastoFixed(1)).dayjs-setup.tswarns with the locale and error when a locale chunk fails to load;pendingLoadstyped.Skipped
None. (
lib/shared/config/yaml.tskeeps its private KiB formatter: it words a config-file size cap in an error message, not a UI file size — left as the finding allowed.)Tests & gates observed
All on the final tree (HEAD
170f37f52, based onorigin/mainfe27bd32b). The first PR body's figures were one74e8bd95; these are the re-runs after the three repair commits.services/platform:bunx tsc --noEmit— exit 0;bunx oxlint --type-aware— exit 0, no output.bunx commitlint --from origin/fix/pii-scrubber-truth(the three repair commits) —found 0 problems, 0 warningseach; headers 69 / 71 / 65 chars.bun run check—Tasks: 39 successful, 40 total:@tale/platform:testTest Files 501 passed (501)/Tests 73209 passed (73209)(+8 for the new tests: 3 document, 2 smoke, 2 resolve-config, 1 pii_gate);@tale/shared22 /@tale/ui124 /@tale/docs30 /@tale/web22 files passed. The one red task istest:ui:Test Files 1 failed | 454 passed (455)/Tests 2 failed | 3501 passed (3503)— bothapp/features/settings/connectors/components/connectors-settings.test.tsxcases,Error: Test timed out in 5000ms.under the 40-task parallel load. Rerun alone withbunx vitest --run --config vitest.ui.config.ts <that file>(thetest:uiconfig) —Test Files 1 passed (1)/Tests 20 passed (20); and once more with--project client—20 passed (20). No UI file changes in this PR.bun run knip:check— exit 0 (thecron-parserconfiguration hint is present onmainas well).run-itest.sh, real Postgres + MinIO, PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222'saa3d1d7a9cherry-picked-nfor the run only and dropped withgit reset --hardafterwards — not in this branch):[itest] 464/466 checks passed across 133/133 lanes, noRUN TRUNCATED(log: 1,696 lines). The two red checks are the known main-side ones and unchanged from the reviewer's own run:webdav re-home (protocol + tree + locks + visibility on pg)(red onmainbefore this campaign) andknowledge: corpus scope drift is corrected and reported — drifted=null(PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222's own probe, the lane the documents theme traced to a pick with noORDER BY; this branch touches no documents/corpus file). ThecheckTasksCollabIntegrityaudit-chain serialization truncation the reviewer hit did not recur on this run — it is alockChainHeadretry-budget flake onmain, not attributable to this diff (no audit/db/tasks file touched); the 13 sandbox/automation lanes it had cut off all ran and passed here.e74e8bd95with a read-only bun script:scrubDocument(block, U+0958×12000 + " card 4111 1111 1111 1111 on file")→{"kind":"pass"}(input 12,033 code units, 72,033 bytes after NFC,clampMessage(...).truncated === true); after the fix the same call →{"kind":"blocked","categoryIds":["creditCard"],"matchCount":1}, and the mask scrubber →modifiedcontaining[CREDIT_CARD].Notes for the reviewer
9b0fb92c7): that commit is pushed and the repair brief forbids rewriting history, so it stays as is; the PR squash-merges, and the header that survives is the PR title, now 72 chars (was 78). The three repair commits are ≤72 chars withcommitlintat 0 problems / 0 warnings each.lib/chat/guardrails.ts, chat-turn theme's file) has the same shape —pass()afterclampMessageon a no-hit — but its dispatcher does not readtruncatedon a pass and never re-assembles windows, so nothing changes for it here; the widenedFilterPassOutcomeis backward compatible (optional field), andpass()with no argument still equals{ kind: 'pass' }undertoEqual.PatternRegistry.fromDefaults()inside the built image under/app/system/pii) is not in this PR — the compose-stack smoke job in.github/workflows/build.ymlis the place for it, outside the platform workspace; the boot probe inbackend/main.tsreports the missing tree at error level in every running container instead.applyPiiPolicyForIndexingwith apii_config. The unit tests are the pin for the whole-document scan and the cache; a lane would need an org with a governance policy plus an upload-and-wait-for-indexing choreography inintegration-check.ts(≈40k lines) that this theme does not otherwise touch, so it is a follow-up rather than a same-change fix.fix/chat-guardrails-policy-wiring, worktree fx-chat-governance): it toucheslib/chat/*and addsbackend/core/chat/guardrails.ts, which importscreateScrubber,createTokenizer,Tokenizer,TokenEntryandScrubberfromlib/pii— none of those signatures change here. The two branches touch no common file.applyPiiPolicyForIndexing's fail-open on a broken scrubber is unchanged in kind; what changed is the volume (oneconsole.errorper policy per process instead of aconsole.warnper document) and the boot probe that names a missing tree before the first policy hit.formatFileSize(chat attachment surfaces) now renders1.5 KBas before but2048as2 KBrather than2.0 KB, and sizes above 1 GB in GB — the point of converging on one formatter.oxlint --type-awarerun prints nothing on success in this workspace; exit code 0 was checked explicitly.