Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3.8k
fix(pii): mask offloaded large payloads chunk-by-chunk instead of aborting at 16MB#5810
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ab8db29
fix(pii): mask offloaded large payloads chunk-by-chunk and retry tran…
TheodoreSpeaks b7c66c0
fix(pii): retry runtime timeouts and socket closes in mask-batch chunks
TheodoreSpeaks e836d99
fix(pii): gate the spaCy fast path on entities the loaded models can …
TheodoreSpeaks 7d05d24
fix(pii): hydrate oversized-chunk manifests serially, not just single…
TheodoreSpeaks e89845f
fix(pii): serialize oversized hydrations globally across nested redac…
TheodoreSpeaks bd2a30a
fix(pii): fail fast on a null mask-batch body; use sleep() in gate test
TheodoreSpeaks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| import { sleep } from '@sim/utils/helpers' | ||
| import { backoffWithJitter, parseRetryAfter } from '@sim/utils/retry' | ||
| import type { GuardrailsMaskBatchResult } from '@/lib/api/contracts' | ||
| import { generateInternalToken } from '@/lib/auth/internal' | ||
| import { env } from '@/lib/core/config/env' | ||
| @@ -18,6 +20,60 @@ import type { CustomPiiPattern } from '@/lib/guardrails/pii-entities' | ||
| */ | ||
| const CHUNK_CONCURRENCY = env.PII_MASK_CHUNK_CONCURRENCY ?? 64 | ||
| /** | ||
| * Per-chunk retry budget for transient failures (network errors, 408/429/5xx). | ||
| * A large payload fans out into many chunk requests, so a single blip — an ALB | ||
| * 502 during a deploy, a Presidio pod restart — must not fail the whole | ||
| * redaction (and, on the execution-altering stages, abort the run). With the | ||
| * default 500ms→30s jittered backoff this rides out ~2 minutes of outage per | ||
| * chunk before giving up. Deterministic failures (4xx, shape mismatches) throw | ||
| * immediately. | ||
| */ | ||
| const MAX_CHUNK_ATTEMPTS = 8 | ||
| const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]) | ||
| class MaskChunkHttpError extends Error { | ||
| constructor( | ||
| message: string, | ||
| readonly status: number, | ||
| readonly retryAfterMs: number | null | ||
| ) { | ||
| super(message) | ||
| this.name = 'MaskChunkHttpError' | ||
| } | ||
| } | ||
| function isRetryableChunkError(error: unknown): boolean { | ||
| if (error instanceof MaskChunkHttpError) { | ||
| return RETRYABLE_STATUSES.has(error.status) | ||
| } | ||
| // A rejected fetch (connection refused/reset, DNS, socket drop) is transient — | ||
| // Node wraps these in TypeError('fetch failed'). Runtime-level request | ||
| // timeouts (undici's default 300s headers/body timeout, Bun's TimeoutError) | ||
| // and mid-flight socket closes surface with their own names/codes per runtime; | ||
| // all are congestion or connection churn, not a deterministic failure: a chunk | ||
| // queued behind a saturated Presidio fleet must retry, not fail the payload. | ||
| if (error instanceof TypeError) { | ||
| return true | ||
| } | ||
TheodoreSpeaks marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| const { name, code } = (error ?? {}) as { name?: unknown; code?: unknown } | ||
| if (name === 'TimeoutError' || name === 'HeadersTimeoutError' || name === 'BodyTimeoutError') { | ||
| return true | ||
| } | ||
| return ( | ||
| typeof code === 'string' && | ||
| [ | ||
| 'ECONNRESET', | ||
| 'ECONNREFUSED', | ||
| 'EPIPE', | ||
| 'ETIMEDOUT', | ||
| 'ConnectionClosed', | ||
| 'ConnectionRefused', | ||
| ].includes(code) | ||
| ) | ||
| } | ||
| /** | ||
| * Mask PII across many strings via the internal app-container endpoint. | ||
| * | ||
| @@ -29,8 +85,10 @@ const CHUNK_CONCURRENCY = env.PII_MASK_CHUNK_CONCURRENCY ?? 64 | ||
| * concurrency, so a large payload fans out rather than serializing; order is | ||
| * preserved, so the returned array matches `texts` length. | ||
| * | ||
| * Rejects on any non-2xx, timeout, or shape mismatch so the caller can apply | ||
| * its own fail-safe (scrubbing rather than leaking). | ||
| * Transient chunk failures (network errors, 408/429/5xx) retry with jittered | ||
| * backoff (see {@link MAX_CHUNK_ATTEMPTS}); only a deterministic failure or an | ||
| * exhausted retry budget rejects, so the caller can apply its own fail-safe | ||
| * (scrubbing rather than leaking). | ||
| */ | ||
| export async function maskPIIBatchViaHttp( | ||
| texts: string[], | ||
| @@ -64,8 +122,29 @@ async function postChunk( | ||
| language: string | undefined, | ||
| customPatterns: CustomPiiPattern[] | undefined | ||
| ): Promise<string[]> { | ||
| // Mint per request: a single token (5min TTL) can expire mid-batch when a | ||
| // large execution fans out into many sequential chunk requests. | ||
| for (let attempt = 1; ; attempt++) { | ||
| try { | ||
| return await postChunkOnce(url, texts, entityTypes, language, customPatterns) | ||
| } catch (error) { | ||
| if (attempt >= MAX_CHUNK_ATTEMPTS || !isRetryableChunkError(error)) { | ||
| throw error | ||
| } | ||
| const retryAfterMs = error instanceof MaskChunkHttpError ? error.retryAfterMs : null | ||
| await sleep(backoffWithJitter(attempt, retryAfterMs)) | ||
| } | ||
| } | ||
| } | ||
| async function postChunkOnce( | ||
| url: string, | ||
| texts: string[], | ||
| entityTypes: string[], | ||
| language: string | undefined, | ||
| customPatterns: CustomPiiPattern[] | undefined | ||
| ): Promise<string[]> { | ||
| // Mint per attempt: a single token (5min TTL) can expire mid-batch when a | ||
| // large execution fans out into many sequential chunk requests or a chunk | ||
| // spends its retry budget waiting out an outage. | ||
| const token = await generateInternalToken() | ||
| // boundary-raw-fetch: internal server-to-server call to the app container (internal JWT auth, configurable base URL) | ||
| @@ -80,11 +159,15 @@ async function postChunk( | ||
| if (!response.ok) { | ||
| const detail = await response.text().catch(() => '') | ||
| throw new Error(`PII mask-batch request failed (${response.status}): ${detail.slice(0, 200)}`) | ||
| throw new MaskChunkHttpError( | ||
| `PII mask-batch request failed (${response.status}): ${detail.slice(0, 200)}`, | ||
| response.status, | ||
| parseRetryAfter(response.headers.get('retry-after')) | ||
| ) | ||
| } | ||
| const data = (await response.json()) as GuardrailsMaskBatchResult | ||
| if (!Array.isArray(data.masked)) { | ||
| const data = (await response.json()) as GuardrailsMaskBatchResult | null | ||
| if (!data || !Array.isArray(data.masked)) { | ||
| throw new Error('PII mask-batch returned an unexpected result') | ||
| } | ||
| return data.masked | ||
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.
Uh oh!
There was an error while loading. Please reload this page.