Skip to content

Feat/generate report - #1

Merged
Sandip117 merged 6 commits into
mainfrom
feat/generate-report
Nov 4, 2026
Merged

Sandip117 merged 6 commits into
mainfrom
feat/generate-report

Conversation

@Sandip117

@Sandip117 Sandip117 commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

This PR closes https://github.com/HARBOR-Medical-AI/HARBOR-planning/issues/170

  1. Document the sensitivity of the audit log and recommended access controls for its feed node
    
  2. Write MAINTENANCE.md (dependency upgrade procedure, tests to re-run) and a README covering inputs, outputs, options and usage
    
  3. Keep stdout and stderr free of PHI. Log file hashes and counts, not identifiers or original paths
    
  4. Return a non-zero exit code on leaks or incomplete pairing (--failOnLeak)
    
  5. Identify what changed per file: tags changed, removed or retained, with before and after values
    
  6. Record the identifier mapping (PatientID, PatientName), the UID mapping (Study, Series, SOP Instance) and date changes
    
  7. Scan the anonymized output for leaked original values and flag any found
    
  8. Flag unmatched, skipped, failed or non-DICOM files, so the log accounts for every input file
    
  9. create or modify e2e tests
    
  10. create or modify unit tests
    

@Sandip117
Sandip117 requested a review from jbernal0019 October 26, 2026 18:51

@jbernal0019 jbernal0019 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Sandip117

Code Review

Scope reviewed

  • All 16 files in the diff against main.
    • Read in depth: audit_engine.py, dicom_audit.py, the four new test modules, README.md, MAINTENANCE.md, Dockerfile, setup.py, requirements.txt and ci.yml.
    • Checked briefly: the LICENSE year change, and the removal of the template files app.py, bootstrap.sh and tests/test_example.py.
  • Checked each requirement in HARBOR-planning#170 against the code.
  • Built the dev image and ran the suite the way CI does (CI=true, read-only mount). All 100 tests pass, including the e2e tests that drive the real pl-dicom_anonymize 1.2.0.
  • Coverage is 96% on both audit_engine.py and dicom_audit.py.
  • Ran the anonymizer and then the audit by hand in the container on test pairs. The cases were patient-named folders, an anonymizer that stops early, a truncated output, a short name component, a private OB blob and a DICOM file with no preamble.

Verdict

Requesting changes.

This is careful work. The docs are thorough, the per-file accounting is complete and the job log stayed free of PHI in every run I tried. Pairing, the UID mapping and --failOnLeak all behaved as described. Leaks in folder names and in deidentification_summary.json were caught.

Three problems need fixing first. The audit can pass a broken output file. It misses names kept in private binary tags. And it flags false leaks often enough that --failOnLeak will fail clean runs.

Should fix before merge

1. A truncated anonymized file passes as audited [OK].

  • Where: audit_engine.py:135-149 and dicom_audit.py:517-521.
  • What I saw: I cut an anonymized file to 300 bytes. The File Meta was intact but the body was gone. read_dicom loaded it as a dataset with 0 elements. The audit then logged 74 elements as "removed", found no leaks because there was nothing left to scan, and reported pixel_integrity: absent_in_deidentified.
  • Why it matters: none of that raised a finding, so --failOnLeak still exits 0. The read_dicom docstring says this exact case is rejected. Only "mismatch" ever becomes a finding. absent_in_deidentified and absent_in_identified never do.
  • Suggested fix:
    • Treat both absent_* results as integrity errors unless --skipPixelCheck is set.
    • In read_dicom, reject a dataset that is empty or has no SOPInstanceUID.
    • Add tests for a truncated output and for an output with PixelData stripped.

