Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Dec 12, 2025

Pydantic can return empty loc tuples for certain validation failures, particularly with model_validator on nested models. Accessing [-1] on an empty tuple raises IndexError.

Changes

  • runner.py: Check if loc tuple is empty before indexing

    # Before
    field_name = str(pydantic_err.get("loc", ["unknown"])[-1])
    
    # After
    loc = pydantic_err.get("loc", ())
    field_name = str(loc[-1]) if loc else "unknown"
  • test_runner.py: Add test case for empty loc tuple handling

The fix defaults to "unknown" for the field name when loc is empty, consistent with existing behavior when loc is missing.

Original prompt

This section details on the original issue you should resolve

<issue_title>IndexError when validation error has empty loc tuple</issue_title>
<issue_description>## Bug Description

When a Pydantic validation error has an empty loc tuple (which can occur with model_validator failures on nested models), the code in runner.py line 80 raises an IndexError.

Current Code

field_name = str(pydantic_err.get("loc", ["unknown"])[-1])

Problem

When loc is an empty tuple (), accessing [-1] causes:

IndexError: tuple index out of range

This edge case occurs when nested model validation fails within a model_validator, where Pydantic may return an empty location tuple.

Suggested Fix

loc = pydantic_err.get("loc", ())
field_name = str(loc[-1]) if loc else "unknown"

Reproduction

This occurs when processing records where nested model validation fails with an empty location. The specific scenario involves using model_validator(mode='after') on nested Pydantic models.

Environment

  • Python 3.12+
  • Pydantic 2.x
  • abstract-validation-base (latest)</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Enhanced validation error handling to robustly manage edge cases with missing or empty location data. Error messages now gracefully default to "unknown" when location information is unavailable, ensuring more consistent and reliable error reporting across validation failures.

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

@coderabbitai
Copy link

coderabbitai bot commented Dec 12, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Added defensive guard in runner.py to safely extract field names from Pydantic validation errors, handling empty loc tuples without raising IndexError. Complementary unit test verifies the fix handles empty loc tuples by defaulting to "unknown".

Changes

Cohort / File(s) Change Summary
Bug Fix
src/abstract_validation_base/runner.py
Modified field name extraction in error_summary to safely handle empty or missing loc tuples. Changed from direct indexing pydantic_err.get("loc", ["unknown"])[-1] to guarded access: extract loc, then access loc[-1] only if loc is non-empty, defaulting to "unknown".
Test Coverage
tests/test_runner.py
Added unit test verifying error_summary correctly processes Pydantic errors with empty loc tuples, asserting the result contains "unknown" as location and preserves the error message.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

  • The fix is a single-line logic change with a straightforward guard condition
  • Test addition is focused on a single edge case
  • No complex interactions or side effects introduced

Poem

A tuple so empty, it had naught to show,
But our guard stood firm, with a gentle "unknown"
No index shall break us when loc runs dry,
Just "unknown" whispers beneath the Python sky 🐰✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: handling IndexError when Pydantic validation errors have empty loc tuples, which matches the core change in runner.py.
Linked Issues check ✅ Passed The PR implements all coding requirements from issue #1: it replaces unsafe indexing with safe loc checking, handles empty tuples by defaulting to 'unknown', and includes test coverage for the empty loc scenario.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the IndexError bug described in issue #1; no extraneous modifications or scope creep is present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

- Fixed bug in runner.py line 80 where accessing [-1] on empty loc tuple caused IndexError
- Changed logic to check if loc tuple is empty before accessing last element
- Added test case to verify empty loc tuple is handled correctly
- All existing tests pass with no regressions

Co-authored-by: jreakin <[email protected]>
Copilot AI changed the title [WIP] Fix IndexError for empty loc tuple in validation Fix IndexError when Pydantic validation error has empty loc tuple Dec 12, 2025
Copilot AI requested a review from jreakin December 12, 2025 09:57
@jreakin
Copy link
Member

jreakin commented Dec 12, 2025

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Dec 12, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@jreakin jreakin marked this pull request as ready for review December 12, 2025 10:05
Copilot AI review requested due to automatic review settings December 12, 2025 10:05
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes an IndexError that occurs when Pydantic validation errors contain an empty loc tuple, which can happen with model_validator failures on nested models. The fix adds a defensive check before indexing the tuple and defaults to "unknown" when the location is empty.

Key changes:

  • Modified error handling in runner.py to safely access the loc tuple with an emptiness check
  • Added comprehensive test coverage for the empty loc tuple edge case

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/abstract_validation_base/runner.py Fixed IndexError by checking if loc tuple is empty before accessing [-1] index
tests/test_runner.py Added test case verifying that empty loc tuples are handled gracefully with "unknown" default

The implementation looks solid and follows the existing error handling patterns in the codebase. The fix correctly addresses the bug described in the issue, and the test coverage adequately validates the new behavior. The solution is consistent with the existing fallback to "unknown" when loc is missing entirely, providing uniform behavior across edge cases.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@sentry
Copy link

sentry bot commented Dec 12, 2025

Welcome to Codecov 🎉

Once you merge this PR into your default branch, you're all set! Codecov will compare coverage reports and display results in all future pull requests.

ℹ️ You can also turn on project coverage checks and project coverage reporting on Pull Request comment

Thanks for integrating Codecov - We've got you covered ☂️

@jreakin jreakin merged commit d4e3c21 into main Dec 12, 2025
17 of 19 checks passed
@jreakin jreakin deleted the copilot/fix-index-error-validation branch December 12, 2025 12:27
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.

IndexError when validation error has empty loc tuple

2 participants