Skip to content

fix(harness): handle null usage and empty or malformed choices in response parsing - #400

Merged
msoedov merged 1 commit into
msoedov:mainfrom
brixtonpham:fix/harness-null-usage-empty-choices
Nov 26, 2026
Merged

msoedov merged 1 commit into
msoedov:mainfrom
brixtonpham:fix/harness-null-usage-empty-choices

Conversation

@brixtonpham

Copy link
Copy Markdown
Contributor

Problem

OpenAI-compatible providers (especially local/proxy servers and content-filtered responses) frequently return "usage": null or empty/malformed choices payloads. Currently both extract_response() (agentic_security_harness/loop.py) and JevDecider.decide() (agentic_security_harness/deciders.py) crash with unhandled AttributeError, IndexError, TypeError, or KeyError:

import httpx
from agentic_security_harness.loop import extract_response

req = httpx.Request("POST", "http://localhost")
extract_response(
    httpx.Response(200, json={"choices": [{"message": {"content": "ok"}}], "usage": None}, request=req)
)
# AttributeError: 'NoneType' object has no attribute 'get'

extract_response(httpx.Response(200, json={"choices": []}, request=req))
# IndexError: list index out of range

Solution

  • agentic_security_harness/loop.py (extract_response):
    • Guard usage = data.get("usage") with isinstance(usage, dict) before calling .get("cost") (preserving cost=None so Harness.attempt keeps cost_estimated=True).
    • Validate choices is a non-empty list and safely extract choices[0].message.content, raising a descriptive ValueError on empty or malformed payloads instead of raw IndexError/TypeError/KeyError/AttributeError.
  • agentic_security_harness/deciders.py (JevDecider.decide):
    • Validate the top-level JSON object, non-empty choices, string message.content, and parsed JSON object with a string action, raising descriptive ValueError on malformed decider responses.
    • Guard data.get("usage") with isinstance(usage, dict) so "usage": null yields 0.0 cost without crashing.
  • tests/harness/test_response_parsing.py:
    • Add 26 offline unit tests covering null/non-dict usage, empty/null/malformed choices, message, content, and decider JSON validation.

Testing

  • OPENAI_API_KEY="sk-fake" python3 -m pytest tests/harness/ -q: 66 passed
  • OPENAI_API_KEY="sk-fake" python3 -m pytest . -q: 644 passed, 4 skipped
  • pre-commit (black, flake8, flake8-docstrings, pyupgrade, pycln, codespell, poetry-check --lock): all passed

@msoedov msoedov 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, appreciate the patch!

@msoedov
msoedov merged commit 9acec47 into msoedov:main Nov 26, 2026
2 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.

2 participants