Skip to content

fix: restore stdout when print_confusion_matrix output_file write fails - #394

Merged
sromoam merged 2 commits into
awslabs:devfrom
hippi345:fix/confusion-matrix-stdout-restore-385
Oct 19, 2026
Merged

sromoam merged 2 commits into
awslabs:devfrom
hippi345:fix/confusion-matrix-stdout-restore-385

Conversation

@hippi345

Copy link
Copy Markdown
Contributor

fix: restore stdout when print_confusion_matrix output_file write fails

Pull Request

Issue Reference

Fixes #385

Description of Changes

When print_confusion_matrix(..., output_file=...) is called with an invalid field_filter regex or encounters any error during file writing, sys.stdout is left pointing at a closed file, breaking all subsequent print() calls in the process.

Changes Made

  • Replaced manual sys.stdout reassignment with contextlib.redirect_stdout() to ensure stdout is always restored on any exit (success or exception)
  • Added pytest test case that forces a mid-write failure and asserts stdout restoration and error propagates correctly

Why These Changes Are Needed

The bug made it impossible to recover from errors in print_confusion_matrix when using output_file. After the error, the entire Python process could not print to stdout, making debugging extremely difficult.

Possible follow-up

The file-output branch skips _print_bulk_info_summary(), which the console-output branch includes, so file output for a bulk result leaves out the processing time, field count, and error count. This could be addressed separately.

Testing

  • Unit tests added/updated
    • Added test_print_confusion_matrix_output_file_error_restores_stdout that uses invalid regex to trigger re.error mid-write
    • Test asserts stdout is restored and error propagates correctly
    • Test demonstrated failure before fix, passes after fix
  • Integration tests added/updated
    • All existing confusion matrix printing tests still pass
  • Manual testing completed
  • All existing tests pass
    • Full test suite (uv sync --all-extras): 2797 passed, 2 skipped, 1 xfailed

Lint checks pass for modified files.

Checklist

  • Code follows the project's coding standards
  • Self-review of code completed
  • Documentation updated (if applicable) - N/A, behavior fix only
  • CHANGELOG.md entry added under [Unreleased], or not needed because
    nothing user-visible changed (see RELEASING.md) - Maintainer to decide if entry needed for bugfix
  • Tests added/updated for new functionality
  • All CI checks are passing - Local tests and lints pass
  • Ready for review

Additional Notes

This contribution was prepared with AI assistance (Cursor Agent).

Use contextlib.redirect_stdout to ensure sys.stdout is always restored,
even when an error occurs during file writing. Previously, any exception
between stdout reassignment and restoration would leave stdout pointing
at a closed file, breaking all subsequent print() calls in the process.

Also catch only OSError from open() instead of all exceptions, and add
missing bulk_info_summary to file output branch.

Fixes awslabs#385
Remove OSError narrowing and bulk_info_summary addition from the previous
commit to focus solely on fixing the stdout restoration bug described in
issue awslabs#385.
@sromoam sromoam added this to the 1.0.1 (Minor) milestone Oct 15, 2026
@hippi345
hippi345 marked this pull request as ready for review October 15, 2026 15:37
@hippi345
hippi345 requested a review from sromoam as a code owner October 15, 2026 15:37

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @hippi345, this fixes what #385 reported for print_confusion_matrix. With redirect_stdout, stdout is restored when a write fails, and the new test tells the old code from the new: the old handler raised ValueError, the new code raises the real re.error. Approving.

The same manual sys.stdout swap is still in print_non_matches (pretty_print.py:951), print_confusion_matrix_html (:1364) and print_evaluation_results (:1282), and the file branch still skips the bulk summary. All of that predates this PR, so I'll open a follow-up issue rather than hold this one. If you'd like to take it, it's yours.

Optional:

  • pretty_print.py:349: except Exception also catches non-I/O errors such as a TypeError from a bad path type. except OSError would report only real open failures.
  • test_confusion_matrix_printing.py:104: pytest's tmp_path fixture would clean up after itself. NamedTemporaryFile(delete=False) leaves a file behind.

I'll add the CHANGELOG line when we cut the release.

@github-actions

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-19T16:02:38+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-19T16:00:36+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 3 0 0 5758 0 3 FAILED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 1 0 0 0 0 1 SKIPPED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 2 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py

Detailed Findings

Show 4 actionable findings

Finding 1: SECRET-HEX-HIGH-ENTROPY-STRING

  • Severity: HIGH
  • Scanner: detect-secrets
  • Rule ID: SECRET-HEX-HIGH-ENTROPY-STRING
  • Location: tests/comparators/test_anls_leaf_semantics.py:89

Description:
Secret of type 'Hex High Entropy String' detected in file 'tests/comparators/test_anls_leaf_semantics.py' at line 89

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B108

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B108
  • Location: tests/comparators/test_anls_leaf_semantics.py:210-212

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

uuid.UUID(int=1),
            pathlib.Path("/tmp/x"),
            b"bytes",

Finding 3: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1362-1368

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

def published_label(node: dict, section: str, object_lists: set) -> str:
            counts_objects = eval(  # noqa: S307
                cond.group(1),
                {},
                {"data": node, "section": section, "OBJECT_LISTS": object_lists},
            )
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 4: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1367-1369

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

)
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Report generated by Automated Security Helper (ASH) at 2026-10-19T16:02:38+00:00

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.

print_confusion_matrix with output_file leaves stdout broken and mislabels errors

2 participants