Skip to content

Narrow sourcehut exception handlers - #988

Merged
potiuk merged 3 commits into
apache:mainfrom
amh1k:fix/sourcehut-narrow-exception-handlers
Jul 30, 2026
Merged

potiuk merged 3 commits into
apache:mainfrom
amh1k:fix/sourcehut-narrow-exception-handlers

Conversation

@amh1k

@amh1k amh1k commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Narrow error handling to only expected malformed-data failures, so unexpected errors now propagate instead of being silently discarded.
  • Add regression coverage for the expected fallback paths and unexpected sort failures.
  • Define the SourceHut development dependency group used by its local quality checks.

Type of change

  • Skill change (.claude/skills/<name>/) — eval fixtures updated below
  • Tool / bridge contract (tools/<system>/*.md)
  • Python package (tools/*/ with pyproject.toml)
  • Groovy reference impl
  • Cross-cutting (RFC, AGENTS.md, sandbox, privacy-LLM)
  • Documentation (docs/, README.md, CONTRIBUTING.md)
  • Project template (projects/_template/)
  • CI / dev loop (prek, workflows, validators)
  • Other:

Test plan

  • prek run --all-files passes
  • uv run --directory tools/sourcehut --group dev ruff check .
  • uv run --directory tools/sourcehut --group dev mypy
  • uv run --directory tools/sourcehut --group dev pytest — 17 passed
  • uv lock --check
  • For Groovy bridges touched: command-line invocation tested end-to-end
  • For skill changes: eval suite passes for the affected skill
    (PYTHONPATH=tools/skill-evals/src python3 -m skill_evals.runner tools/skill-evals/evals/<skill>/)
  • For skill behaviour changes: a new or updated eval fixture is included in this PR
    (a regression test for the bug fixed / the behaviour added — see CONTRIBUTING.md)
  • Other:

RFC-AI-0004 compliance

Not applicable: this change only narrows local Python exception handling and adds tests.

Linked issues

Closes #953

Notes for reviewers (optional)

The HTTP-error fallback now catches only json.JSONDecodeError, KeyError, and TypeError. Email sorting suppresses only TypeError and AttributeError; unexpected failures propagate rather than allowing an incorrect cover-letter selection.

@justinmclean

Copy link
Copy Markdown
Member

I ran both changed handlers with the patch applied.

Inline comment 1 — tools/sourcehut/src/magpie_sourcehut/client.py:82

This narrowing leaks exceptions that query_graphql previously converted into SourceHutError. Every other error path in this function raises SourceHutError; after this change four realistic HTTP-error bodies escape as raw exceptions instead. Driving the real function with a mocked HTTPError:

text
plain text body -> SourceHutError: HTTP request to ... failed with status 400 (ok)
non-utf8 body -> LEAKED UnicodeDecodeError
JSON array body -> LEAKED AttributeError: 'list' object has no attribute 'get'
JSON string body -> LEAKED AttributeError: 'str' object has no attribute 'get'
{"errors":"boom"} -> LEAKED AttributeError: 'str' object has no attribute 'get'

exc.read().decode("utf-8") raises UnicodeDecodeError, which is a ValueError but not a json.JSONDecodeError, so a latin-1 error page from a proxy now crashes the caller. err_json.get(...) raises AttributeError whenever the body is valid JSON that is not an object, and e.get(...) does the same when errors is a string. Separately, KeyError is unreachable here: the block only uses .get(), never subscripting.

suggestion
except (ValueError, AttributeError, TypeError):

ValueError covers json.JSONDecodeError and UnicodeDecodeError both.

Inline comment 2 — tools/sourcehut/src/magpie_sourcehut/lists.py:125

The issue asks for the handler to stop "silently yielding the wrong description and author". Narrowing Exception to TypeError does not achieve that, because TypeError is the failure mode: a null date among the emails raises it mid-sort, and list.sort leaves the list in a partially reordered state when the key comparison raises. emails[0] is then not the cover letter. Running the real map_patchset_to_pr with the patch applied, on a nine-email patchset with one null date:

text
input first email : E6
PR description/author : E0 / E0 <- wrong cover letter and wrong author

Over 2000 randomised patchsets of 3 to 12 emails with one null date, 920 came back reordered. The PR notes say "unexpected failures propagate rather than allowing an incorrect cover-letter selection", but the suppressed TypeError is precisely the path that allows it. Sorting on a total-ordering-safe key removes the failure instead of relabelling it:

suggestion
emails.sort(key=lambda x: x.get("date") or "")