2. Names in private OB/OW elements are never scanned.

  • Where: _text_values in audit_engine.py:366-376 only decodes UN.
  • What I saw: with dicom_anonymize --keepPrivateTags, a private (0029,1110) OB holding VANCE^ORRIN reached the output unchanged and the file was reported [OK].
  • Why it matters: vendor blobs such as Siemens CSA headers are OB in explicit VR files. The README says private tags are scanned. This only matters when private tags are kept, but we don't know yet how the plugin will be deployed. If --keepPrivateTags turns out to be unused in practice, this could drop to Minor.
  • Suggested fix: decode OB/OW in odd groups as latin-1 the same way UN is. If that's too noisy, at least raise a coverage warning when private binary elements exist and were not scanned.

3. Name components are matched as plain substrings, which gives false leaks.

  • Where: phi_needles and token_in in audit_engine.py:316-395.
  • What I saw: two real false leaks from one run.
    • Zed^Quill produced the token ZED. It matched inside ANONYMIZED, the text dicom-anonymizer writes into replaced elements. That flagged InstitutionName, StationName and ContrastBolusAgent.
    • Ann^Lee produced ANN. It matched in the retained Manufacturer value ACME SCANNER CO.
  • Why it matters: both runs exit 1 under --failOnLeak. Any name part that is a substring of ANONYMIZED (ZED, NYM, NON, ANON) will flag every replaced element. People will learn to ignore the flag.
  • Suggested fix:
    • Match name components on word boundaries.
    • Keep plain substring matching for full values.
    • Drop tokens that occur inside the anonymizer's replacement string.
    • Add a test with Zed and one with Ann.

Minor

  • A hashing error can crash the run and put a path in the log (dicom_audit.py:335-336). file_sha256(ip) and file_sha256(ap) run after the try in audit_pair. If a file vanishes or loses read permission between the read and the hash, you get a traceback with the full original path. Patient-named folders would show up there. The run also stops before audit_summary.json is written. Moving both calls inside the try fixes it.
  • A DICOM file without the 128-byte preamble is only info (audit_engine.py:119-126). The anonymizer skips it for the same reason, so a real image with PHI never gets de-identified. The audit lists it as not_dicom / info, and --failOnLeak does not care. A dcmread(force=True) probe could tell "not DICOM" apart from "DICOM without preamble" and report the second as a warning.
  • Untested paths. These are the coverage gaps that matter:
    • The unreadable status (dicom_audit.py:326-329). It's the "failed" case the issue asks to flag.
    • Sequence items_added / items_removed (audit_engine.py:263-268).
    • The "shifted, inconsistent offsets" date branch (audit_engine.py:634).

Worth noting

  • The CI change turns on the build job for pushes to main, but needs: [ test ] is still commented out. A push to main will build and push :latest even when tests fail. That line comes from the template, but this PR is the one that turns the build on.
  • Text needles come only from the same file's top-level elements. Patient B's name in patient A's header, or an ID inside OtherPatientIDsSequence, is not searched for. Only UIDs are checked across files. This would be worth a line under Limitations in the README.
  • The 12-character path hashes in the job log are unsalted. Someone with a list of likely names could match them to patient-named folders. This matches what pl-dicom_anonymize already prints, but the README should say so.

Nits

  • The PR title is still the branch name, and items 11 and 12 in the description are empty.
  • The test job uses actions/checkout@v4 while build uses @v6.

@Sandip117
Sandip117 requested a review from jbernal0019 October 28, 2026 18:17
@Sandip117

Copy link
Copy Markdown
Contributor Author

@jbernal0019
Thanks for the thorough review. All three requested changes are addressed in eaef269:

  1. Truncated/pixel-less output: read_dicom now rejects files that end mid-element (declared vs. read length, last-element end vs. file size), short native PixelData, and datasets without SOP UIDs. PixelData present on only one side is a new error (pixel_missing), including with --skipPixelCheck. Cutting a test file at every byte, only element-boundary cuts read as valid; those are caught by the pixel-presence check and the diff.

  2. Private OB/OW: odd-group OB/OW and EncapsulatedDocument are decoded and scanned; remaining standard binary elements (including nested icon PixelData) are reported as binary_not_scanned.

  3. False positives: single-word values match only as whole words. Your ANN/ZED case is a regression test; fused names (DoeJane) are a documented miss.

