Skip to content

fix: replace print() with logging and bare excepts in graph_debugger.py#342

Open
Samarth0211 wants to merge 1 commit intomicrosoft:mainfrom
Samarth0211:fix/logging-and-bare-excepts
Open

fix: replace print() with logging and bare excepts in graph_debugger.py#342
Samarth0211 wants to merge 1 commit intomicrosoft:mainfrom
Samarth0211:fix/logging-and-bare-excepts

Conversation

@Samarth0211
Copy link

Fixes #334 and #332

  • Replace all library-internal print() calls with logger.warning() and logger.info() using the module-level logger = logging.getLogger(name)
  • CLI-facing print() in session_commands.py is intentionally left as-is per issue guidance ("CLI user-facing print is OK")
  • Replace bare except: blocks with except Exception: in _generate_static_png() and generate_comparison_visualization() to avoid silently catching KeyboardInterrupt and SystemExit
  • Add import logging and module-level logger at top of file

Description

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Maintenance (dependency updates, CI/CD, refactoring)
  • Security fix

Package(s) Affected

  • agent-os-kernel
  • agent-mesh
  • agent-runtime
  • agent-sre
  • agent-governance
  • docs / root

Checklist

  • My code follows the project style guidelines (ruff check)
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (pytest)
  • I have updated documentation as needed
  • I have signed the Microsoft CLA

Related Issues

Fixes microsoft#334 and microsoft#332

- Replace all library-internal print() calls with logger.warning() and
  logger.info() using the module-level logger = logging.getLogger(__name__)
- CLI-facing print() in session_commands.py is intentionally left as-is
  per issue guidance ("CLI user-facing print is OK")
- Replace bare `except:` blocks with `except Exception:` in
  _generate_static_png() and generate_comparison_visualization() to
  avoid silently catching KeyboardInterrupt and SystemExit
- Add `import logging` and module-level logger at top of file
@github-actions
Copy link

Welcome to the Agent Governance Toolkit! Thanks for your first pull request.
Please ensure tests pass, code follows style (ruff check), and you have signed the CLA.
See our Contributing Guide.

@github-actions github-actions bot added the size/XL Extra large PR (500+ lines) label Mar 22, 2026
Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

🤖 AI Agent: code-reviewer

Review Summary

This pull request addresses two issues: replacing print() statements with proper logging and replacing bare except: blocks with except Exception: in the graph_debugger.py file. These changes are aligned with Python best practices and improve the maintainability and robustness of the code. However, there are a few areas that require attention to ensure correctness, security, and maintainability.


Key Findings

🔴 CRITICAL: Logging Sensitive Information

  1. Potential Logging of Sensitive Data:
    • In the _get_node_style method, the title string includes trace.validation_errors. If validation_errors contains sensitive information (e.g., user data, credentials, or other sensitive details), logging this data using logger.info or logger.warning could lead to information leakage.
    • Recommendation: Ensure that trace.validation_errors does not contain sensitive information. If it might, sanitize or redact sensitive data before logging.

💡 SUGGESTION: Improve Logging Messages

  1. Generic Logging Messages:

    • Some logging messages, such as "Visualization libraries not available: %s. Install with: pip install matplotlib networkx pyvis", could be more specific about the impact of missing libraries on the functionality.
    • Recommendation: Update the message to include the consequences of missing libraries (e.g., "Visualization libraries not available: %s. Visualization features will be disabled. Install with: pip install matplotlib networkx pyvis").
  2. Logging Levels:

    • The use of logger.warning for missing libraries is appropriate. However, consider using logger.error for critical issues like unsupported formats in the visualize_trace method.
    • Recommendation: Use logger.error for cases where the program cannot proceed due to an error.

💡 SUGGESTION: Exception Handling

  1. Generic Exception Handling:
    • While replacing except: with except Exception: is an improvement, it is still a broad exception handling practice. For example, in _generate_static_png, the except Exception: block could mask unexpected errors.
    • Recommendation: Narrow down the exception types to handle only expected exceptions (e.g., ValueError, KeyError, etc.). If a broad exception is necessary, log the exception details using logger.exception to aid debugging.

💡 SUGGESTION: Logging Configuration

  1. Logging Configuration:
    • The PR introduces a logger object but does not configure the logging module. This could lead to logs being silently dropped if no handlers are configured.
    • Recommendation: Add a default logging configuration in the main entry point of the application or library (e.g., logging.basicConfig(level=logging.INFO)).

💡 SUGGESTION: Code Formatting

  1. Code Formatting Issues:
    • The diff shows inconsistent indentation, with some lines using 4 spaces and others using 8 spaces. This inconsistency makes the code harder to read and maintain.
    • Recommendation: Run a linter (e.g., ruff) or a code formatter (e.g., black) to ensure consistent formatting.