If you prefer to keep a guard, sort a copy and only assign it back on success, so a raise cannot leave emails half-ordered.

Inline comment 3 — tools/sourcehut/tests/test_sourcehut.py, test_map_patchset_to_pr_keeps_input_order_when_dates_cannot_be_compared

This test asserts behaviour CPython does not guarantee. It passes only because two elements raise on the first comparison before any swap. Add a third and fourth email with the null date in the middle and the assertion fails. As written it locks in an implementation detail and gives false confidence that the wrong-cover-letter bug is covered. Once comment 2 is addressed the test should assert the sorted result directly, with null-dated emails landing in a defined position.

Credit where due: test_map_patchset_to_pr_propagates_unexpected_sort_errors is a good test and does what it claims and the acceptance criterion on exception-path coverage is met.

@potiuk potiuk changed the title Narrow SourceHut exception handlers Narrow exception handlers Jul 30, 2026
Follow-up on the two handlers narrowed in this PR. Narrowing them was the
right call, but both tuples were drawn slightly wrong and the second one
left a real bug in place. Both problems were identified by @justinmclean
in review; this commit implements his findings.

client.py — the suppressed block is a best-effort attempt to pull a nicer
message out of an untrusted HTTP error body, so failing to parse it must
never be worse than not trying: control is meant to fall through to the
status-only SourceHutError. `(json.JSONDecodeError, KeyError, TypeError)`
broke that guarantee. `exc.read().decode("utf-8")` raises
UnicodeDecodeError, which is a ValueError but not a JSONDecodeError, so a
non-UTF-8 error page from a proxy escaped to the caller; and
`err_json.get(...)` / `e.get(...)` raise AttributeError whenever the body
is valid JSON that is not an object (`null`, an array, a bare string) or
`errors` is not a list of objects. Six of the seven body shapes now
covered by tests escaped as raw exceptions. `KeyError` was unreachable —
the block only ever calls `.get()`.

Widened to `(ValueError, AttributeError, TypeError, OSError)`: ValueError
covers JSONDecodeError and UnicodeDecodeError both, AttributeError covers
the non-object bodies, and OSError covers a failed `exc.read()`.
Programming errors still propagate, which was the point of the change.

lists.py — narrowing to TypeError did not fix the bug the change set out
to fix, because TypeError *is* the failure mode: a null date raises
mid-sort, and `list.sort()` mutates in place, so it can leave the list
partially reordered when a comparison raises. `emails[0]` is then not the
cover letter, and the function silently reports the wrong description and
author — the exact symptom the change was meant to remove.

Fixed at the source instead of relabelling it: a `None` date is folded
into the sort key (the `.get` default only covers a *missing* key, not an
explicit null), so the common case no longer raises at all, and undated
emails sort last and keep their input order rather than displacing a real
cover letter. The sort now builds a copy and only adopts it on success, so
a raise on a genuinely uncomparable key cannot leave `emails` half-ordered.

Tests: `test_map_patchset_to_pr_keeps_input_order_when_dates_cannot_be_compared`
asserted behaviour CPython does not guarantee — it passed only because two
elements raise on the first comparison before any swap, and would fail with
the null date in the middle of four. Replaced with a four-email case that
asserts the resulting order directly, plus an uncomparable-key case that
asserts the input order survives. The error-body cases are now a
parametrised sweep of the seven shapes; six of them fail against the
previous tuple.

Generated-by: Claude Code (Opus 5)

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving with the fixes applied directly — I pushed one commit (aac33a2) implementing @justinmclean's two findings, so this can land without another round-trip. Please read what I changed rather than take it on trust; details and reasoning below.

First, credit where it's due: @justinmclean's review is the substantive one here, and on the lists.py half he was right where my own first read was wrong. I had signed off on (TypeError, AttributeError) as correct narrowing. It isn't, and his empirical check (920 of 2000 randomised patchsets coming back reordered) is what settles it.

lists.py — narrowing didn't fix the bug, because TypeError is the bug

The change set out to stop the function "silently yielding the wrong description and author". Suppressing TypeError cannot achieve that: a None date raises TypeError mid-sort, and list.sort() mutates in place, so it can leave the list partially reordered when a comparison raises. emails[0] is then a reply rather than the cover letter — precisely the symptom the PR was written to remove.

Fixed at the source instead of relabelling it:

with contextlib.suppress(TypeError, AttributeError):
    emails = sorted(emails, key=lambda x: (x.get("date") is None, x.get("date") or ""))