Minor items: hashing moved inside the per-file guard, plus a top-level guard (class + fixed text, exit 2); preamble-less DICOM → dicom_without_preamble (pairing error); tests added for the unreadable path, items_added and the no-dates branch; needs: [test] restored and checkout aligned; README covers unsalted path hashes and cross-file text.

One more I found while fixing these: pydicom’s lazy validation was quoting invalid values (e.g. a UID spelling a name) into the job log. Warnings and read validation are now silenced for the whole run, with an e2e test.

@jbernal0019 jbernal0019 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Sandip117

Code Review follow-up (68b6d44)

Scope reviewed

  • The follow-up commit 68b6d44 (ab63f34..68b6d44), against the three should-fix items and the minor items from the first review. That covers 9 files: audit_engine.py, dicom_audit.py, the three test modules, README.md, MAINTENANCE.md, ci.yml and .gitignore.
  • Built the dev image and ran the suite the way CI does. All 135 tests pass. Coverage is 96% on audit_engine.py and 97% on dicom_audit.py.
  • Ran the real pl-dicom_anonymize and then the audit in the container. I repeated every case from the first review and added:
    • an SR with no PixelData
    • a JPEG 2000 file
    • a true leak in a retained element
    • a native YBR_FULL_422 file
    • patient folders with a digit attached to the name
  • Cut one anonymized CT at 111 offsets, and once more with PixelData removed cleanly.

Verdict

Requesting changes.

One regression needs fixing before merge. It's a small fix. Two smaller ones can then follow.

The three original items are fixed. I confirmed each in the container:

  • Truncated output. Every cut is caught. Mid-element cuts read as unreadable. A clean cut before PixelData raises pixel_missing, with or without --skipPixelCheck.
  • Private OB/OW. VANCE^ORRIN in a private (0029,1110) OB is now flagged.
  • False leaks. ZED and ANN no longer match inside ANONYMIZED or ACME SCANNER CO. True leaks such as a surname in Manufacturer and the Doe_Johnathan/ folder are still caught.

The minor items are done too:

  • A file without the preamble is now a pairing error.
  • needs: [ test ] is back in the CI build job.
  • Hashing is inside the per-file guard.
  • The README covers unsalted path hashes and cross-file text.

The pydicom warning fix you found on your own is a good catch and it has a test.

Should fix before merge

1. Names attached to a digit are no longer caught.

  • Where: _WORDCHAR at audit_engine.py:497, used by token_pattern at line 518.
  • Problem: the whole-word boundary treats digits as word characters. A name token next to a digit no longer matches. The old substring match caught these.
  • What I saw: the anonymized tree kept the folders SMITH1/ and DOE20240301/ for patients Smith and Doe. leaks.csv was empty and the run passed. Folders like these are common in exports. The same applies to IDs like scanMRN001. The README lists DoeJane and JDoe as known misses but says nothing about digits.
  • Suggested fix:
    • For tokens made only of letters use a letters-only boundary ([^\W\d_]).
    • Keep the current boundary for tokens that contain digits.
    • Add a path test with SMITH1/.

Minor

2. A few trailing zero bytes make a valid file unreadable.

  • Where: check_not_truncated in audit_engine.py:172.
  • What I saw: I appended zero bytes to a good CT, once on the anonymized side and once on the original side.
    • 1 to 4 bytes: the pair is unreadable with TruncatedDicomError, and --failOnLeak exits 1.
    • 8 or 16 bytes: the pair is audited normally because pydicom reads them as empty (0000,0000) elements.
  • Why it matters: some writers and transfer tools leave stray trailing padding. The file is not truncated, but the audit says it is.
  • Suggested fix: if everything after the last complete element is zero bytes, accept it. Add a test with 1 and 3 trailing bytes.

