Repository navigation
feat(environment): discriminate multiplexed POST RPC operations in manifest and replay - #9204
saariuslystoned wants to merge 20 commits into
Conversation
…nifest and replay
[Medium impact] The PR appears safe to merge; no new blocking issue was established. SummaryAdds operation-aware tools for multiplexed
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
Capture["Recorded exchanges"] --> Parse["Bounded RPC and XSSI parsing"]
Parse --> Manifest["Manifest tools and operation identity"]
Manifest --> State["Read views and write plans"]
Manifest --> Match["Match probe path and operation"]
State --> Answer["State or recorded answer"]
Match --> Answer
Answer --> Compare["Compare with the captured live answer"]
Reviews (17) · Last reviewed commit: "chore: sync with upstream main" · Reviewed by Greptile |
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
There was a problem hiding this comment.
TL;DR: This is a code read. I ran nothing from the PR, and CI has not run on this head yet. The Greptile fixes I checked are in. One change isn't in the body. A rebuild renames tools, even on a path with just one GraphQL or JSON-RPC call.
Edit (7 Nov): I ran this PR at head ddd7229 in a VM, and the results are here.
I read the PR head e4d6b9d against its merge base 48f5f30. Main is now 99db80a, and none of main's new commits touch these files.
Worth a look
- Single-operation paths get new tool names. The group key always carries the operation kind and name when one is found (
EnvironmentManifestAccumulator.tslines 275 to 282). That happens even when a path has just one operation. Discrimination is on by default (line 213), andtoolNameadds the operation words (line 554). Say a capture has onePOST /graphqlcall namedGetViewer. A rebuild with this PR adds the words fromGetViewerto that tool's name (environmentManifestNames.tslines 120 to 127). The same goes for any JSON-RPC 2.0 endpoint. An agent or config that knows the old name would miss the tool after a rebuild. The body calls the contract change an additive optional field. Two fixes would work. Split a path only when two or more calls share it, or list the rename under breaking changes.
Nit
- The 64 KiB check measures two different things. The manifest checks the raw request text, spaces included (
rpcOperationSelector.tslines 110 to 111 and 255). The replay value path measures compact JSON instead (lines 114 to 140, called fromenvironmentReplay.tsline 109). A pretty-printed body just over 64 KiB is left undispatched in the manifest. At replay the same body can fit and get an operation. If the path also has discriminated tools, replay then refuses it (environmentReplay.tslines 117 to 127). It's rare, but one shared measure would keep the two sides in step.
Looks good
- Encoded batch names. The
f.reqcheck now usesURLSearchParams(bodyText).getAll("f.req")(rpcOperationSelector.tsline 265), so percent-encoded names are caught. - Comparison origin.
isProbeJsonLikenow uses the samehasBoundedXssiJsonResponsecheck as the manifest (environmentCompareProbe.tsline 144). - Old saved manifests still parse.
rpc_operationisexactOptional(environmentManifestSchema.tslines 49 and 50). Replay against an old manifest falls back to tools without an operation (environmentReplay.tsline 129). - Batches stay whole. A JSON array body is not a plain object, so GraphQL and JSON-RPC batches are left undispatched (
rpcOperationSelector.tslines 261 and 293). - Request bodies are bounded. The raw text is checked against 64 KiB before any JSON or form parsing (line 255).
Not run
- No build, no typecheck, no tests. Each point comes from reading the code.
- I did not check how persisted GraphQL queries are sorted into reads and writes. Only their name is known.
- I did not trace the derived-state path for an old saved bundle that has an XSSI endpoint and no RPC tools.
🤖 Written with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊
…atchexecute form bodies
|
TL;DR: I ran this PR at head ddd7229 in a VM, and the 7 changed test files pass on Node 22.23.4, 24.22.1 and 26.12.1. A capture with one operation on a path keeps its plain tool name again. CI has not run on this head. I tested the head alone, without merging main. Edit (7 Nov): I ran this PR again at head 83fc5eb in a VM, with a check of the XSSI item I left open here, and the results are here. What passed
My first point: one-operation paths keep their namesA build from a capture with one operation on a path, by commit:
So the rename I found at e4d6b9d is gone at ddd7229. A path with two operations still splits into two tools, as the PR intends. One thing to know. A bundle built from a one-operation capture holds The probe is my own script, not PR code. It feeds hand-made POST records to the PR's manifest builder ( My second point: the 64 KiB budgetI did not write a separate test for this. The PR has two tests for it, and both files passed on all three Node versions. I read both. Each one builds a GraphQL body that is over 64 KiB with its spaces, but under 256 bytes without them. That is my case:
I read the setup of both and did not run either one alone. Still not run
Thanks, saariuslystoned, for both of the fixes you made. Test setup
CommandsThe 7 files are the test files in npm --prefix ~/pr-9204/src ci --offline
npm --prefix ~/pr-9204/src run prepare
npm --prefix ~/pr-9204/src run test:prepare
npm --prefix ~/pr-9204/src run test:focused -- \
src/application/environment/environmentCompare.test.ts \
src/application/environment/environmentReplay.test.ts \
src/application/environment/environmentState.test.ts \
src/application/environment/environmentTools.test.ts \
src/domain/analysisView/EnvironmentManifestAccumulator.test.ts \
src/domain/analysisView/environmentStateQueryCalls.test.ts \
src/domain/analysisView/rpcOperationSelector.test.tsAll exited 0. The test command ran once per Node version: 7 files and 194 tests each time. The probe ran with const acc = new EnvironmentManifestAccumulator(1024 * 1024);
for (const spec of specs) acc.add(record(spec)); // hand-made POST records
const out = acc.finish();
console.log(out.value.tools.map((t) => t.name + (t.rpc_operation ? ` [rpc_operation ${t.rpc_operation.kind}:${t.rpc_operation.name}]` : "")));🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
|
TL;DR: I ran this PR at head 83fc5eb in a VM, and the 7 changed test files pass on Node 22.23.4, 24.22.1 and 26.12.1. Then I took the old XSSI fallback out of Edit (24 Nov): I ran the new head, 48f2191, in a VM, and the results are here. What passed
The count is 200, up from the 194 in my earlier comment at ddd7229. The six extra tests are two XSSI tests in I reran the tool-name probe from my earlier comment, on Node 24.22.1 only. It gives the same five lines at 83fc5eb as at ddd7229. A one-operation path keeps its plain name, and two operations on one path still split. Old bundle with an XSSI endpoint (open item in my review above)I removed the fallback in the VM copy only, by adding
Persisted GraphQL sorting (open item in my review above)The head adds Still not run
Test setup
CommandsThe 7 files are the test files this PR changes. None calls All exited 0. The test command ran once per Node version: 7 files and 200 tests each time. The probe is the same script as before ( The removal of the fallback, in the VM copy only: That run exited 1 with 3 failed and 35 passed. A second and third run added one 🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
…st-rpc-agentenv Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@CassieFox23 thanks for the review. Single-operation tool names stay plain. The 64 KiB check runs on the raw body before The persisted-GraphQL / legacy XSSI fallback in derive and environment state is still required. Removing it fails with "The state names a tool the manifest does not have". Persisted GraphQL classification tests passed in the post-merge focused run ( ☁️ |
Adopt main's prepare/commit split in the manifest accumulator: RPC operation and XSSI facts are admitted in prepare, and the operation map, JSON-like count and group fields are written only in the commit closure. Pass the manifest name to environmentToolDefinitions in the new test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Head branch was pushed to by a user without write access
With operations in separate POST buckets, a mutation whose response repeated the latest GET of /graphql passed the repeated-read check and became a query-body view. Reject declared mutations and subscriptions before any response- or path-based read inference. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@saariuslystoned thanks for the PR — there is 1 open review thread here:
Could you address or reply to this? Once it's resolved and CI is green we can take another look. |
|
@saariuslystoned also, this branch has merge conflicts with |
Merge 42bbf33 while preserving the lazy per-call RPC facts repair. Retain normalized media ownership, shared JSON helpers, and upstream environment admission fixes. Use the shared record predicate in the RPC selector to satisfy current architecture checks. Dependency-free regression and source checks pass; full dependency-backed validation remains with the coordinator.
|
TL;DR: On the new head, 48f2191, the seven changed test files pass on three Node versions: 205 of 205 tests. The last open review thread asked that a POST body not be parsed when the saved RPC facts already answer. A new test checks that, and it passes. My last comment tested head 83fc5eb on 8 November, with 200 tests in the same files. Thanks, saariuslystoned, for the answers on tool names and the 64 KiB check. Results
Not run
Test setupCommands🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
Summary
Discriminate multiplexed single-path HTTP
POSTRPC operations—GraphQL (operationName), JSON-RPC 2.0 / MCP (method), and Googlebatchexecute(f.req/ singlerpcidswith XSSI-guarded)]}'JSON responses)—across AgentEnv manifest accumulation, state partitioning, replay tool matching, and live/recorded environment comparison.Previously,
EnvironmentManifestAccumulator,EnvironmentStateAccumulator,environmentReplay, andenvironmentComparegrouped HTTP exchanges solely by(method, pathTemplate)and required rawisJsonLikeresponse bodies, collapsing distinct RPC operations on a sharedPOSTendpoint into a single tool and replay bucket while excluding XSSI-prefixedbatchexecuteresponses served astext/plainorapplication/x-javascript. No existing upstream issue is linked; this addresses a concrete capture-to-AgentEnv fidelity gap on multiplexed RPC endpoints.Problem and expected behavior
Modern web applications frequently multiplex unrelated read and write operations onto one
POSTpath:POST /graphqlorPOST /api/.../graphqlwith JSON body{"operationName":"GetViewer","query":"..."}).POST /rpcorPOST /mcpwith JSON body{"jsonrpc":"2.0","method":"tools/list","id":1}).batchexecuteRPCs (POST /_/.../data/batchexecutewithapplication/x-www-form-urlencodedf.req=[[["RpcMethodId","...",null,"generic"]]]or singlerpcids=RpcMethodId, returning)]}'\n-prefixed or length-framed JSON payloads).Expected observable behavior:
POSTpath_template, unambiguous RPC operations produce distinct manifest tools with deterministic snake_case names (appending tokenized operation words before_by_<params>), carry optionalrpc_operation: { kind, name }metadata on each discriminated tool, keep query-identifiedbatchexecuteoperations separated even wheninclude_query_parameter_namesisfalse, and still participate in path-segment templating ({param}) within the same RPC operation; non-overlapping single-operation(POST, pathTemplate)routes keep their pre-existing tool name and omitrpc_operationwhile still participating in read-only RPC state classification and advertising string-or-objectbodyinputs forbatchexecuteform payloads.EnvironmentStateAccumulatorbuckets (state.viewswithreason: "query-body"vs.state.writes) instead of colliding on one route key, including single-operation read-only RPC routes and multi-operation / fragment-bearing GraphQL documents whereoperationNameselects either aqueryormutationdefinition.)]}'\n/)]}',\n) JSON (including guardednull) and length-framedbatchexecuteresponses within the 64 KiB UTF-8 XSSI limit on non-JSON-like JavaScript/empty media types (and up to 256 KiB on JSON-like media types) are retained and parsed consistently across manifest eligibility, state extraction, replay, and probe origin/body comparison.POSTrequests inmatchReplayTool/environmentCompareevaluateselectRpcOperationFromTextagainst the same bounded 64 KiB raw UTF-8 wirebodyTextas manifest accumulation across fittingPOSTtemplates (breaking specificity ties by literal segment count) and dispatch only to the matchingrpc_operationtool on multiplexed paths (refusing unrecorded operations on discriminated endpoints rather than cross-dispatching), while ordinary RESTPOSTroutes, single-operationPOSTroutes, anonymous GraphQL queries, malformed payloads, >64 KiB raw wire bodies (even when compact JSON would be smaller), and mixed multi-operation batches (including percent-encodedf%2Ereqform fields) preserve existing(method, pathTemplate)behavior.rpc_operationexisted preserve state derivation and confirmed REST writes via non-discriminated fallback inderiveEnvironmentState.Change and scope
Follow the contribution scope.
Not applicable for a maintainer scope decision: this change operates strictly on already-captured network exchange data and local AgentEnv manifest/state/replay projection within existing boundaries, introducing no new provider, process execution, injection, target mutation, or protection recovery.
Chosen approach:
src/domain/analysisView/rpcOperationSelector.ts(zero regex backtracking, strict1..128char operation name limit,64 KiBUTF-8 request body and non-JSON-like XSSI response cap,8 KiBquery string cap,URLSearchParamsdecoding for percent-encodedf.req/rpcidsfields) plus XSSI guard detection and bounded JSON/frame parsing.rpcOperation(rpc_operationinenvironmentManifestSchema.ts) throughEnvironmentManifestAccumulator(reading raw query strings for/batchexecuteindependently ofinclude_query_parameter_names),environmentManifestRules.ts(ToolGroupmerging and sibling-variance/pair rebucketing keys), andenvironmentManifestNames.ts(deterministic tool naming and sort order).rpc_operation, bounded XSSI body parsing, and pre-RPC manifest compatibility (discriminateRpc = falsefallback inderiveEnvironmentStatealongsidewrites/originchecks instateMismatch) throughEnvironmentStateAccumulator,environmentState.ts,environmentStateRules.ts, andenvironmentStateQueryCalls.ts(linear lexical scanning of top-level GraphQLqueryvs.mutation/subscriptiondefinitions skipping fragment headers).matchReplayToolinsrc/application/environment/environmentReplay.tsand wiredenvironmentCompareMatch.ts,environmentCompareProbe.ts,environmentSource.ts, andenvironmentTools.ts(toolDescriptionRPC annotation and{ oneOf: [{ type: "string" }, { type: "object" }] }body input schema forbatchexecuteform-urlencoded tools), and updated owning docs indocs/guides/web/web-network-captures.mdanddocs/agent-environments.md.batchexecuteenvelopes into synthetic sub-exchanges (ambiguous batches safely fall back toundefined).Contract and boundary impact
src/domain/analysisView/rpcOperationSelector.tsowns bounded RPC operation discrimination and XSSI JSON parsing;EnvironmentManifestAccumulatorandEnvironmentStateAccumulatorare the earliest changed domain stages, consumed byenvironmentSource,environmentState,environmentReplay,environmentTools, andenvironmentCompare.rpc_operation?: { kind: "graphql" | "json-rpc" | "batchexecute"; name: string }field onenvironment-manifesttool entries; generated AgentEnv MCP tool descriptions include(graphql "<name>")/(json-rpc "<name>")/(batchexecute "<name>"), andbatchexecutetools accept string or objectbodyinputs. Owning documentation indocs/guides/web/web-network-captures.mdanddocs/agent-environments.mdis updated accordingly. Top-level REA CLI commands and static MCP tool catalog entries are unchanged (npm run mcp-catalog:checkandnpm run docs:checkpass).record_ordinals,evidenceId, status codes, excluded exchange accounting, and replay provenance; pre-existing saved manifests withoutrpc_operationcontinue to derive state, confirm REST writes, and replay identically tomain.docs/public/product-catalog.json), package, or installation impact: none (npm run metadata:check,npm run mcp-catalog:check, andnpm run docs:checkpass with zero generated catalog drift).Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.
Evidence and regression coverage
src/domain/analysisView/rpcOperationSelector.test.ts: unit coverage for GraphQL (operationNamewithquery, persisted-queryextensions, and/graphqlpaths), JSON-RPC 2.0methoddiscrimination, Googlebatchexecutef.req(including percent-encodedf%2Ereqmixed-batch non-fallback) and single-rpcidsextraction, fallback cases, raw-wire >64 KiB UTF-8 byte limits, and XSSI)]}'direct (null, objects, arrays) + length-framed response parsing and 64 KiB eligibility bounds.src/domain/analysisView/EnvironmentManifestAccumulator.test.ts&src/domain/analysisView/environmentStateQueryCalls.test.ts: verifies distinct manifest tools andrpc_operationmetadata when 2+ groups share an equal or overlappingPOSTpath_template(e.g.,/api/orgs/org-1/graphqlvs./api/orgs/{org_id}/graphql), unchanged pre-existing tool names (rpc_operation: undefined) on non-overlapping single-operationPOSTroutes, query-onlybatchexecuteseparation wheninclude_query_parameter_namesisfalse,{org_id}sibling-variance path templating within an RPC operation, XSSI response retention, and read vs. write partitioning inEnvironmentStateAccumulator(including single-operation read-only RPC routes, persisted GraphQLGetViewervs.UpdateProfile/Viewerclassification whenbody.queryis absent, and shared multi-operation / keyword-namedfragmentGraphQL documents).src/application/environment/environmentState.test.ts,src/application/environment/environmentTools.test.ts, &src/application/environment/environmentReplay.test.ts: verifies saved pre-RPC manifest state compatibility (preserving derived state and confirmed REST writes even when the capture also contains XSSI endpoints), single-operationbatchexecutestring-or-objectbodyschema generation, end-to-end manifest projection ->environmentServeSource->matchReplayTool+replayEnvironmentToolacross equal and overlapping GraphQL templates, unrecorded operation rejection, pretty-printed >64 KiB wire-body fallback parity, JSON-RPCtools/listvs.tools/call, XSSI-framedbatchexecute, and unchanged ordinary REST / single-operationPOSTroutes.src/application/environment/environmentCompare.test.ts: verifiescompareEnvironmentmatches live GraphQL (including overlapping literal +{org_id}templates), JSON-RPC 2.0 (including pretty-printed >64 KiB raw-wire request parity), single-operation RPC routes (including single-operationbatchexecuteform payloads), and XSSIbatchexecuteprobes (including >64 KiB XSSI origin-selection parity) without cross-tool or cross-origin mismatches.main, feeding multiple GraphQLoperationNamecalls on/graphqlor JSON-RPC methods on/rpcintoEnvironmentManifestAccumulatorproduces a singlepost_graphql/post_rpctool, andbatchexecuteapplication/x-javascript)]}'\nresponses are excluded asnon-json.environment-manifesttools emitnamevalues such aspost_graphql_get_viewer,post_rpc_tools_list, andpost_appui_data_batchexecute_get_itemsalongsiderpc_operation: { kind, name }.Google Chrome 156.0.8078.80capture_browser_scenario->export_environment_bundle->rea environment-serve(stateful and--replay-only) round-trip; Linux/Windows CI matrix runners execute on push.For evidence-bearing changes:
Validation performed
npx vitest run src/domain/analysisView/ src/application/environment/ src/application/analysisView/ src/server/environment/ tests/boundary/cli/environmentCompareCli.test.ts tests/boundary/mcp/environmentServeWritesMcp.test.ts— passed (116test files passed,2345tests passed).npx oxfmt --check .— passed (7120files checked, all formatted).npm run check:fast— passed (typecheckandlint:2successful tasks,0errors).npm run verify:architecture-guards— passed (2520source files checked).npm run verify:test-discovery— passed (3158test files discovered once).npm run scan:todos— passed (No tech-debt markers found).npm run jscpd— passed (5803files checked, within threshold).npm run knip— passed (Knip found no issues).npm run knip:production— passed (0errors;0advisory candidates in touched files).npm run lint:typed— passed (6587files,0errors).npm run metadata:check— passed (exit0).npm run mcp-catalog:check— passed (4successful tasks, exit0).npm run docs:check— passed (6successful tasks +tests/conformance/readmeConsistency.test.ts9/9passed).main(08637b0c2) + multi-Node matrix (v22.23.4,v24.22.2,v26.13.0): clean merge (0conflicts),npm run check:fastpassed, and all7changed test files (200/200tests) passed across Nodev22.23.4,v24.22.2, andv26.13.0; mutation probe onrpcCallReadsOnly(case "absent") failed the 2 persisted-GraphQL tests inenvironmentStateQueryCalls.test.tsas expected before restore.Google Chrome 156.0.8078.80capture_browser_scenario->export_environment_bundle->rea environment-serveHTTP MCP verification (v24.22.2): exported9manifest tools across REST, declared GraphQL query/mutation, persisted GraphQL query (withoutbody.query), JSON-RPC 2.0 read/write, single-ID XSSIbatchexecute, and unsplit multi-ID XSSIbatchexecute; verified all6/6read-only tools in stateful mode and all9/9tools in--replay-onlymode (isError: false,)]}'XSSI prefix stripped to structured JSON).Compatibility, safety, and release
rpc_operationisexactOptional()inenvironmentManifestSchema; pre-existing saved manifests withoutrpc_operationcontinue to load, derive state, serve confirmed writes, and match unchanged, single-operationPOSTroutes keep their existing tool names and schemas on rebuild, and captures recording multiple distinct RPC operations on a sharedPOSTroute now emit one operation-qualified tool per operation instead of collapsing them onto a single conflicting route bucket.v22.23.4,v24.22.2, andv26.13.0, including liveGoogle Chrome 156.0.8078.80capture_browser_scenario->export_environment_bundle->rea environment-serveHTTP MCP replay. Hopper/Ghidra providers are not touched.64 KiBUTF-8, query inspection at8 KiB, operation names at128ASCII characters, XSSI multi-frame parsing is bounded by input slice indices and accumulator byte budgets, and character-code scanners avoid backtracking regular expressions.Author readiness
Human owner: @saariuslystoned
Before merge
type(scope): outcome.