Skip to content

fix(platform): make the PII scrubber load, scan whole and tell the truth - #3229

Merged
larryro merged 11 commits into
mainfrom
fix/pii-scrubber-truth
Sep 5, 2026
Merged

larryro merged 11 commits into
mainfrom
fix/pii-scrubber-truth

Conversation

@larryro

@larryro larryro commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

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-utils-pii-1 — lib/shared/config/system-root.ts is the one resolver (explicit root → absolute $TALE_CONFIG_SYSTEM_DIR → repo walk-up) behind loadPiiData, providers/load_system_config.ts and connectors/catalog.ts; the loader checks the tree exists and names the path + remedy; backend/main.ts probes PatternRegistry.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).
  • lib-utils-pii-2 — 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 back truncated, and joins the verdicts (any blocked blocks; a step error surfaces; rewritten windows replace their text in order). pii_gate uses 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 inside scrub() — and scrub() returned a bare pass when 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). FilterPassOutcome now carries truncated? like every other kind, scrub() sets it on the no-match path, scanPiece treats 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 → blocked under block, [CREDIT_CARD] under mask; a fake scrubber's truncated pass is 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 → refuse under block, masked under mask) plus the existing 120 KB documents with PII in the first and last paragraph and only past byte 60,000.
  • lib-utils-pii-3 — materializePatterns (lib/pii/engine/materialize.ts) is the single ScrubberOptions → pattern-list resolution; createScrubber and createTokenizer both 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's backend/core/chat/guardrails.ts builds createTokenizer and detokenizes model output through it, which is what backs the "restore in the reply" copy. Test: tests/pii/tokenizer.test.ts custom-pattern round trip. Dependency, stated plainly: on this PR alone createTokenizer / detokenize have 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.
  • lib-utils-pii-4 — pii_gate.scrubberForPolicy caches 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; createScrubberFromConfig resolves its default registry only for an enabled policy, so a disabled policy never touches the data tree (test: PatternRegistry.fromDefaults not called for a disabled policy, called once for an enabled one).
  • lib-utils-pii-5 — lib/utils/folder-tree.ts (+ test) deleted: buildFolderView / isInFolder were test-only since feat(platform): rewrite the AI backend on a minimal YAML-config core #2857; the live normalizeFolderPath callers use backend/domains/folders/paths.ts.
  • lib-utils-pii-6 — stripLeadingPunctuation / LEADING_PUNCTUATION_RE deleted from lib/utils/string.ts (+ its describe block).
  • lib-utils-pii-7 — lib/utils/format/number.ts formatBytes is the one byte formatter: non-finite/negative → —, sub-byte → 0 B, unit index clamped; format-bytes.ts deleted and its three callers re-pointed; formatFileSize delegates to it. file-preview-card.test.tsx re-pinned to the converged rendering (2 KB / 1 KB / 3 MB, was toFixed(1)).
  • lib-utils-pii-8 — dayjs-setup.ts warns with the locale and error when a locale chunk fails to load; pendingLoads typed.

Skipped

None. (lib/shared/config/yaml.ts keeps 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 on origin/main fe27bd32b). The first PR body's figures were on e74e8bd95; 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 warnings each; headers 69 / 71 / 65 chars.
  • Root bun run check — Tasks: 39 successful, 40 total: @tale/platform:test Test Files 501 passed (501) / Tests 73209 passed (73209) (+8 for the new tests: 3 document, 2 smoke, 2 resolve-config, 1 pii_gate); @tale/shared 22 / @tale/ui 124 / @tale/docs 30 / @tale/web 22 files passed. The one red task is test:ui: Test Files 1 failed | 454 passed (455) / Tests 2 failed | 3501 passed (3503) — both app/features/settings/connectors/components/connectors-settings.test.tsx cases, Error: Test timed out in 5000ms. under the 40-task parallel load. Rerun alone with bunx vitest --run --config vitest.ui.config.ts <that file> (the test:ui config) — 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.
  • Root bun run knip:check — exit 0 (the cron-parser configuration hint is present on main as well).
  • Integration proof (run-itest.sh, real Postgres + MinIO, PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7a9 cherry-picked -n for the run only and dropped with git reset --hard afterwards — not in this branch): [itest] 464/466 checks passed across 133/133 lanes, no RUN 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 on main before this campaign) and knowledge: 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 no ORDER BY; this branch touches no documents/corpus file). The checkTasksCollabIntegrity audit-chain serialization truncation the reviewer hit did not recur on this run — it is a lockChainHead retry-budget flake on main, 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.
  • Reproduction of blocking 1 before the fix, on e74e8bd95 with 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 → modified containing [CREDIT_CARD].

