Skip to content

fix(langchain): opt-in fail-closed and quarantine blocking; scan structured tool outputs (#7) - #9

Merged
TARSDrakon merged 3 commits into
mainfrom
loop/7-langchain-fail-closed
Oct 17, 2026
Merged

TARSDrakon merged 3 commits into
mainfrom
loop/7-langchain-fail-closed

Conversation

@TARSDrakon

Copy link
Copy Markdown
Contributor

Closes #7

Design

Defaults are unchanged for API errors and QUARANTINE. The only default behaviour change is the tool-output scanning fix.

fail_closed: bool = False (both handlers, shared _configure)

  • With fail_closed=True and raise_on_block=True, a ShieldCortexError from a scan (401, 429, 5xx, timeout, and any other subclass the clients raise) is re-raised as ContentBlockedError via raise ... from exc. error.result is None, error.__cause__ is the original error, and the message is ShieldCortex blocked <source>: scan failed: <error>. LangChain stops the run.
  • fail_closed=True with raise_on_block=False raises ValueError at construction. Without raising there is nothing that can stop the run, so a silent no-op option would be misleading.
  • Default: log and skip, as before.
  • No new exception class. ContentBlockedError.__init__ takes result: ScanResult | None and an optional reason. The attribute's static type widens to Optional, but runtime behaviour for verdict blocks is unchanged.

block_on_quarantine: bool = False

  • When True, a QUARANTINE verdict goes through the same path as BLOCK: a warning, or ContentBlockedError with raise_on_block=True.

Tool output reduction (_tool_output_text, used by both on_tool_end)

  • str: scanned as is. Empty strings are still scanned, so the existing test_empty_tool_input_and_output_are_still_scanned keeps passing.
  • Object with a string .content (ToolMessage / BaseMessage): that content.
  • List .content (content blocks): str items plus the string "text" of dict items, joined with \n.
  • Anything else: json.dumps(obj, default=str), falling back to str(obj) on TypeError/ValueError (for example circular references).
  • None, and non-string outputs that reduce to empty text, are not scanned.

The module docstring, both class docstrings, the README LangChain section (with an options table) and the CHANGELOG [Unreleased] section are updated.

LangChain caveat, now documented in the README: under ainvoke, a tool with no coroutine has its async-handler callbacks run by LangChain's _run_coros, which logs and swallows exceptions. A block there is scanned and logged but does not propagate. Tools with a coroutine propagate normally. This is the same family as the existing "async handler cannot propagate from invoke" note.

Tests added (tests/integrations/test_langchain.py, each sync and async)

  • fail_closed=True, raise_on_block=True: 401, 503 and a ReadTimeout raise ContentBlockedError with __cause__ set to the ShieldCortexError (AuthError for 401, status_code == 503) and result is None.
  • Default: the same three errors are logged and skipped, and the run returns normally (pins the fail-open default).
  • fail_closed=True without raise_on_block raises ValueError.
  • block_on_quarantine=True: QUARANTINE raises. Default: QUARANTINE does not raise.
  • A StructuredTool (langchain_core.tools) invoked with a tool call returns a ToolMessage, which is scanned and raises. A content-block ToolMessage scans "first\nsecond". A dict output is scanned as JSON and raises. A None output makes no request.
  • A unit test of the reduction helper covers empty content, image-only blocks, the default=str path and the circular-reference str() fallback.

Gate receipts (mine, local venv with .[dev,langchain], langchain-core 1.6.12)

  • ruff check src/: exit 0, All checks passed!
  • mypy src/shieldcortex/ --ignore-missing-imports: exit 0, Success: no issues found in 12 source files
  • python -m pytest -q: exit 0, 162 passed in 2.18s

🤖 Generated with Claude Code

TARSDrakon and others added 3 commits October 17, 2026 00:42
…ctured tool outputs (#7)

- fail_closed (default False) on both handlers: with raise_on_block=True a
  ShieldCortexError from a scan raises ContentBlockedError (result=None,
  original error chained as __cause__). fail_closed=True without
  raise_on_block=True raises ValueError at construction.
- block_on_quarantine (default False): QUARANTINE is handled exactly like
  BLOCK.
- on_tool_end reduces non-string outputs to text via one shared helper
  (.content string, joined text parts of a content-block list, JSON with
  str() fallback) and scans them; None and empty reductions are skipped.
- Docstrings, README and CHANGELOG updated; defaults unchanged for API
  errors and QUARANTINE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in PR #8 (path-parameter encoding). CHANGELOG.md conflict in
[Unreleased] resolved by keeping both entries under one "Fixed" heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r ainvoke; add regression matrix

B1: with the async handler, LangChain runs a sync-only tool's ainvoke
through invoke in a worker thread and logs and swallows every exception
the async handler raises (callbacks/manager.py _run_coros ignores
raise_error). Neither BLOCK nor fail_closed scan-error raises stop that
tool. Enforcing this from the handler would mean patching LangChain, so
the contract is narrowed in the module docstring, README and CHANGELOG
(new "Known limitation"), with the workarounds: give the tool a coroutine,
or pass the sync handler with a sync client, whose exceptions propagate
on that route.

Tests:
- Real sync-only StructuredTool (no coroutine) under ainvoke: the async
  handler with fail_closed lets the tool run and return on BLOCK and 503,
  for tool_input and tool_output (characterises LangChain's behaviour so a
  change is noticed); the sync handler raises, and on tool_input the tool
  never runs.
- N2: ToolMessage list content with a non-text dict block is dropped, not
  JSON-encoded; a bare list return is stringified by LangChain and scanned.
- N3: fail_closed matrix over chain, LLM, chat and tool input/output hooks
  x 401/429/503/timeout/base ShieldCortexError in sync and async handlers,
  plus raw httpx.ConnectError propagating unwrapped.

N1: README and CHANGELOG migration note for ContentBlockedError.result
being typed ScanResult | None (never None without fail_closed, but type
checkers ask callers to narrow).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@TARSDrakon
TARSDrakon merged commit 069d2d3 into main Oct 17, 2026
5 checks passed
@TARSDrakon

Copy link
Copy Markdown
Contributor Author

Independent review (OpenAI-family lane), round 2 delta at exact head 3a22734c74eb9826d401521854305af0f136c3a9: APPROVE.

  • Round-1 B1 resolved: README/CHANGELOG/module docs now state that with the async handler, BLOCK verdicts and fail_closed raises do not stop a sync-only tool reached through ainvoke, and give the supported workarounds; a regression test with a genuinely sync-only StructuredTool pins that behaviour (input and output, BLOCK and HTTP 503), and a workaround test shows the sync handler raising before the tool runs.
  • N1 (None-aware migration example), N2 (list-content block drop vs bare-list JSON encoding) and N3 (hook x error matrix across both handlers, plus unwrapped httpx.ConnectError) resolved. No existing assertion weakened.
  • CI 3.9-3.13 green at this head.

Merged with the head pinned.

@CASE-Drakon CASE-Drakon mentioned this pull request Oct 17, 2026
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.

LangChain handlers fail open on API errors/QUARANTINE and skip non-string tool outputs

1 participant