3. A valid native YBR_FULL_422 file is rejected as truncated.

  • Where: expected_pixel_bytes in audit_engine.py:148.
  • Problem: it computes rows × columns × samples × bytes per sample. With 4:2:2 subsampling (YBR_FULL_422, YBR_PARTIAL_422), 3 samples per pixel take only 2 samples' worth of bytes, so the file is shorter than this formula expects.
  • What I saw: pl-dicom_anonymize de-identified a conformant 16×16 8-bit file without trouble. The audit then marked the pair unreadable with TruncatedDicomError and exited 1 under --failOnLeak.
  • Why it's minor here: the plugin is likely meant for CT and MR, which rarely use this layout. It would matter for ultrasound or for color secondary captures stored in a CT or MR study.
  • Suggested fix: use 2 samples per pixel when PhotometricInterpretation ends in _422, and add a test with a native _422 file.

Worth noting

  • EncapsulatedDocument is now counted as scanned (audit_engine.py:467). The text in an encapsulated PDF is usually Flate-compressed, though, so a latin-1 scan will rarely find a name in it. Listing it under binary_not_scanned or adding a line to the README limitations would avoid false confidence. I haven't tested this.
  • MAINTENANCE.md says plainly that check_not_truncated depends on pydicom's private RawDataElement internals, and it names the test that guards that. Good. That test will be the first thing to break on a pydicom upgrade.
  • Each pair is now loaded in full (pixels included) and then read again for hashing. That's fine for normal studies but heavy for multi-GB multiframe files.

Nits

  • The PR comment points to eaef269. Updating it to 68b6d44 would help anyone reading the thread later.

@Sandip117
Sandip117 requested a review from jbernal0019 November 2, 2026 15:58

@jbernal0019 jbernal0019 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Sandip117

Code Review

Scope reviewed

  • The commit 9483a5c (68b6d44..9483a5c) against the review of 68b6d44. It touches audit_engine.py, README.md, tests/test_audit.py and tests/test_engine.py.
  • Built the dev image and ran the suite the way CI does. All 155 tests pass. Coverage is 96% on audit_engine.py and 97% on dicom_audit.py. Ten of the new tests fail against 68b6d44, so they do exercise the fixes.
  • Ran the real pl-dicom_anonymize and then the audit in the container for each fix. Then I tried to break the fixes:
    • 372 cuts of an anonymized CT
    • cuts into all-zero PixelData
    • padding on explicit VR, implicit VR and JPEG 2000 files
    • 4:2:2 at 16-bit and multi-frame
    • patient names made only of hex letters
    • short surnames against retained MR values
    • an SR ending in an undefined-length sequence

Verdict

Requesting changes.

One false failure needs fixing before merge because it makes a clean run fail under --failOnLeak and nothing can silence it. Item 1 is a side effect of the boundary rule I suggested last round. Item 2 under Minor came in with 68b6d44 and I missed it in the last review.

All three requested fixes do what they should. I confirmed each in the container:

  • Names next to a digit. SMITH1/, DOE20240301/ and HALE2 MEDICAL are flagged. ZED and ANN still don't match inside ANONYMIZED or SCANNER.
  • Trailing padding. Trailing zeros of any length are accepted on either side. Non-zero tails are rejected on non-encapsulated files. None of the truncated files got through, including cuts into all-zero PixelData.
  • 4:2:2. YBR_FULL_422 and YBR_PARTIAL_422 pass, including 16-bit and multi-frame. Short 4:2:2 and short RGB data are still rejected.

The README now covers encapsulated PDFs, which resolves that note.

Should fix before merge

