Skip to content

implement registry functions and fix linting (#12) - #49

Merged
aviralgarg05 merged 3 commits into
aviralgarg05:mainfrom
Sunil-saini1818:main
Jan 1, 2026
Merged

aviralgarg05 merged 3 commits into
aviralgarg05:mainfrom
Sunil-saini1818:main

Conversation

@Sunil-saini1818

@Sunil-saini1818 Sunil-saini1818 commented Dec 30, 2025

Copy link
Copy Markdown
Contributor

Description

This PR addresses the missing functionality in the metrics registry by implementing the registration and retrieval logic. This allows for dynamic expansion of the metrics suite and ensures better reliability through comprehensive unit tests.

Fixes #12

Type of Change

Please delete options that are not relevant:

  • New feature (non-breaking change which adds functionality)
  • Test coverage improvement

Changes Made

  • Implemented register_metric() in src/agentunit/metrics/registry.py to allow adding new metrics at runtime.

  • Implemented get_metric() in src/agentunit/metrics/registry.py to safely retrieve metrics by their string names.

  • Created tests/test_metrics_registry.py with 4 new test cases.

  • Ensured all imports follow PEP8/Ruff guidelines by placing them at the top of the file.

Testing

  • Existing test suite passes (pytest)
  • Added new tests for new functionality
  • Manual testing performed

Test Configuration

  • Python version: 3.12.1
  • Operating System: Linux (GitHub Codespaces)
  • Relevant adapters tested: Built-in metrics (Faithfulness, ToolSuccess)

Test Results

============================= test session starts ==============================
platform linux -- Python 3.12.1, pytest-8.4.2, pluggy-1.6.0
rootdir: /workspaces/agentunit
configfile: pyproject.toml
plugins: agentunit-0.7.0, cov-5.0.0, anyio-4.11.0
collected 4 items

tests/test_metrics_registry.py .... [100%]

============================== 4 passed in 0.02s ===============================

Code Quality

  • My code follows the project's style guidelines (Ruff, Black)
  • I have performed a self-review of my own code
  • My changes generate no new warnings or errors
  • I have added type hints where appropriate

Documentation

  • I have added/updated docstrings for new/modified functions

Dependencies

  • No new dependencies added

Performance Impact

  • No performance impact

Additional Context

Add any other context about the PR here:

  • Links to related issues or PRs
  • References to external documentation
  • Design decisions and trade-offs
  • Known limitations or future work

Checklist

  • I have read the CONTRIBUTING.md guide
  • My commit messages follow the conventional commit format
  • I have tested my changes locally
  • I have added tests that prove my fix is effective or that my feature works
  • All new and existing tests pass

Reviewer Notes

Please pay special attention to:

Post-Merge Tasks

Tasks to complete after merging (if any):

  • Update external documentation
  • Announce in discussions/community
  • Create follow-up issues for future work

Summary by CodeRabbit

  • New Features

    • Metrics can be dynamically registered and retrieved at runtime via new public APIs, including single-metric retrieval.
  • Bug Fixes

    • Prevents duplicate metric registrations with clear errors; registry mutations are now safe under concurrent use and unknown lookups raise descriptive errors.
  • Tests

    • Added tests for default resolution, successful registration and retrieval, duplicate-registration errors, and unknown-metric handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@continue

continue Bot commented Dec 30, 2025

Copy link
Copy Markdown

All Green - Keep your PRs mergeable

Learn more

All Green is an AI agent that automatically:

✅ Addresses code review comments

✅ Fixes failing CI checks

✅ Resolves merge conflicts


Unsubscribe from All Green comments

@coderabbitai

coderabbitai Bot commented Dec 30, 2025

Copy link
Copy Markdown

Walkthrough

Adds thread-safe mutation APIs to the metrics registry: register_metric(name, metric) and get_metric(name), plus tests covering default resolution, unknown metric, duplicate registration, successful get, and successful register (with cleanup).

Changes

Cohort / File(s) Change Summary
Metrics registry module
src/agentunit/metrics/registry.py
Added module-level _registry_lock (imports threading) and two public functions: register_metric(name: str, metric: Metric) (registers a metric; raises ValueError if name already exists) and get_metric(name: str) -> Metric (retrieves a single metric via existing resolve_metrics logic). Existing resolve_metrics behavior preserved.
Metrics registry tests
tests/test_metrics_registry.py
New test file adding: test_resolve_default_metrics (validates resolve_metrics(None) count), test_resolve_unknown_metric (expects KeyError for unknown name), test_register_duplicate_metric (expects ValueError when registering duplicate), test_get_metric_success (retrieves ToolSuccessMetric), and test_register_metric_success (registers a new metric and cleans up after test).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • Implements tests and edge-case behavior requested by issue #12 (Improve test coverage for metrics registry).

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'implement registry functions and fix linting (#12)' directly describes the main changes: implementing registry functions and fixing linting issues, which aligns with the changeset.
Description check ✅ Passed The description covers key sections including summary, type of change, changes made, testing, code quality, and dependencies. However, several checkboxes remain unchecked and some template sections are incomplete.
Linked Issues check ✅ Passed The PR implements test coverage for register_metric() and get_metric() with edge case tests for duplicate metrics and non-existent metrics [#12], meeting all coding requirements from the linked issue.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing registry functions and adding test coverage as specified in issue #12; no out-of-scope changes detected.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/agentunit/metrics/registry.py (1)

51-56: Consider deduplicating lookup logic.

The lookup pattern (get from DEFAULT_METRICS, check None, raise KeyError) is duplicated between get_metric and resolve_metrics (lines 36-39). While the duplication is minimal, you could reduce it by having one function call the other.

🔎 Example refactor to reduce duplication
 def get_metric(name: str) -> Metric:
-    metric = DEFAULT_METRICS.get(name)
-    if metric is None:
-        msg = f"Unknown metric '{name}'"
-        raise KeyError(msg)
-    return metric
+    return resolve_metrics([name])[0]
tests/test_metrics_registry.py (1)

22-29: Consider adding test coverage for successful metric registration.

While this test correctly validates duplicate detection, there's no test for the successful registration path. Consider adding a test that registers a new metric and then retrieves it, with proper cleanup to avoid polluting the global state for other tests.

🔎 Example test with cleanup
def test_register_metric_success():
    from agentunit.metrics.registry import DEFAULT_METRICS
    from agentunit.metrics.builtin import ToolSuccessMetric
    
    # Register a new metric with a unique name
    test_metric = ToolSuccessMetric()
    register_metric("test_custom_metric", test_metric)
    
    try:
        # Verify it was registered
        retrieved = get_metric("test_custom_metric")
        assert retrieved is test_metric
    finally:
        # Cleanup to avoid polluting other tests
        DEFAULT_METRICS.pop("test_custom_metric", None)
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 584d96f and 8ff85a3.

📒 Files selected for processing (2)
  • src/agentunit/metrics/registry.py
  • tests/test_metrics_registry.py
🧰 Additional context used
🧬 Code graph analysis (2)
tests/test_metrics_registry.py (2)
src/agentunit/metrics/registry.py (3)
  • get_metric (51-56)
  • register_metric (44-48)
  • resolve_metrics (31-41)
src/agentunit/metrics/builtin.py (2)
  • FaithfulnessMetric (37-57)
  • ToolSuccessMetric (60-70)
src/agentunit/metrics/registry.py (2)
src/agentunit/datasets/base.py (1)
  • name (38-39)
src/agentunit/metrics/base.py (1)
  • Metric (23-26)
🔇 Additional comments (2)
tests/test_metrics_registry.py (2)

12-18: LGTM!

The test correctly validates error handling for unknown metrics and checks the error message.


32-39: LGTM!

The test correctly validates successful metric retrieval and verifies the returned type.

Comment thread src/agentunit/metrics/registry.py Outdated
Comment thread src/agentunit/metrics/registry.py Outdated
Comment thread tests/test_metrics_registry.py Outdated

@aviralgarg05 aviralgarg05 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Pls fix the issues

@codecov-commenter

codecov-commenter commented Dec 31, 2025

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 60.00000% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/agentunit/metrics/registry.py 60.00% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/agentunit/metrics/registry.py (1)

31-31: Consider documenting the concurrency model.

The lock correctly guards write operations in register_metric, but read operations (resolve_metrics, get_metric) access DEFAULT_METRICS without synchronization. This is acceptable if metric registration occurs only during application startup before concurrent access begins.

Consider adding a module-level docstring or comment documenting the expected usage pattern to prevent future misuse.

📝 Example documentation
"""Metric registry mapping string names to implementations.

Thread safety: Metric registration via register_metric() is thread-safe.
For best results, register all metrics during application initialization
before concurrent access begins.
"""
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3254a6c and 9e66a8c.

📒 Files selected for processing (2)
  • src/agentunit/metrics/registry.py
  • tests/test_metrics_registry.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_metrics_registry.py
🧰 Additional context used
🧬 Code graph analysis (1)
src/agentunit/metrics/registry.py (1)
src/agentunit/metrics/base.py (1)
  • Metric (23-26)
🔇 Additional comments (3)
src/agentunit/metrics/registry.py (3)

5-5: LGTM: Import correctly placed.

The threading import is properly positioned according to PEP8 conventions (stdlib imports in alphabetical order).


47-52: LGTM: Thread-safe registration with proper validation.

The implementation correctly:

  • Guards the check-then-set operation with _registry_lock to prevent race conditions
  • Validates for duplicate registrations before adding
  • Provides clear error messages

55-58: LGTM: Clean delegation pattern.

The function correctly delegates to resolve_metrics to avoid duplicating error-handling logic. The comment clearly explains the rationale for this design choice. The KeyError raised by resolve_metrics will propagate naturally when the metric is not found.

@Sunil-saini1818

Copy link
Copy Markdown
Contributor Author

All requested changes have been implemented and verified:

Thread Safety: Added threading.Lock to register_metric to guard global state mutation.

Deduplication: Refactored get_metric to use resolve_metrics, ensuring consistent error messages across the registry.

Test Robustness: Updated test_resolve_default_metrics with dynamic length checks and added test_register_metric_success with proper state cleanup.

CI Status: Local poetry build and ruff format are successful, and all GitHub CI checks are now Green.

The PR is ready for final review and merging. Thank you so much @aviralgarg05 for the guidance 🙏🙏

@aviralgarg05 aviralgarg05 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

LGTM!

@aviralgarg05
aviralgarg05 merged commit 8b1a913 into aviralgarg05:main Jan 1, 2026
12 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.

Improve test coverage for metrics registry

3 participants