Add exact LangChain policy middleware - #38
Conversation
|
Warning Review limit reached
Next review available in: 46 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
Summary by CodeRabbit
WalkthroughAdded an optional LangChain and LangGraph policy adapter. It validates exact tool registries, enforces policy on final arguments, supports sync and async middleware, handles review interrupts, binds approvals to call fingerprints, and adds tests, documentation, examples, and CI contracts. ChangesLangChain integration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Agent as LangChain agent
participant Middleware as LangChainToolPolicy
participant Policy as Policy engine
participant Checkpointer as LangGraph checkpointer
Agent->>Middleware: invoke tool with final arguments
Middleware->>Policy: evaluate normalized call
Policy-->>Middleware: review decision
Middleware->>Checkpointer: persist interrupt and fingerprint
Checkpointer-->>Agent: return review interrupt
Agent->>Middleware: resume with approval evidence
Middleware->>Policy: re-evaluate exact call
Middleware-->>Agent: execute tool or return rejection
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/LANGCHAIN.md`:
- Around line 7-19: Update the LangChain example and its documented dependency
contract so the command using the langchain extra can run without undeclared
packages: either add the package providing PostgresSaver to the langchain extra,
or replace PostgresSaver with InMemorySaver and note that production deployments
require durable LangGraph checkpointing. Keep the create_agent example and
requirements-langchain.lock behavior consistent with the selected approach.
In `@src/samsarix_ethics/langchain.py`:
- Around line 230-242: Update _verify_response to encode both tool_call_id
operands and both tool_call_fingerprint operands to bytes before passing them to
hmac.compare_digest. Preserve the existing mismatch condition and ensure
non-ASCII identifiers raise the typed LangChainIntegrationError rather than a
TypeError.
In `@tests/test_langchain.py`:
- Around line 378-396: Update the invalid request coverage around
middleware.wrap_tool_call by pairing every malformed request with its specific
expected exception type instead of accepting the entire exception union.
Parameterize the cases or use request/exception tuples, and include the case
index or identifying input in parametrized test IDs so failures identify which
request regressed.
- Around line 431-449: Extend
test_async_middleware_authorizes_before_awaiting_handler after the
approved-review assertions with a rejected async review, asserting
awrap_tool_call returns the expected rejection ToolMessage and that calls
remains unchanged, proving the handler is not awaited.
- Around line 291-311: Replace the expected tool_call_fingerprint in the payload
assertion with a value computed directly from the relevant binding fingerprint
oracle, using the explicit expected tool-call inputs such as call ID, actor, and
request data. Do not derive the expectation through adapter.approval_for; keep
the assertion independent from _review_payload and _request.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 6dfb32e1-43c7-4f19-90fc-af403c32c968
⛔ Files ignored due to path filters (1)
requirements-langchain.lockis excluded by!**/*.lock
📒 Files selected for processing (20)
.github/workflows/ci.ymlCHANGELOG.mdCONTRIBUTING.mdREADME.mdRELEASING.mdROADMAP.mdSECURITY.mddocs/ADOPTION.mddocs/API.mddocs/ARCHITECTURE.mddocs/LANGCHAIN.mddocs/PRODUCTIZATION.mdexamples/langchain_policy_middleware_demo.pyintegration_tests/test_langchain_sdk.pypyproject.tomlrequirements-langchain.txtsrc/samsarix_ethics/__init__.pysrc/samsarix_ethics/langchain.pytests/test_langchain.pytests/test_public_api.py
What changed
Why
LangChain is a major agent runtime, but model-proposed tool metadata and a plain human-approved boolean are not sufficient authorization evidence. This adapter gives applications a public, reproducible integration that exact-matches the trusted tool registry and fails closed before a tool handler runs.
Impact and boundaries
The base package keeps zero runtime dependencies; LangChain imports only when the optional factory is called. Applications must place Samsarix last in the middleware list and retain responsibility for checkpointer protection, reviewer authentication, expiry, one-time resume, thread authorization, and non-transactional side effects.
Validation
python -m ruff check src tests integration_tests examplespython -m mypy srcpython -m pytest— 531 passed, 95.72% branch-aware coveragelangchain==1.3.14twine checkpip checkrequirements-langchain.lock— no known vulnerabilities