💡 SUGGESTION: Testing

  1. Testing for Logging and Exception Handling:
    • The PR does not include any new tests to verify the changes made to logging and exception handling.
    • Recommendation: Add tests to ensure that:
      • Logging messages are generated as expected.
      • The application behaves correctly when exceptions are raised (e.g., by mocking the logger and asserting the logged messages).

Final Assessment

  • The changes in this PR improve the codebase by replacing print() with logging and addressing the use of bare except: blocks. However, there are some areas that require further attention, particularly around logging sensitive information and exception handling.
  • The PR does not introduce any breaking changes, but the potential for sensitive data leakage in logs is a critical issue that must be addressed.

Actionable Feedback Summary

  1. 🔴 CRITICAL: Ensure that sensitive information (e.g., trace.validation_errors) is not logged or is properly sanitized/redacted before logging.
  2. 💡 SUGGESTION: Improve the specificity and clarity of logging messages, especially for critical issues.
  3. 💡 SUGGESTION: Replace broad except Exception: blocks with more specific exception handling where possible. Use logger.exception to log details of unexpected errors.
  4. 💡 SUGGESTION: Add a default logging configuration to ensure logs are not silently dropped.
  5. 💡 SUGGESTION: Run a linter (e.g., ruff) or formatter (e.g., black) to fix inconsistent indentation and ensure code style compliance.
  6. 💡 SUGGESTION: Add tests to verify the correctness of logging and exception handling changes.

Let me know if you need further clarification or assistance!

@microsoft-github-policy-service

@Samarth0211 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@github-actions
Copy link

🤖 AI Agent: contributor-guide

Hello @first-time-contributor! 👋

Welcome to the microsoft/agent-governance-toolkit project, and thank you for taking the time to contribute! 🎉 We’re thrilled to have you here, and we appreciate your effort in addressing issues #334 and #332. Let’s dive into your pull request together!


What You Did Well ✅

  1. Clear Description: Your PR description is detailed and well-structured. You’ve clearly outlined the changes you’ve made and referenced the relevant issues. This makes it easy for reviewers to understand the purpose of your contribution.
  2. Thoughtful Changes: Replacing print() statements with logger calls is a great improvement for better logging and debugging. Similarly, replacing bare except: blocks with except Exception: is a good practice to avoid catching system-level exceptions like KeyboardInterrupt and SystemExit.
  3. Following Issue Guidance: You’ve carefully followed the guidance in the issues, leaving CLI-facing print() statements untouched. This shows attention to detail and respect for the project’s requirements.

Suggestions for Improvement ✨

  1. Code Formatting:

    • It seems like there are some indentation issues in your code. For example, in the NodeState class and other parts of the code, the indentation is inconsistent. This might have been caused by copy-pasting or an editor configuration. To ensure consistency, we use ruff for linting. You can run ruff check . locally to identify and fix these issues. You can find more details in our CONTRIBUTING.md.
  2. Testing:

    • While your changes look great, it’s important to add or update tests to ensure the new behavior works as expected. For example:
      • Add tests to verify that logger.warning() and logger.info() are called instead of print().
      • Add tests to confirm that except Exception: blocks handle errors correctly without catching system-level exceptions.
    • Tests for this module should go in the packages/agent-os/tests/ directory. You can find more details about testing in our CONTRIBUTING.md.
  3. Commit Message:

    • Thank you for using the fix: prefix in your commit message! This aligns with our Conventional Commits guidelines. However, it would be great if you could make the message more descriptive. For example:
      fix(graph_debugger): replace print() with logging and handle exceptions explicitly
      
  4. Documentation:

    • If these changes impact how developers interact with the code (e.g., logging behavior), consider updating the relevant documentation. You can find more details in our CONTRIBUTING.md and QUICKSTART.md.

Next Steps 🚀

  1. Run Linter: Run ruff check . locally to fix any formatting issues.
  2. Add/Update Tests: Add tests for the changes you’ve made in the packages/agent-os/tests/ directory.
  3. Update Commit Message: Amend your commit message to follow the Conventional Commits format with more descriptive details.
  4. Push Changes: Once you’ve made these updates, push them to your branch. This will automatically update the pull request.

After you’ve made these changes, we’ll review your PR again. If you have any questions or need help, feel free to ask! We’re here to support you. 😊

Thank you again for contributing to the project — we’re excited to collaborate with you! 🎉

@github-actions
Copy link

🤖 AI Agent: security-scanner

Security Review of PR: fix: replace print() with logging and bare excepts in graph_debugger.py

Summary

This PR addresses two issues:

  1. Replacing print() statements with logger.warning() or logger.info() for better logging practices.
  2. Replacing bare except: blocks with except Exception: to avoid catching critical exceptions like KeyboardInterrupt and SystemExit.