1. A name made only of hex letters matches inside path hashes.

  • Where: the letters-only branch of token_pattern in audit_engine.py:544, reached through scan_anonymized_tree in dicom_audit.py:391.

  • Problem: digits now count as boundaries. deidentification_summary.json holds a 12-character hex path_hash for every file and the audit scans that file. So ADA matches in a90ada7ae450.

  • What I saw: a clean run for patient Ada^Lovelace gave a phi_in_non_dicom error and exit 1. I then measured how often this happens for ADA on simulated paths:

    Files in the study Studies with a false leak
    100 10%
    300 27%
    1000 66%
  • Why it matters: the same applies to any three-letter name using only A to F, such as ABE, BEA, DEE, DEB or ACE. These are real names, and CT and MR series easily reach these file counts. Nothing can silence it. --acknowledgeRetainedTags doesn't apply to this scan and raising --residualMinLength also drops real three-letter names.

  • Suggested fix: see the note under item 3. The same change can fix both. Add a test with a hash that contains a name.

Minor

2. A valid file ending in an undefined-length sequence is rejected as truncated.

  • Where: check_not_truncated in audit_engine.py:207-219.
  • Problem: pydicom hands that sequence back as a DataElement, not a RawDataElement, so raws skips it. last then points at the element before it and the sequence bytes look like leftovers. The docstring says this case is skipped, but the skip never fires here. Line 216 is also not covered by any test.
  • What I saw: an SR whose last element is an undefined-length ContentSequence went through the anonymizer fine. The audit marked it unreadable with TruncatedDicomError and exited 1. It fails the same way when only the anonymized side has the undefined length. The same SR with a defined length is audited normally, and so is a CT with an undefined-length sequence in the middle of the file.
  • Why it's minor for now: we don't know yet whether SRs will go through this pipeline. If they do, this matters more. SRs such as CT dose reports travel with CT studies and undefined-length sequences are a normal way to encode them, so each one would fail the run.
  • Suggested fix: return early when a non-raw top-level element has a tag above last. Add a test with an undefined-length sequence as the last element.

3. Short surnames now match retained MR and CT values.

  • Where: the same branch, audit_engine.py:544.

  • What I saw: each of these gave a residual_phi error and exit 1:

    Patient Retained value
    Tse^Rick SequenceName = T2TSE3D
    Sag^Dana SequenceName = SAG2
    Vida^Mina ManufacturerModelName = VIDA3T
  • Why it's minor: --acknowledgeRetainedTags can silence these, unlike item 1. Still, Tse on a TSE sequence is a likely combination at a site that runs MR.

  • Suggested fix for items 1 and 3: the case the digit boundary was added for is folder names. Use the letters-only boundary only when scanning relative paths. Go back to the stricter whole-word rule for headers and non-DICOM content. SMITH1/ stays caught and neither false leak can happen. The trade-off is that SMITH1 inside a header or a text file goes unmatched. If you keep the current rule for headers instead, blank hex runs before scanning non-DICOM content and add these examples to the False positives section of the README.

Worth noting

  • IDs and dates fused with letters are still missed: P12345/ for ID 12345 and scanMRN6677/ for ID MRN6677 both passed with no leak. The README documents this as a limitation, and the strict rule is there to protect against matches in hex hashes. P12345 is a common way to name a folder though, so it's worth deciding on purpose. If hex runs get blanked before scanning, that rule could be loosened for paths.

Nits

  • check_not_truncated returns early on any undefined-length last element, so 3 non-zero bytes after JPEG 2000 PixelData are accepted while the same bytes after a native file are rejected. This is unchanged and I don't see any harm from it, but it's inconsistent.
  • The all-zero PixelData, 4:2:2 multi-frame and 4:2:2 16-bit cases pass but have no tests.

@Sandip117

Copy link
Copy Markdown
Contributor Author

I also ran pydicom’s 166 sample files through the real anonymizer and the audit, which found and fixed five more issues (details in the second commit message). 133 of the 134 files the anonymizer processed now pass; the remaining one is a genuine anonymizer leak in an SR. Measured false-positive rates with 9,495 real names are in the README.

@Sandip117
Sandip117 requested a review from jbernal0019 November 4, 2026 16:27
@Sandip117
Sandip117 merged commit 97eca4e into main Nov 4, 2026
3 checks passed
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.

2 participants