Three things there, each load-bearing:

  • x.get("date") or "" removes the common failure entirely. Worth noting why the original x.get("date", "") didn't already do this: the .get default only fires for a missing key, not for a key present with an explicit null — which is what the API actually returns.
  • x.get("date") is None as the first key element sorts undated emails last. Folding None to "" alone would sort them first, which trades a crashing bug for a deterministic wrong-cover-letter — an undated reply would take the slot. This is a small refinement of your suggestion, @justinmclean, for that reason; a stable sort keeps undated emails in input order within their group.
  • sorted(...) assigned on success rather than .sort() in place, so a raise on a genuinely uncomparable key (a numeric date, say) cannot leave emails half-ordered. That is your "sort a copy and only assign it back on success", which is the part that makes the remaining guard safe.

client.py — the tuple broke the "never worse than not trying" guarantee

Both of us landed on this one independently, with the same list of escaping shapes. The suppressed block is a best-effort attempt to extract a nicer message from an untrusted error body; control is meant to fall through to the status-only SourceHutError. I verified the escapes against the real function:

Error body Old tuple Now
not json SourceHutError SourceHutError
b"\xff\xfe" non-UTF-8 leaked UnicodeDecodeError SourceHutError
null leaked AttributeError SourceHutError
[1, 2] leaked AttributeError SourceHutError
"oops" leaked AttributeError SourceHutError
{"errors": "boom"} leaked AttributeError SourceHutError
{"errors": ["boom"]} leaked AttributeError SourceHutError

Widened to (ValueError, AttributeError, TypeError, OSError). ValueError covers json.JSONDecodeError and UnicodeDecodeError both — the trap being that UnicodeDecodeError is a ValueError but not a JSONDecodeError. I added OSError on top of @justinmclean's suggested triple, for a exc.read() that fails on an already-closed connection; same reasoning as the rest, a failed read shouldn't be worse than not reading. KeyError is gone — as noted, unreachable, since the block only calls .get().

Tests

test_map_patchset_to_pr_keeps_input_order_when_dates_cannot_be_compared asserted behaviour CPython does not guarantee — it passed only because two elements raise on the first comparison before any swap. Replaced with a four-email case (undated one in the middle) asserting the resulting order directly, plus an uncomparable-key case asserting the input order survives.

The error-body cases are now a parametrised sweep of all seven shapes. Six of the seven fail against the previous tuple — I checked by reverting the fix and re-running, so these are real regression tests rather than tests that merely pass.

test_map_patchset_to_pr_propagates_unexpected_sort_errors is kept as-is. It was a good test, it does what it claims, and it still passes — a RuntimeError from the key function propagates.

Verified locally: 25 tests pass, ruff check, ruff format --check, and mypy are clean on tools/sourcehut, and the workspace prek hooks pass.

Also worth crediting on the packaging change: the new dev group brings tools/sourcehut in line with 23 of the 25 tool projects, and your pins (ruff>=0.15.21, mypy>=2.3.0, pytest>=9.1.1) match the workspace root exactly, which is what that block's comment asks for. 18 of the tools have drifted to mypy>=2.1.0, so copying a neighbour would have been the easy wrong answer.

Thanks for this — the instinct to kill blanket except Exception was right, and the narrowing bug it surfaced in map_patchset_to_pr was worth finding on its own.


This review was drafted by an AI-assisted tool and
confirmed by an Apache Magpie maintainer. The maintainer
approving this PR has read the findings and signed off. If
something feels off, please reply on the PR and a maintainer
will follow up.

More on how Apache Magpie handles maintainer review:
CONTRIBUTING.md § Opening a pull request.

@potiuk
potiuk merged commit 3c64b79 into apache:main Jul 30, 2026
38 checks passed
@potiuk potiuk changed the title Narrow exception handlers Narrow sourcehut exception handlers Jul 30, 2026
@potiuk potiuk added contract:mail-archive Tool capability: mailing-list / forum archive reads contract:source-control Tool capability: branch / commit / diff / push (VCS) contract:tracker Tool capability: issue / board / label backend labels Sep 25, 2026
@potiuk potiuk added family:ci .github workflows, prek, validators family:tools tools/* labels Nov 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contract:mail-archive Tool capability: mailing-list / forum archive reads contract:source-control Tool capability: branch / commit / diff / push (VCS) contract:tracker Tool capability: issue / board / label backend family:ci .github workflows, prek, validators family:tools tools/*

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Narrow two broad exception handlers in the SourceHut adapter

3 participants