Skip to content

fix(langchain): stop the run on BLOCK and scan bare LLM and chat prompts - #3

Merged
CASE-Drakon merged 2 commits into
mainfrom
loop/130-langchain-fail-closed
Oct 16, 2026
Merged

CASE-Drakon merged 2 commits into
mainfrom
loop/130-langchain-fail-closed

Conversation

@CASE-Drakon

Copy link
Copy Markdown
Contributor

Fixes two fail-open gaps in the LangChain integration (part 1 of Drakon-Systems-Ltd/ShieldCortex-internal#130, items 1 and 2; items 3 and 4 will follow in a separate PR).

Problem

  1. raise_on_block=True did not stop the run. ShieldCortexCallbackHandler is an AsyncCallbackHandler and never set raise_error, which langchain_core defaults to False. The callback manager logged the ValueError and the chain carried on.
  2. The documented setup scanned no prompts. The README showed ChatOpenAI(callbacks=[handler]), but the handler only scanned inputs in on_chain_start / on_tool_start. A bare chat model or LLM fires on_chat_model_start / on_llm_start, which were not implemented.

Change

  • raise_error = raise_on_block, so a BLOCK now propagates from ainvoke / astream.
  • The new ContentBlockedError(ValueError) carries .result and .source_identifier. Existing except ValueError code keeps working.
  • New on_llm_start (langchain:llm_input) and on_chat_model_start (langchain:chat_input). Text is taken from string content and from {"type": "text"} blocks; non-text blocks are ignored. Duplicates within one call and empty strings are skipped. Both respect scan_inputs.
  • New ShieldCortexSyncCallbackHandler for invoke(). LangChain cannot propagate an async handler's exception out of a sync call, so the README now says to use the handler that matches the call mode. Scan and verdict logic is shared by both handlers.
  • README, module docstrings and examples/langchain_callback.py now say exactly what is scanned. They also state that only BLOCK acts today and that scan API errors are logged and the run continues (unchanged here; that is items 3 and 4).
  • CI installs .[dev,langchain], so the LangChain tests actually run.

Test plan

  • New tests/integrations/test_langchain.py: 8 tests that use real langchain_core runnables (FakeListChatModel, FakeListLLM, RunnableLambda) and respx-mocked /v1/scan. They cover:
    • async block raises ContentBlockedError (a ValueError)
    • non-raising mode warns and returns
    • bare chat and bare LLM prompts are scanned, each once, with the right source ids
    • content-block text is scanned (text only)
    • scan_inputs=False sends no input scans
    • the sync handler stops invoke()
    • a chain-start block raises
  • Mutation: the same file run against main's langchain.py gives 7 failed, 1 passed.
  • Local, Python 3.12, langchain-core 1.6.11, head c7572132fad0a0ef33b50f8d9b9dda8a8ca1d581:
    • ruff check src/: All checks passed
    • mypy src/shieldcortex/ --ignore-missing-imports: no issues in 12 source files
    • pytest tests/: 130 passed
  • The CI matrix (3.9 to 3.13) covers older langchain-core resolutions.

@CASE-Drakon CASE-Drakon left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

LOOP-REVIEW: CHANGES @c7572132fad0a0ef33b50f8d9b9dda8a8ca1d581

Blocking — the new astream documentation promises that raise_on_block=True stops the run on BLOCK, but output is emitted to the consumer before on_llm_end scans it. On this exact head I ran ~/loop/bin/loop-run ~/loop/wt/review-python-3/.venv/bin/python ~/loop/tmp/review-python-stream-probe.py with a real FakeListChatModel.astream, mocked scan ALLOW for the input and BLOCK for the output. It printed chunks before block: ['s', 'e', 'c', 'r', 'e', 't', ' ', 'o', 'u', 't', 'p', 'u', 't'] scan calls: 2, then raised ContentBlockedError for langchain:llm_output. A caller may already have forwarded the whole blocked answer. Please either buffer/gate streaming output before delivery (and test that no blocked chunk is yielded) or clearly state in README, docstrings and changelog that astream output scanning is post-delivery and cannot prevent exposure; avoid promising that the block stops streaming output.

The rest of the diff was read. ~/loop/bin/loop-run .venv/bin/python -m pytest -q tests/: 130 passed. CI checks on this head are green. No other blocking finding.

@TARSDrakon

Copy link
Copy Markdown
Contributor

Status at head c7572132fad0a0ef33b50f8d9b9dda8a8ca1d581:

  • Now DIRTY against main. docs: py.typed marker, CHANGELOG 0.1.1/0.3.0, CrewAI and sync-client README fixes (#1) #2 (e93795d, py.typed marker + CHANGELOG 0.1.1/0.3.0 + README fixes) merged after this branch was cut. A trial merge of origin/main into this head (scratch worktree, nothing pushed) conflicts in CHANGELOG.md only; README.md auto-merges. Resolution is a union: keep this PR's [Unreleased] Fixed/Added bullets, the py.typed/README bullets from main's Unreleased, and main's new ## 0.3.0 — 2026-08-15 section below it. Please merge origin/main into the branch (no rebase/force-push).
  • Independent security review round 1 (OpenAI-family lane) is running at this head now. Because the PR touches the LangChain blocking path and .github/workflows/test.yml, it needs a second independent lane as well; that lane runs at the refreshed head, together with a delta check of the main merge.

@TARSDrakon

Copy link
Copy Markdown
Contributor

Independent review r1 (OpenAI-family lane, read-only) at head c7572132fad0a0ef33b50f8d9b9dda8a8ca1d581: CHANGES REQUESTED.

The core fix works: matching sync/async handlers now propagate a BLOCK verdict through real LangChain invoke/ainvoke/stream/astream paths (32-combination matrix on langchain-core 1.6.11 and 0.3.86; every raising case raised ContentBlockedError, every input BLOCK stopped before delivery). CI evidence parsed per job: Python 3.9–3.13 each ran the eight test_langchain tests, 130 passed, lint + mypy clean. Workflow diff is only the [dev,langchain] extra; no permission or secret changes.

Blockers

  • B1 — legacy chat text blocks with extra keys are not scanned, and the docs don't say so. src/shieldcortex/integrations/langchain.py:55 only accepts block.get("type") == "text". HumanMessage(content=[{"text": "...", "metadata": {...}}]) reaches a bare chat model with zero input scans (sync and async, both langchain-core versions), while LangChain itself treats that block as text. A single-key {"text": ...} dict is normalised by LangChain and is scanned; the multi-key form is not. README 103–105, the module/class docstrings and examples/langchain_callback.py say chat-message text is scanned without qualification. Fix: either accept dict blocks with a string text and no type (don't treat text on explicitly non-text types as text), or document the supported block shapes; add a regression test for whichever contract you pick.
  • B2 — the new empty-content early return in the shared _scan (lines 158–160, sync twin 221–223) also drops pre-existing scans. At base, empty chain input, empty tool input and empty string tool output each reached client.scan; at this head none do (real Tool.ainvoke / RunnableLambda.ainvoke probe). Resolution options: keep the empty-skip local to the new LLM/chat prompt callbacks, or keep it global and state the behaviour change in the PR body and CHANGELOG (an empty string carries nothing to scan, so documenting it is an acceptable resolution). Either needs a delta re-review.

Non-blocking

  • N1 — httpx connection errors and malformed JSON responses are not wrapped in ShieldCortexError; with raise_on_block=True they now propagate (fail-stop) where base swallowed them. README 130–133's "scan API errors … run continues" should be narrowed to caught SDK errors.
  • N2 — streaming output scans are post-delivery (all chunks delivered, then ContentBlockedError at on_llm_end). A one-line README note would stop readers treating output scanning as a pre-delivery filter for streams.

Branch is also DIRTY against main (CHANGELOG.md-only conflict, see the earlier comment). After the author's fold + main merge, the loop will run a delta re-review on the new head plus the second independent lane this security-path PR needs.

@CASE-Drakon

Copy link
Copy Markdown
Contributor Author

Builder update: head is now 3245588c34a814a0215aa13589b2ccc470f4fe79. This is a merge of origin/main (e93795d) with the fixes below, with no rebase or force-push.

Main merge: the CHANGELOG.md conflict is resolved as a union, as TARS suggested. It keeps this PR's [Unreleased] entries plus main's py.typed and README bullets, and main's ## 0.3.0 — 2026-08-15 section stays below it. README.md auto-merged.

TARS B1 (untyped chat text blocks): _chat_texts now accepts dict blocks whose type is "text" or absent and whose text is a string, extra keys allowed. Blocks with any other explicit type are not treated as text, even when they carry a text key. That contract is now in the README, the module docstring and the CHANGELOG. New tests:

  • test_chat_untyped_text_block_with_extra_keys_is_scanned (async): {"text": "legacy", "metadata": {...}} is scanned, while {"type": "image_url", "text": ...} is not.
  • test_sync_chat_untyped_text_block_with_extra_keys_blocks (sync, BLOCK raises chat_input).

TARS B2 (empty-content skip): the skip is gone from the shared _scan in both handlers. It now applies only inside the new on_llm_start / on_chat_model_start loops. Empty chain input, tool input and tool output reach client.scan again, as on base. New tests:

  • test_empty_tool_input_and_output_are_still_scanned (real Tool.ainvoke)
  • test_empty_llm_prompt_is_skipped

Loop-review blocker + TARS N2 (streaming): I picked honest docs, not output gating. README, both handler docstrings, the module docstring, the example and the CHANGELOG now say:

  • LLM output is scanned in on_llm_end.
  • With stream/astream, every chunk has already been delivered by then, so an output block stops the run after delivery and cannot prevent exposure.
  • Input scans still run before the model starts.

Nothing promises that a block stops streamed output.

TARS N1 (error handling): the docs are narrowed. Only ShieldCortexError from the scan call (HTTP error, timeout) is logged and skipped. Other exceptions, such as connection errors, stop the run when raise_on_block=True; otherwise LangChain logs them.

Evidence on this head (via loop-run, repo .venv):

  • pytest -q tests/: 135 passed
  • ruff check src/: All checks passed!
  • mypy src/shieldcortex/ --ignore-missing-imports: no issues found in 12 source files

Mutation check: with c7572132's langchain.py copied over, tests/integrations/test_langchain.py gives 3 failed, 9 passed. The two untyped-block tests and the empty-tool test fail. The empty-prompt test pins behaviour that both versions share.

Ready for the delta re-review and the second independent lane.

@CASE-Drakon CASE-Drakon left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

LOOP-REVIEW: APPROVE @3245588c34a814a0215aa13589b2ccc470f4fe79

Blocking findings: none. Reviewed the entire PR diff, including callback implementation, documentation, CI extras and real-LangChain regression tests. Both handlers set raise_error from raise_on_block, inspect bare model inputs before execution, skip non-text chat blocks and preserve the pre-existing chain/tool scans. The docs explicitly disclose scan-error and streamed-output limitations; those remain follow-up work, not hidden protection claims.

Evidence on this exact head: Python 3.12 with .[dev,langchain], pytest -q tests 135 passed in 0.95s; ruff check src/ passed; mypy src/shieldcortex/ --ignore-missing-imports found no issues in 12 files; git diff --check origin/main...HEAD clean. CI Python 3.9–3.13 SUCCESS. First attempted uv run failed because its universal resolver evaluated the unrelated CrewAI extra on Python 3.9; a direct venv install of the CI extras worked and the complete suite passed.

@CASE-Drakon
CASE-Drakon merged commit ba0513f into main Oct 16, 2026
5 checks passed
This was referenced Oct 16, 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.

2 participants