While these changes improve code quality and maintainability, a security review is necessary to ensure no new vulnerabilities are introduced.


Findings

1. Logging of Sensitive Information

Rating: 🟠 HIGH

Issue:

  • The PR introduces logging for various events, such as missing libraries and file save operations. However, there is no validation or sanitization of the data being logged. If sensitive information (e.g., file paths, session IDs, or metadata) is included in the logs, it could lead to unintended information disclosure.

Attack Vector:

  • If the metadata field in ExecutionTrace contains sensitive information (e.g., API keys, user credentials, or PII), logging it without sanitization could expose this data in logs, which might be accessible to unauthorized users.

Recommendation:

  • Review the contents of metadata and other logged fields to ensure no sensitive information is being logged.
  • Use a logging filter to sanitize sensitive data before logging.
  • Add a warning in the documentation to avoid storing sensitive information in the metadata field.

2. Improper Exception Handling

Rating: 🟠 HIGH

Issue:

  • While the PR replaces bare except: blocks with except Exception:, this still catches a broad range of exceptions, including potentially unexpected ones. For example, MemoryError or KeyboardInterrupt are still caught, which could lead to unintended behavior.

Attack Vector:

  • Catching all exceptions (even non-critical ones) can mask underlying issues, making it harder to debug and potentially allowing attackers to exploit unhandled edge cases.

Recommendation:

  • Be more specific in exception handling. For example, if the code is expected to handle only IOError or ValueError, catch those specific exceptions instead of using except Exception:.
  • Log the exception details (e.g., logger.error("Error occurred", exc_info=True)) to aid debugging.

3. Potential for Sandbox Escape

Rating: 🟠 HIGH

Issue:

  • The _generate_static_png method uses matplotlib and networkx to generate visualizations. If the trace object contains malicious data (e.g., specially crafted strings or payloads), it could potentially exploit vulnerabilities in these libraries to execute arbitrary code or escape a sandboxed environment.

Attack Vector:

  • If an attacker provides a malicious trace object with crafted node_id, metadata, or validation_errors, it could exploit vulnerabilities in matplotlib or networkx to execute arbitrary code or cause a denial of service.

Recommendation:

  • Validate and sanitize all user-provided data (e.g., node_id, metadata, validation_errors) before passing it to third-party libraries.
  • Use a library like bleach to sanitize strings if they are rendered as HTML or used in visualizations.
  • Consider running the visualization generation in a sandboxed environment to limit the impact of potential vulnerabilities in third-party libraries.

4. Error Messages Reveal Internal Details

Rating: 🟡 MEDIUM

Issue:

  • The logging messages introduced in this PR reveal internal implementation details, such as the names of missing libraries and file paths.

Attack Vector:

  • An attacker could use this information to infer the internal structure of the application or exploit known vulnerabilities in the missing libraries.

Recommendation:

  • Avoid logging detailed internal information in production environments. Use generic error messages for end-users and reserve detailed logs for debugging in development environments.

5. Race Conditions in Visualization File Generation

Rating: 🔵 LOW

Issue:

  • The visualize_trace method writes visualization files to the filesystem. If multiple processes or threads attempt to write to the same file simultaneously, it could lead to race conditions or data corruption.

Attack Vector:

  • An attacker could exploit this by triggering multiple concurrent requests to generate visualizations, potentially causing a denial of service or overwriting files.

Recommendation:

  • Use unique filenames for each visualization file, such as appending a UUID or timestamp to the filename.
  • Alternatively, use a thread-safe mechanism to ensure only one process writes to a file at a time.

Additional Observations

  1. Improper Indentation:

    • The diff shows significant indentation issues (e.g., extra spaces or tabs). While this is not a security issue, it affects code readability and maintainability. Ensure consistent indentation throughout the file.
  2. Dependency Management:

    • The PR does not address dependency management. Ensure that all third-party libraries (networkx, pyvis, matplotlib) are up-to-date and free from known vulnerabilities. Use tools like pip-audit or safety to scan for vulnerabilities.

Recommendations for the PR

  1. Sanitize Logged Data:

    • Review and sanitize all data being logged to prevent sensitive information from being exposed.
  2. Refine Exception Handling:

    • Replace except Exception: with more specific exception types where possible.
  3. Validate User-Provided Data:

    • Add validation and sanitization for all user-provided data passed to third-party libraries.
  4. Use Unique Filenames:

    • Ensure visualization files have unique filenames to prevent race conditions.
  5. Audit Dependencies:

    • Perform a security audit of all dependencies used in this module.
  6. Fix Indentation:

    • Correct the indentation issues in the file for better readability.

Final Assessment

  • Severity: 🟠 HIGH
  • Approval: Changes are beneficial but require additional fixes for security hardening.
  • Next Steps: Address the recommendations above before merging the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR (500+ lines)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: replace print() with logging in library source

1 participant