Skip to content

fix(fi-core): match Python card-number redaction and correlation-ID handling in TypeScript - #806

Open
nik13 wants to merge 8 commits into
devfrom
fix/fi-core-card-luhn-parity
Open

nik13 wants to merge 8 commits into
devfrom
fix/fi-core-card-luhn-parity

Conversation

@nik13

@nik13 nik13 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

With piiRedaction on, the TypeScript @traceai/fi-core card-number redaction works the same way as the Python fi_instrumentation redaction. One shared fixture, spec/pii-redaction/card-and-ids.json, drives both the Jest and pytest suites, so the two SDKs are checked against the same expected output.

  • A digit run becomes <CREDIT_CARD> only when it has a card's length (13 to 19 digits), a card's grouping, and a valid Luhn checksum. Unicode decimal digits (such as full-width digits) count as digits.
  • Values under the correlation keys session.id, user.id, gen_ai.conversation.id and conversation.id, and under their dot-delimited child keys (for example user.id.0), are not scanned for PII. The base64 image cap, explicit hide rules and credential and registered-secret scrubbing still apply to them. Every other key is scanned, including metadata and keys that only look similar (for example user.identity_note).

Changes

  • piiRedaction.ts
    • The card pattern uses Unicode word boundaries. When the grouping is complete, it matches a grouped 17 to 19 digit card before the shorter four-group form.
    • A Luhn and grouping check decides whether a candidate is replaced. Two groupings are accepted: groups of 4 to 6 digits, or groups of 4 with a final group of 1 to 4 digits.
    • When a valid 16-digit card is directly followed by another number, only the card part is replaced, so a phone number after a card is matched by the phone pattern.
    • The phone pattern does not match the tail of a longer identifier. A phone number that follows a literal \n, \t or \r escape in serialized JSON is matched.
    • The quick pre-check accepts any Unicode decimal digit.
  • maskingRules.ts: redactValue(config, value, key?) applies the image cap first. It skips the PII pass only for the four correlation key prefixes above. Values with no key (exception text, status description) are scanned.
  • FISpan.ts and export-privacy.ts pass each attribute's key into redactValue, so the correlation-key rule applies to early native attribute writes and on export.
  • Card redaction retries from each later digit-group start, so a valid card number that follows a short number, date or time (qty 2 4111…, 2026-11-30 10:15 4111…, order 12 4111 1111 1111 1111) is still redacted. Long IDs and timestamps that fail the checksum are still kept. The same fix is in the Python pii_redaction.py.
  • International phone numbers written with a leading + (+447911123456, +44 7911 123456) are redacted whole, in both SDKs. Numbers followed by a letter or _ (5551234567x, +447911123456_) are still kept, as identifiers.
  • Tests:
    • piiCardParity.test.ts and a parametrised pytest case, both driven by the shared fixture.
    • Span, event and link attribute cases in eventPiiRedaction.test.ts.
    • startSpanContext.test.ts expects an unchanged correlation ID to be bound with PII redaction on, and a session ID rewritten by the image cap to stay unbound.
    • The Google ADK native privacy tests expect a 13-digit millisecond timestamp, which fails the Luhn check, to be kept as is. Card numbers and emails in the same payload are redacted.
  • CI: fi-core-typescript-tests.yml and fi-core-python-compat.yml also run on changes under spec/pii-redaction/**, for both push and pull_request.
  • typescript/packages/fi-core/CHANGELOG.md: a Fixed entry under Unreleased.

Tests

All cloud runs used a throwaway VM, with networking limited to loopback for the CI-equivalent runs:

  • TypeScript card and correlation-ID tests (piiCardParity, eventPiiRedaction, written test-first): 26 of 26 passed.

  • TypeScript PII suites (piiRedaction, piiQuickCheckSuperset, piiEmailResourceBound, eventPiiRedaction): 109 of 109 passed.

  • startSpanContext.test.ts: 16 of 16 passed.

  • fi-core node tests against packed OTel SDK 2.0.1 and 2.12.0: 144 of 144 passed on each.

  • fi-semantic-conventions Jest: 124 of 124 passed.

  • Google ADK native tests: 31 of 31 passed. The ADK native privacy wire check (ADK 2.4.0, numeric-pii mode) exited 0.

  • Python tests/test_pii_redaction.py and tests/test_config.py: 128 passed. The full Python core selection: 5712 passed, 25 skipped.

  • The shared fixture spec/pii-redaction/card-and-ids.json gains 31 rows for these cases, including date and time prefixes, grouped cards, cards followed by a short number, separated and compact international numbers for four countries, and the identifier-suffix exclusions. The Jest and pytest fixture tests both run them.

  • piiPrefilterParity.test.ts (new): snapshot tests that pin redaction output to this PR's redactor. They cover every row of spec/pii-redaction/card-and-ids.json, both directly and through keyed masking, the existing scalar and phone examples, and 400 fixed-seed numeric strings with Unicode digits and near-boundary card lengths. The snapshot's original entries are unchanged. The only additions are 31 pairs for the new fixture rows: 22 newly redacted cards or phones, and 9 controls that stay as they were.

  • Full fi-core Jest on a throwaway VM at the base commit and at this PR's redactor: only timing limits failed, in the two image-cap performance suites. The interleaved A/B below shows those failures are noise (6 of 15 runs on base, 8 of 15 on the PR, medians within ±2.6%). Making those tests stable is tracked in fi-core: image-cap decode performance tests give the same result on every run #807. resourceDetection.test.ts needs a passwd entry for the container's mapped UID, and passed (5 of 5) once one was provided.

  • On a throwaway VM at this head: full fi-core Jest 168 of 168 suites (6,067 tests, 13 existing skips, 3 parity snapshots), Python PII tests 159 passed and the Python core selection 5,747 passed (21 existing skips), fi-core node tests against packed OTel SDK 2.0.1 and 2.12.0 144 of 144 each, and fi-semantic-conventions 124 of 124.

PR CI is the test of record.

Performance

Interleaved A/B on one idle VM, same Node 22.23.4, 15 runs per side, base cb04244b vs this PR's redactor (evidence branch evidence/traceai-806-perf-1130 @ 6d04c5a9):

Case Base median PR median Change
Image cap, mixed escapes (CPU) 165.9 ms 166.8 ms +0.5%
Image cap, many data-URL headers (CPU) 122.6 ms 125.4 ms +2.3%
PII numeric non-match, 16 repeats (wall) 0.229 ms 0.237 ms +3.6%
PII numeric non-match, 1,024 repeats (wall) 0.519 ms 0.781 ms +50.5%
PII numeric non-match, 8,192 repeats (wall) 2.725 ms 4.523 ms +66.0%
PII email local-part boundaries, no domain (wall) 9.846 ms 13.296 ms +35.0%
PII many accepted email addresses (wall) 13.399 ms 16.795 ms +25.4%

The PII rows are from a second interleaved A/B on this head, after the card and phone fixes: base cb04244b, n=15 per arm, evidence evidence/traceai-806-card-e164-1130 @ b7566944. The image-cap rows are from the first A/B.

  • Image cap: every case is within ±2.6%. Timing-limit failures are about equal on both sides. The image-cap path does not call the new card or correlation-key logic.
  • Numeric text: a CPU profile puts the added time in the card-candidate pattern and the Unicode phone pattern inside redactPiiInString (piiRedaction.ts:183–194). Long digit runs are real card candidates, so they are checked. The common short ID or counter shape (16 repeats) is +3.6%.
  • Email rows: no separate profile was taken at this redactor. Their cost is inferred to come from the same two patterns scanning the text.
  • A card/phone pre-filter was tried and rejected. Measured against the same base in a separate A/B (evidence/traceai-806-prefilter-1130 @ 3f431152), it gave numeric 1,024 +222.5%, numeric 8,192 +72.7% and many accepted addresses +46.0%. A profile (evidence/traceai-806-emailprof-1130 @ b1290633) put the extra time in the pre-filter's own length scan.
  • A single-pass candidate scanner that brings these rows within 10% of base, with the parity snapshots unchanged, is tracked in fi-core: PII redaction scans long numeric and address-heavy text in a single pass #808.

Behaviour change

For users and operators with piiRedaction enabled in TypeScript:

  • A card number that follows a short number, date or time, and an international phone number written with a leading +, are now redacted in both SDKs. Numbers followed by a letter or _ are still kept.
  • A 13 to 19 digit number becomes <CREDIT_CARD> only when its checksum is valid and its grouping looks like a card. Long numeric IDs, millisecond timestamps and similar numbers in exported text that fail the checksum are kept as they are, as in Python. A card-grouped 13 to 19 digit number that passes it is still replaced.
  • session.id, user.id, gen_ai.conversation.id, conversation.id and their dot-delimited child keys skip PII redaction, so values that look like an email address or card number are kept, and session binding uses the original ID. The image cap, explicit hide rules and credential and registered-secret scrubbing still apply to these keys.
  • With piiRedaction off, nothing changes.

Linked: none
AI use: Claude Code (Opus) coordinated; a cloud worker wrote the change test-first on a throwaway VM and a review agent checked it.
Docs: none (the fi-core CHANGELOG entry covers it; no public option or API changed)

🤖 Generated with Claude Code

nik13 and others added 5 commits November 29, 2026 23:01
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…andling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nik13

nik13 commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

One rerun of the failed job: Core Python 3.11 OTel floor (tracing) failed on a single Python test, tests/test_plain_channel_isolated_sender.py::test_a_caller_session_flipped_during_a_thousand_exports_puts_no_marker_byte_on_a_proxy[0.0]. It hit ConnectionResetError(104, 'Connection reset by peer') from the test's local proxy socket; the other 5710 tests passed. This PR changes only the TypeScript PII redaction package, and that check passed on dev's recent runs. This is the one rerun; if it fails again I'll treat it as a real failure and look into it.

@nik13

nik13 commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my rerun note above: this PR is not TypeScript-only. It also adds test_card_and_identifier_policy_parity to python/tests/test_pii_redaction.py, driven by the shared spec/pii-redaction/card-and-ids.json fixture. It also adds spec/pii-redaction/** to the path filters of the Python compatibility and TypeScript test workflows. The test that failed, tests/test_plain_channel_isolated_sender.py, is in a different module and uses neither the redaction code nor that fixture, and the rerun passed. A timing comparison of the image-cap Jest cases between this head and the base is still running; the Tests section will be updated with the result.

Record the redactor's output for the shared card and identifier fixture
(direct and through keyed masking), the existing scalar and phone
examples, and 400 fixed-seed numeric strings, so a later speed-up has
to keep every result the same. Provider-key-shaped inputs are built at
runtime instead of written as literals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nik13

nik13 commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Merge-gate review at head 3c9afcf1: changes needed. I reproduced two redaction regressions against the merge-base cb04244b. In each, the base redacts the value and this head exports it unredacted. Both were confirmed independently.

1. A Luhn-valid card that follows a short number is no longer redacted

Location: typescript/packages/fi-core/src/trace/trace-config/piiRedaction.ts (CARD_CANDIDATE generic alternative + replaceCard, diff lines ~417-463)

Evidence: I ran the real redactPiiInString from head 3c9afcf and from merge-base cb04244 (node --experimental-strip-types; the file has no imports). 'qty 2 4111111111111111': base 'qty <CREDIT_CARD>', head 'qty 2 4111111111111111'. 'item 3 5555555555554444 thanks': base 'item <CREDIT_CARD> thanks', head unchanged. '2 378282246310005': base '<CREDIT_CARD>', head unchanged. '10:30 4111111111111111': base '10:<CREDIT_CARD>', head unchanged. '2026-11-30 4111111111111111': base '2026-11-<CREDIT_CARD>', head unchanged, so a timestamped log line leaks the whole card. Grouped: 'order 12 4111 1111 1111 1111': base 'order <CREDIT_CARD> 1111', head unchanged. Cause: the greedy generic candidate takes the leading short number, so the candidate is longer than one card (for example '2 4111111111111111' or '30 4111111111111111'). That candidate fails the grouping or Luhn check, replaceCard falls back only to a four-group prefix, and String.replace resumes after the whole match, so the card inside is never tried. The body's Behaviour change section says a card-grouped number that passes the check 'is still replaced', and this leak is not disclosed. The untouched Python _redact_credit_cards has the same gap, so parity does not cover it: in TypeScript this is a new false negative.

Fix: When a candidate fails the card check, still replace any Luhn-valid, card-grouped 13-19 digit run inside it, for example by re-trying from each later group start or with a scan anchored at each digit-group boundary. Make the same change in the Python redactor so the shared fixture still holds for both SDKs. Add rows to spec/pii-redaction/card-and-ids.json for a short number before a card, both ungrouped ('qty 2 4111111111111111') and grouped ('order 12 4111 1111 1111 1111'), and for a date or time prefix. The piiPrefilterParity snapshot will then need re-recording.

2. International phone numbers without separators are no longer redacted at all

Location: typescript/packages/fi-core/src/trace/trace-config/piiRedaction.ts (phone pattern with (?<!WORD) lookbehind, diff lines ~485-489)

Evidence: Real redactPiiInString, base cb04244 vs head 3c9afcf: '+447911123456' base '+44<PHONE_NUMBER>', head '+447911123456'. '+919876543210' base '+9<PHONE_NUMBER>', head unchanged. 'call +447911123456 now' base 'call +44<PHONE_NUMBER> now', head unchanged. Base redacted the last 10 digits. Head rejects every start position inside the digit run, so the whole number is exported. The body frames the phone change as 'does not match the tail of a longer identifier'. Dropping real E.164 numbers that the base redacted (all but the country code) is not disclosed. US '+15551234567' is still redacted.

Fix: Allow a match to start after a '+' plus country-code digits, or add an E.164 alternative such as +\p{Nd}{7,15} at a word boundary, so non-US international numbers are still redacted. Keep the identifier-suffix exclusion for letter or underscore prefixes. Add fixture rows for '+447911123456' and '+919876543210'. If Python is meant to match, change it the same way.

The new parity test is good: the snapshot holds real outputs that would fail on any change. It will need re-recording after these fixes. CI was still running at review time, with nothing failing.

nik13 and others added 2 commits November 29, 2026 23:13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nik13

nik13 commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Merge-gate review at head 3bbfec9c: changes needed.

Both regressions from the last round are fixed in TypeScript and Python. I checked this by running both redactors. A fuzz run of about 28k cases showed TypeScript and Python agree on every case. Two more TypeScript regressions against the merge-base cb04244b were reproduced and confirmed independently:

1. TS: an ungrouped Luhn-valid card right after a serialized \n, \t or \r escape is now exported in full

Location: typescript/packages/fi-core/src/trace/trace-config/piiRedaction.ts: CARD_CANDIDATE (lookbehind (?<!WORD) has no (?<=\\[ntr]) alternative), together with the new (?<!WORD) lookbehind on the PII_PATTERNS phone regex

Evidence: I ran redactPiiInString through node --experimental-strip-types on base cb04244 and on head. Each line shows input, then base output, then head output.

  • '{"content":"My card is\n4111111111111111"}': base '...\n41111<PHONE_NUMBER>"}', head '...\n4111111111111111"}'.
  • 'Card:\n4111111111111111': base 'Card:\n41111<PHONE_NUMBER>', head unchanged (full number).
  • '\t5555555555554444': base '\t555555<PHONE_NUMBER>', head unchanged.
  • '\r378282246310005': base '\r37828<PHONE_NUMBER>', head unchanged.
    At base the phone pattern had no lookbehind, so it masked the last 10 to 11 digits and left only the first 5 or 6 visible. Head prints the whole card number. JSON.stringify of message content (input.value and similar) produces exactly this literal backslash-n form, and redactValue scans the whole string. The PR's own snapshot already pins '\n5551234567' for phones, so serialized escapes are in scope, but there is no card row for them. The body discloses the phone escape handling only. The grouped form ('\n4111 1111 1111 1111') also leaked at base, so it is not counted here. Python base and head both have the same gap, so this is a TS-only regression of the same kind as the last send-back (qty 2 4111..., where Python base also leaked).

Fix: Add the (?:(?<!WORD)|(?<=\\\\[ntr])) start alternative to CARD_CANDIDATE in TS. Mirror it in Python _CREDIT_CARD_RE, which has the same pre-existing gap. Add shared fixture rows: ungrouped, spaced and hyphenated cards after \n, \t and \r, plus a JSON-serialized message example. Update the parity snapshot with them.

2. TS: a plus-prefixed E.164 number followed by a space and another number is no longer redacted at all

Location: typescript/packages/fi-core/src/trace/trace-config/piiRedaction.ts: INTERNATIONAL_PHONE trailing guard (?!${WORD}|[ .-]${DECIMAL}) (the same guard is in Python _INTERNATIONAL_PHONE_RE), plus the new phone lookbehind

Evidence: Same harness. Each line shows input, then base output, then head output.

  • '+447911123456 2026-11-30': base '+<CREDIT_CARD>-11-30', head '+447911123456 2026-11-30'.
  • '+447911123456 1234': base '+<CREDIT_CARD>', head unchanged.
  • '+33612345678 12345': base '+<CREDIT_CARD>', head unchanged.
  • 'Call +4915123456789 1x': base 'Call +<CREDIT_CARD> 1x', head unchanged.
    Why it fails: the international pass lets a following ' ' extend the match. Once the total passes 15 digits it cannot stop early, because the lookahead rejects a following ' '. The card pass then sees a Luhn-failing run, and the bare phone pattern can no longer match the tail because of the new word lookbehind. The body says plus-prefixed numbers 'are redacted whole' and lists only letter or '_' suffixes as kept, so this is not disclosed. Python base also leaked these, and TS head now equals Python head on them.

Fix: Let the international match end before a ' ' delimiter, for example by trying the longest valid phone that is followed by a non-word character or by whitespace or punctuation and another number, instead of rejecting outright. Keep the identifier-suffix exclusions ('x' and '_'). Apply the same change in Python and add shared fixture rows for a plus-prefixed number followed by a date, time or short count.

Scope for the next push: fix these two, add the fixture rows, and update the snapshot. After that, any further edge case where the base only redacted by accident gets a follow-up issue rather than another round here. The exceptions are a full Luhn-valid card number or a full E.164 number that the base hid and the head exports.

This branch has not been deployed

No deployments
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