Notes for the reviewer

  • Review blocking 2 (the 74-char header on 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 with commitlint at 0 problems / 0 warnings each.
  • The chat filter (lib/chat/guardrails.ts, chat-turn theme's file) has the same shape — pass() after clampMessage on a no-hit — but its dispatcher does not read truncated on a pass and never re-assembles windows, so nothing changes for it here; the widened FilterPassOutcome is backward compatible (optional field), and pass() with no argument still equals { kind: 'pass' } under toEqual.
  • Priced deferral: the image smoke step finding lib-utils-pii-1 proposed (run PatternRegistry.fromDefaults() inside the built image under /app/system/pii) is not in this PR — the compose-stack smoke job in .github/workflows/build.yml is the place for it, outside the platform workspace; the boot probe in backend/main.ts reports the missing tree at error level in every running container instead.
  • Not added: an integration lane that runs a document through applyPiiPolicyForIndexing with a pii_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 in integration-check.ts (≈40k lines) that this theme does not otherwise touch, so it is a follow-up rather than a same-change fix.
  • Overlap with the chat-turn theme (branch fix/chat-guardrails-policy-wiring, worktree fx-chat-governance): it touches lib/chat/* and adds backend/core/chat/guardrails.ts, which imports createScrubber, createTokenizer, Tokenizer, TokenEntry and Scrubber from lib/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 (one console.error per policy per process instead of a console.warn per document) and the boot probe that names a missing tree before the first policy hit.
  • formatFileSize (chat attachment surfaces) now renders 1.5 KB as before but 2048 as 2 KB rather than 2.0 KB, and sizes above 1 GB in GB — the point of converging on one formatter.
  • The oxlint --type-aware run prints nothing on success in this workspace; exit code 0 was checked explicitly.

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.
@larryro

larryro commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Integration proof, run 1 (run-itest.sh, real Postgres + MinIO, PR #3222's aa3d1d7a9 cherry-picked -n for the run only):

[itest] 462/466 checks passed across 133/133 lanes — no RUN TRUNCATED. Four checks red:

  • webdav re-home (protocol + tree + locks + visibility on pg) — red on main before this campaign.
  • knowledge: 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; identically red in the core-lib-providers, sso and sandbox themes' runs (the lane picks a document with no ORDER BY).
  • controlled-record content freeze on updateDocument (REST PATCH) — mark → 500 and, cascading from that unmarked record, REST DELETE inherits record protection (retained history) + audit — ownerApprove → 404. The 500 is PostgresError: could not serialize access due to concurrent update raised from audit_logs/service.ts lockChainHead after the [db] retry budget (5 attempts, 20→160 ms) was exhausted while other lanes wrote audit rows. This branch touches no audit, documents or db-retry file; both probes pass in the documents, core-lib-providers, sso and chat-turn themes' runs on the same base. A second run is in progress and its line follows here.

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).
@larryro larryro changed the title fix(platform): make the PII scrubber load, cover and promise only what it does fix(platform): make the PII scrubber load, scan whole and tell the truth Sep 5, 2026
@larryro

larryro commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Integration proof, run 3 — on the repair tip 170f37f52 (run-itest.sh, real Postgres + MinIO, PR #3222's aa3d1d7a9 cherry-picked -n for the run only and dropped with git reset --hard afterwards):

[itest] 464/466 checks passed across 133/133 lanes — no RUN TRUNCATED. Two checks red, both the known main-side ones:

  • webdav re-home (protocol + tree + locks + visibility on pg) — red on main before this campaign.
  • knowledge: 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 documents theme traced it to a pick with no ORDER BY); this branch touches no documents/corpus file.

The checkTasksCollabIntegrity audit-chain serialization truncation from the review's run did not recur; the 13 sandbox/automation lanes it had cut off all ran and passed.

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.
@larryro
larryro merged commit 3997f6a into main Sep 5, 2026
16 checks passed
@larryro
larryro deleted the fix/pii-scrubber-truth branch September 5, 2026 10:37
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