Repository navigation
fix(#7681): bind the HTTP session transaction on the ten Grafana and Prometheus /api/v1/ts routes - #7723
Conversation
…Prometheus /api/v1/ts routes Issue #7402 moved the three documented /api/v1/ts routes onto DatabaseAbstractHandler, which is the only handler base class that reads arcadedb-session-id. The other ten routes registered under the same prefix did not move, and each carried the hand-rolled checkAuthorizationOnDatabase call whose own javadoc said it existed "Because these handlers do not extend DatabaseAbstractHandler". All ten now extend it, so a request carrying arcadedb-session-id runs inside that session: under its lock, on its principal, with its idle timer refreshed. POST /prom/write, the one write among them, answers true to rejectsUnresolvableSession() so a stale id is refused rather than ingested outside the transaction the caller believes it is inside; the nine reads answer requiresTransaction() false and degrade, the same split #7402 established. AbstractBinaryHttpHandler was reparented rather than duplicated: its only two subclasses are the Prometheus remote read and write handlers, and both had to move. Its byte body moved from an instance field of what is a singleton handler onto the exchange, which is the shape of #7683 in the class that holds the byte body - adding the session resolution between parseRequestPayload and execute widens that window rather than narrowing it. PostPrometheusWriteHandler opens its own begin/commit, and now does so only when this request does not already have a transaction. Inside a session it would otherwise push a nested one, and DatabaseContext caps nesting at 3 - a depth the auto-create path needs, so a remote write that created a type inside a session failed with "Exceeded number of 3 nested transactions" wrapped as a SchemaException naming the type. The three specs document the header on all thirteen operations; the five shared paragraphs moved to SpecBuilders so the three contributors cannot drift apart on what it means. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
Warning Review limit reachedNext included review available in 15 minutes. View limit detailsLimit details: You’ve used all 4 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (18)
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 |
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 0 |
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
ReviewSolid, well-scoped fix. I read through the full diff (all 17 changed files) plus Correctness
Test coverageThe new Nits
Worth double-checking, not blocking
Nothing else jumped out - the transaction/session semantics match the established |
…que import claude-review on PR #7723: GetPromQLQueryHandler and GetPromQLQueryRangeHandler were left with a double blank line between the last import and the class javadoc, where `import java.util.Deque;` used to be. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
Review Went through the diff (not just the PR description) end to end: the ten handler files, DatabaseAbstractHandler, AbstractBinaryHttpHandler, the OpenAPI spec changes, and the new IT. Solid change; a few notes below, nothing blocking. Verified correct (things that looked suspicious at first glance but check out)
Minor observations (non-blocking)
Test coverage The new Issue7681GrafanaPrometheusHttpSessionIT is thorough: it covers all ten routes' session echo, the write-refuses/read-degrades asymmetry, cross-principal session rejection with a control case, session-detach-doesn't-disturb-caller's-own-transaction, and the concurrency plus reflection pair for the binary handler. The structural allTenGrafanaAndPrometheusRoutesAreOnTheSessionAwareBaseHandler test is a nice guard against a future handler being added back onto the old base class. Overall: well-scoped, well-tested, and the security and behavioral claims in the description hold up against the actual code. |
…the two gates beside it do claude-review on PR #7723 noted that carriesSessionId treats a header present-but-blank as naming a session, dispatching to a worker for a value that can never resolve - correctly flagging it as pre-existing rather than a regression. It stays, and the javadoc now says why instead of leaving the next reader to ask. setTransactionInThreadLocal and removeSession make the SAME test on the same header, and this one decides which thread the request is answered on while that one decides what the id resolves to. Tightening either alone makes the two disagree: a request answered on the IO thread that then blocks on the session lock anyway, or a dispatch for a request that was never going to touch a session. The other two observations need no change and are recorded in the PR body: the new IT class runs in 4.5 s, so @tag("slow") is not warranted, and the residual-risk items were already argued in the description. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
ReviewReviewed the diff against the CLAUDE.md guidance (reuse, imports, style, tests) and traced the security/behavioral claims in the PR description against the actual code. Summary: solid fix, well-scoped, and unusually well self-documented. I verified the specific claims below rather than taking the PR body at face value. Verified correct
Minor observations (non-blocking)
Test coverageThe new Style/convention compliance
Nothing here blocks merge from my read — the residual-risk items are already argued in the PR body, and the adversarial-pass gaps are filed as separate issues rather than swept under the rug. |
Three time-series PRs landed on main while this one was in review, and two of them meet it. #7681 (PR #7723) moved the session paragraphs out of TimeSeriesApiSpec into SpecBuilders, because it needed the same text on ten more Grafana and Prometheus operations, and bound those ten to the HTTP session transaction. That is a conflict on the constants block and, more to the point, ten more operations that now reach DatabaseAbstractHandler's DEGRADING branch - so ten more that can send the arcadedb-session-expired header this branch added for #7714 and had documented nowhere. Resolved main's way: the header's paragraph moves into SpecBuilders next to the other four, and GrafanaApiSpec and PrometheusApiSpec declare it on every read. Prometheus remote-write does NOT - it answers true to rejectsUnresolvableSession(), so it refuses a stale id rather than running outside the transaction, and a spec that promised the header there would describe one the caller can never see. #7675 (PR #7719) rewrote the bucketInterval and requests descriptions on the same schema. Both halves are true of the same member, so the merged text carries both: the width must be positive AND whole, and an empty requests array is refused. CoreApiSpecTest.commitAndRollbackDoNotAdvertiseTheSessionIdResponseHeader asserted those two operations declare NO response headers, as a way of saying they do not declare the session-id one. They now declare the expired one, and correctly: both handlers remove ARCADEDB_SESSION_ID before responding and only that, while arcadedb-session-expired is set on the way in and nothing takes it off - which is exactly what a retried commit naming an already-removed session gets. The assertion is narrowed to the header it is actually about, and now pins the other one too. everyDegradingOperationDeclaresTheSessionExpiredHeader grows from six operations to fifteen, and its negative half from two to four.
Closes #7681
DatabaseAbstractHandleris the only handler base class that readsarcadedb-session-id. Issue #7402 moved the three documented/api/v1/tsroutes onto it; the other ten registered under the same prefix did not move, and each still carried the hand-rolledcheckAuthorizationOnDatabasecall whose own javadoc said it existed "Because these handlers do not extendDatabaseAbstractHandler". A client that opened a session withPOST /api/v1/begin/{db}and presented its id onPOST /ts/{db}/grafana/queryorPOST /ts/{db}/prom/writewas answered from outside it: no session transaction, no session lock, no principal, and no refresh of the idle timer that decides when its transaction is rolled back underneath it. All ten now extend it,POST /prom/writerefuses a session id it cannot resolve rather than ingesting outside it, and the nine reads degrade the wayGET /queryand the two/api/v1/tsreads already do.Test plan
mvn -o -pl server -am verify -Pintegration -Dit.test=Issue7681GrafanaPrometheusHttpSessionIT— 17 tests, the new regression suitemvn -o -pl server -am verify -Pintegration -Dit.test='GrafanaTimeSeriesHandlerIT,PromQLHttpHandlerIT,PrometheusRemoteWriteReadIT,Issue7402TimeSeriesHttpSessionIT,UngatedHandlerCrossDatabaseIT,TimeSeriesPerTypeAclIT,OpenApiSpecGenerationIT,Issue7043AbsentMinMaxOverHttpIT,Issue7584AbsentSumAvgOverHttpIT,Issue7305GrafanaFieldProjectionIT,Issue7371PromQLDiscoveryProjectionIT,Issue6839PrometheusWriteEngineUnavailableIT,Issue6807PromQLParameterValidationIT,TimeSeriesIngestBatchAppendIT'— every IT that touches these routesmvn -o -pl server test— the module's 1253 unit tests, including all 17 OpenAPI spec testsPOST /api/v1/begin/{db}, then any of the ten routes with the returnedarcadedb-session-id. The response must echo the header back; before this change it never did.Results. The new IT is 17/17 green. Reverting only
server/src/main/javaand re-running it turns 13 of 16 red (the count before the 17th test was added), one per route plus both refusal tests plus the structural one. The three that stayed green are the two boundary pins (an unresolvable id on a read still answers; a read leaves the session's uncommitted work alone), which pass before and after by construction, and the concurrency test - see Adversarial pass below, where that is treated as a finding rather than glossed. The affected ITs and the 1253 server unit tests are green.Two engine unit tests are red on this branch and on
mainalike -MultiColumnAggregationResultTest.emptySumIsAbsentNotZeroandflatModeEmptySumIsAbsentNotZero. They are the known#7584-vs-#7506contradiction tracked in #7694, in a module this branch does not touch (git diff --stat main...HEAD -- engine/is empty).Coverage
The invariant: every route registered under
/api/v1/ts/{database}resolvesarcadedb-session-id- running on the named session's transaction, under its lock, on its principal, refreshing its idle timer - and a route that WRITES refuses a header it cannot resolve rather than performing the write outside the session.The population, found by command rather than recalled:
Thirteen routes, three already done by #7402, ten here - which is the issue's own count, confirmed independently.
POST /ts/{db}/writeIssue7402TimeSeriesHttpSessionITPOST /ts/{db}/queryIssue7402TimeSeriesHttpSessionITGET /ts/{db}/latestIssue7402TimeSeriesHttpSessionITGET /ts/{db}/grafana/healththeGrafanaHealthRouteRunsInsideTheSessionItIsHandedGET /ts/{db}/grafana/metadatatheGrafanaMetadataRouteRunsInsideTheSessionItIsHandedPOST /ts/{db}/grafana/querytheGrafanaQueryRouteRunsInsideTheSessionItIsHandedPOST /ts/{db}/prom/writethePrometheusWriteRouteRunsInsideTheSessionItIsHanded+ both refusal testsPOST /ts/{db}/prom/readthePrometheusReadRouteRunsInsideTheSessionItIsHandedGET /ts/{db}/prom/api/v1/querythePromQLInstantQueryRouteRunsInsideTheSessionItIsHandedGET /ts/{db}/prom/api/v1/query_rangethePromQLRangeQueryRouteRunsInsideTheSessionItIsHandedGET /ts/{db}/prom/api/v1/labelsthePromQLLabelsRouteRunsInsideTheSessionItIsHandedGET /ts/{db}/prom/api/v1/label/{name}/valuesthePromQLLabelValuesRouteRunsInsideTheSessionItIsHandedGET /ts/{db}/prom/api/v1/seriesthePromQLSeriesRouteRunsInsideTheSessionItIsHandedThe same shape elsewhere
The defect's shape is a database-scoped handler that hand-rolls its authorization because it is not on
DatabaseAbstractHandler. Grepping for that call rather than for the location:returns, after this change, exactly two handlers outside
/api/v1/ts:POST /api/v1/batch(PostBatchHandler)GET /api/v1/progress(GetProgressHandler)grep -n 'getDatabase|Database\b|begin()|transaction' GetProgressHandler.javareturns only the authz gate on line 62 and its own class javadoc on line 36 ("no database access, no transaction"). It reads the lock-freeOperationProgressRegistrysnapshot.Known gaps
GET /prom/api/v1/label/{name}/valuesandGET /prom/api/v1/seriesanswer aforEachRow(Long.MIN_VALUE, Long.MAX_VALUE, ...)scan of every sample on an Undertow IO thread when no session header is present. Pre-existing, not introduced here: the newmustExecuteOnWorkerThread(exchange)override dispatches only the session-carrying case, deliberately leaving the session-less one exactly as it was. It is the case Grafana and Prometheus actually exercise, since neither ever sends the header.GET /api/v1/querycan park an IO thread on the session lock. Untouched here, and no new instance of it was introduced: all eight IO-thread reads on this prefix dispatch to a worker when the header is present.PostTimeSeriesWriteHandler, which HTTP /api/v1/ts read routes ignore arcadedb-session-id and read outside the session transaction #7402 fixed onmain. The byte body inAbstractBinaryHttpHandleris the same shape and is fixed here, because moving these handlers ontoDatabaseAbstractHandlerputs the session resolution betweenparseRequestPayloadandexecuteand so widens that window rather than narrowing it. This PR does not close PostTimeSeriesWriteHandler keeps the request body in an instance field, so concurrent ingests overwrite each other #7683 - it does not name this class.thePrometheusWriteRouteRunsInsideTheSessionItIsHanded.Residual risk
One deliberate behaviour change, reachable.
DatabaseAbstractHandlerresolves the database before callingexecute, so on these ten routes a request naming a nonexistent database now answers 404 where some previously answered something more specific first. It is most visible onPOST /prom/write, whose removed comment recorded that an earlier review had reverted exactly this ordering so an empty body or a zero-series request would keep its 400/204. That specificity is gone, and it is the price of the base class. It is taken knowingly: #7402 already made the same trade forPOST /ts/{db}/write, so all thirteen routes under the prefix now agree, and a 404 for a database that does not exist is not a wrong answer.greping the server tests found nothing pinning the old ordering, and the fourteen ITs listed in the test plan are green.One unreachable change, argued. The five PromQL handlers used to answer a missing
databaseparameter with the Prometheus error envelope ({"status":"error","errorType":"bad_data"}); the base class answers{"error":"Database parameter is null"}. Unreachable: every route is registered under the path template/ts/{database}/...(HttpServer.java:282-291), so Undertow binds the parameter whenever the route matches at all. No test covers it, because nothing can reach it.Nothing else. The completeness table above has no blank row.
Adversarial pass
The skill spawns an isolated subagent for this. No agent-spawning tool was available in this session, so the pass was run by the same agent that wrote the patch and is worth less than it should be - it had already been persuaded. Recorded here rather than silently skipped. Findings:
GetPromQLLabelValuesHandler.java:136isengine.forEachRow(Long.MIN_VALUE, Long.MAX_VALUE, ...).X-Request-Idthe six writers did not interleave betweenparseRequestPayloadandexecutein this harness. Rather than leave an unproven claim in a javadoc,theBinaryBaseHandlerKeepsNoRequestStateInAnInstanceField()was added - it asserts the invariant by reflection, was confirmed to fail withprotected byte[] rawBytesrestored, and the concurrency test's javadoc now says plainly what it does and does not show.thePrometheusWriteRouteRunsInsideTheSessionItIsHandedso a future change making either transactional fails here.databaseparameter is lostOne defect the tests caught during implementation
Worth naming because it is not visible in the final diff as a bug. With the ten routes moved and nothing else changed,
thePrometheusWriteRouteRunsInsideTheSessionItIsHandedfailed:PostPrometheusWriteHandleropens its ownbegin()/commit(). Inside a session that is a nested transaction on top of the caller's, andDatabaseContext.maxNestedis 3 - a level the auto-create path needs, because opening a new type's shards and tag dictionary takes transactions of its own. The fix is theownTransactiongate: open one only when this request does not already have one, and gatecommit()/rollback()on the same flag, since either applied to a transaction this handler did not open would settle the caller's session transaction behind its back. The session-less path is byte-for-byte unchanged.🤖 Generated with Claude Code
Review cycles
Three cycles against
claude-review, ending in a clean approval. CodeRabbit hit its OSS rate limit on the first push ("Next included review available in 31 minutes") and posted no review, no inline thread and no "outside diff range" finding on any of the three commits; its check is green.4ced36cAbstractBinaryHttpHandlermoved and its byte body taken off the shared field,PostPrometheusWriteHandler'sownTransactiongate, three OpenAPI contributors, the new 17-test IT.import java.util.Deque;was removed. Verified and fixed.4cded93d943d84carriesSessionId's javadoc why it reads the header exactly as the two gates beside it do.What cycle 2's observations got
carriesSessionIdtreats a present-but-blank header as naming a session, dispatching to a worker for a value that can never resolve. Flagged as pre-existing, not a regression.setTransactionInThreadLocalandremoveSessionmake the identical test on the same header -DatabaseAbstractHandler.java:319,:394,:404, all threesessionId != null && !sessionId.isEmpty(), whereisEmpty()asks whether the header carries any value rather than whether the value is blank. This method decides which THREAD the request is answered on; that one decides what the id RESOLVES to. Tightening either alone makes the two disagree, so the fix for this is one change to all three, not to this one.@Tag("slow").Time elapsed: 4.496 sinserver/target/failsafe-reports. CLAUDE.md reserves the tag for tests that take "noticeably long"; 4.5 s for seventeen tests including a live server is not that.Final state
clean-approval. No deferred items, no unaddressed feedback, no open review thread.A note on the adversarial pass
Stated again here because it is the weakest part of this PR's process. The skill spawns an isolated subagent for Phase 1.5 precisely so the pass is run by someone who has not already been convinced by the author's reasoning. No agent-spawning tool was available in this session, so it was run by the same agent that wrote the patch. It did find three real things - #7722, the unproven concurrency claim, and the post-rollback question it had to answer by experiment - but it should be read as a self-review, not as an independent one.