Skip to content

fix(#7681): bind the HTTP session transaction on the ten Grafana and Prometheus /api/v1/ts routes - #7723

Merged
robfrank merged 3 commits into
mainfrom
fix/7681-grafana-prometheus-ts-session-id
Sep 16, 2026
Merged

robfrank merged 3 commits into
mainfrom
fix/7681-grafana-prometheus-ts-session-id

Conversation

@robfrank

@robfrank robfrank commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #7681

DatabaseAbstractHandler is the only handler base class that reads arcadedb-session-id. Issue #7402 moved the three documented /api/v1/ts routes onto it; the other ten registered under the same prefix did not move, and each still carried the hand-rolled checkAuthorizationOnDatabase call whose own javadoc said it existed "Because these handlers do not extend DatabaseAbstractHandler". A client that opened a session with POST /api/v1/begin/{db} and presented its id on POST /ts/{db}/grafana/query or POST /ts/{db}/prom/write was 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/write refuses a session id it cannot resolve rather than ingesting outside it, and the nine reads degrade the way GET /query and the two /api/v1/ts reads already do.

Test plan

  • mvn -o -pl server -am verify -Pintegration -Dit.test=Issue7681GrafanaPrometheusHttpSessionIT — 17 tests, the new regression suite
  • mvn -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 routes
  • mvn -o -pl server test — the module's 1253 unit tests, including all 17 OpenAPI spec tests
  • By hand: POST /api/v1/begin/{db}, then any of the ten routes with the returned arcadedb-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/java and 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 main alike - MultiColumnAggregationResultTest.emptySumIsAbsentNotZero and flatModeEmptySumIsAbsentNotZero. They are the known #7584-vs-#7506 contradiction 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} resolves arcadedb-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:

$ grep -n '\.\(get\|post\)("/ts/' server/src/main/java/com/arcadedb/server/http/HttpServer.java \
    | sed 's/.*new \([A-Za-z]*\)(this).*/\1/' | while read h; do
      printf '%-32s %s\n' "$h" "$(grep -h "public class $h extends" \
        server/src/main/java/com/arcadedb/server/http/handler/$h.java | sed 's/.*extends //;s/ {//')"; done
PostTimeSeriesWriteHandler       DatabaseAbstractHandler
PostTimeSeriesQueryHandler       DatabaseAbstractHandler
GetTimeSeriesLatestHandler       DatabaseAbstractHandler
GetGrafanaHealthHandler          AbstractServerHttpHandler
GetGrafanaMetadataHandler        AbstractServerHttpHandler
PostGrafanaQueryHandler          AbstractServerHttpHandler
PostPrometheusWriteHandler       AbstractBinaryHttpHandler
PostPrometheusReadHandler        AbstractBinaryHttpHandler
GetPromQLQueryHandler            AbstractServerHttpHandler
GetPromQLQueryRangeHandler       AbstractServerHttpHandler
GetPromQLLabelsHandler           AbstractServerHttpHandler
GetPromQLLabelValuesHandler      AbstractServerHttpHandler
GetPromQLSeriesHandler           AbstractServerHttpHandler

Thirteen routes, three already done by #7402, ten here - which is the issue's own count, confirmed independently.

Entry point Covered by fix? Covered by a test?
POST /ts/{db}/write #7402 Issue7402TimeSeriesHttpSessionIT
POST /ts/{db}/query #7402 Issue7402TimeSeriesHttpSessionIT
GET /ts/{db}/latest #7402 Issue7402TimeSeriesHttpSessionIT
GET /ts/{db}/grafana/health yes theGrafanaHealthRouteRunsInsideTheSessionItIsHanded
GET /ts/{db}/grafana/metadata yes theGrafanaMetadataRouteRunsInsideTheSessionItIsHanded
POST /ts/{db}/grafana/query yes theGrafanaQueryRouteRunsInsideTheSessionItIsHanded
POST /ts/{db}/prom/write yes thePrometheusWriteRouteRunsInsideTheSessionItIsHanded + both refusal tests
POST /ts/{db}/prom/read yes thePrometheusReadRouteRunsInsideTheSessionItIsHanded
GET /ts/{db}/prom/api/v1/query yes thePromQLInstantQueryRouteRunsInsideTheSessionItIsHanded
GET /ts/{db}/prom/api/v1/query_range yes thePromQLRangeQueryRouteRunsInsideTheSessionItIsHanded
GET /ts/{db}/prom/api/v1/labels yes thePromQLLabelsRouteRunsInsideTheSessionItIsHanded
GET /ts/{db}/prom/api/v1/label/{name}/values yes thePromQLLabelValuesRouteRunsInsideTheSessionItIsHanded
GET /ts/{db}/prom/api/v1/series yes thePromQLSeriesRouteRunsInsideTheSessionItIsHanded

The 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:

$ grep -rn 'checkAuthorizationOnDatabase' --include="*.java" server/src/main/java | grep -v 'AbstractServerHttpHandler.java'

returns, after this change, exactly two handlers outside /api/v1/ts:

Entry point Disposition
POST /api/v1/batch (PostBatchHandler) Filed - already open as #7682, which reports exactly this for the batch loader. Out of scope here: it is a streaming bulk-load path with leader forwarding, a different edit.
GET /api/v1/progress (GetProgressHandler) Argued - it reaches no database at all, so there is nothing for a session to bind. grep -n 'getDatabase|Database\b|begin()|transaction' GetProgressHandler.java returns only the authz gate on line 62 and its own class javadoc on line 36 ("no database access, no transaction"). It reads the lock-free OperationProgressRegistry snapshot.

Known gaps

Residual risk

One deliberate behaviour change, reachable. DatabaseAbstractHandler resolves the database before calling execute, 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 on POST /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 for POST /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 database parameter 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:

Finding Disposition
The PromQL discovery endpoints scan every sample on an IO thread Real, out of scope → filed as #7722. Verified: GetPromQLLabelValuesHandler.java:136 is engine.forEachRow(Long.MIN_VALUE, Long.MAX_VALUE, ...).
404 now precedes body validation on a nonexistent database Real, in scope → argued above, under Residual risk.
The concurrency test claimed to prove the old shared-field bug and did not Real → fixed. The test passed against the instance field: with no session header and no X-Request-Id the six writers did not interleave between parseRequestPayload and execute in this harness. Rather than leave an unproven claim in a javadoc, theBinaryBaseHandlerKeepsNoRequestStateInAnInstanceField() was added - it asserts the invariant by reflection, was confirmed to fail with protected byte[] rawBytes restored, and the concurrency test's javadoc now says plainly what it does and does not show.
What happens to a type a remote write auto-creates inside a session, after that session rolls back? Answered by experiment, then pinned. Neither the type nor the sample is undone. Asserted at the end of thePrometheusWriteRouteRunsInsideTheSessionItIsHanded so a future change making either transactional fails here.
The PromQL-shaped 400 for a missing database parameter is lost Not real - unreachable behind the route template. Evidence under Residual risk.

One 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, thePrometheusWriteRouteRunsInsideTheSessionItIsHanded failed:

{"exception":"com.arcadedb.exception.SchemaException",
 "detail":"Failed to initialize TimeSeries engine for type 'Ts7681Prom' -> Failed to initialize shards
           -> Exceeded number of 3 nested transactions."}

PostPrometheusWriteHandler opens its own begin()/commit(). Inside a session that is a nested transaction on top of the caller's, and DatabaseContext.maxNested is 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 the ownTransaction gate: open one only when this request does not already have one, and gate commit()/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.

# Head SHA What changed Review outcome
1 4ced36c The fix itself: ten handlers reparented, AbstractBinaryHttpHandler moved and its byte body taken off the shared field, PostPrometheusWriteHandler's ownTransaction gate, three OpenAPI contributors, the new 17-test IT. "Solid, well-scoped fix." One actionable nit: a leftover double blank line in two files where import java.util.Deque; was removed. Verified and fixed.
2 4cded93 Squashed those two blank lines. "Nothing blocking." Three non-blocking observations - see the table below.
3 d943d84 Recorded in carriesSessionId's javadoc why it reads the header exactly as the two gates beside it do. "Nothing here blocks merge from my read." No actionable items; working tree clean.

What cycle 2's observations got

Observation Disposition
carriesSessionId treats 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. Kept, and the reason written down (cycle 3). setTransactionInThreadLocal and removeSession make the identical test on the same header - DatabaseAbstractHandler.java:319, :394, :404, all three sessionId != null && !sessionId.isEmpty(), where isEmpty() 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.
The 6-thread concurrency test might want @Tag("slow"). Not applied, measured rather than argued. The whole IT class is Time elapsed: 4.496 s in server/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.
The residual-risk items and #7722 are correctly scoped. Agreement, no change.

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.

…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>
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 15 minutes.

Check out review usage here.

View limit details

Limit 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.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 2ea342f6-b56d-44b3-9ea6-a1321df41563

📥 Commits

Reviewing files that changed from the base of the PR and between 495bdca and d943d84.

📒 Files selected for processing (18)
  • server/src/main/java/com/arcadedb/server/http/handler/AbstractBinaryHttpHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/DatabaseAbstractHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetGrafanaHealthHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetGrafanaMetadataHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetPromQLLabelValuesHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetPromQLLabelsHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetPromQLQueryHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetPromQLQueryRangeHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetPromQLSeriesHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/GetTimeSeriesLatestHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/PostGrafanaQueryHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/PostPrometheusReadHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/PostPrometheusWriteHandler.java
  • server/src/main/java/com/arcadedb/server/http/handler/openapi/GrafanaApiSpec.java
  • server/src/main/java/com/arcadedb/server/http/handler/openapi/PrometheusApiSpec.java
  • server/src/main/java/com/arcadedb/server/http/handler/openapi/SpecBuilders.java
  • server/src/main/java/com/arcadedb/server/http/handler/openapi/TimeSeriesApiSpec.java
  • server/src/test/java/com/arcadedb/server/Issue7681GrafanaPrometheusHttpSessionIT.java

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

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.

@claude

claude Bot commented Sep 16, 2026

Copy link
Copy Markdown

Review

Solid, well-scoped fix. I read through the full diff (all 17 changed files) plus DatabaseAbstractHandler/AbstractServerHttpHandler to verify the authorization and transaction plumbing, and traced through the new IT. Summary below.

Correctness

  • Core fix is right. DatabaseAbstractHandler.execute() performs user.canAccessToDatabase(...) before resolving the database (line ~70-74) and binds the current principal into DatabaseContext (line ~89-91), so moving these ten handlers off the hand-rolled checkAuthorizationOnDatabase doesn't weaken either the database-level gate (GHSA-x8mg-6r4p-87pf) or the per-type ACL binding (GHSA-c23x-pqcj-7hfm) - it's the same mechanism the three #7402 handlers already rely on.
  • ownTransaction gate in PostPrometheusWriteHandler is correct. Traced the two paths: session-less (activeSession == null -> atomicTransaction falls back to requiresTransaction() which is false -> no wrapper transaction -> database.isTransactionActive() is false at entry -> ownTransaction = true, byte-for-byte the old behavior) vs. in-session (activeSession != null -> no wrapper either, but the session's transaction is already bound -> ownTransaction = false, avoiding the nested-transaction-depth exhaustion described in the PR). Good catch, and it's exercised by the new IT.
  • AbstractBinaryHttpHandler field-to-attachment fix is a genuine, separate bug fix (shared-instance-field race on a singleton handler across concurrent Prometheus remote-write requests) bundled sensibly into this change since reparenting onto DatabaseAbstractHandler widens the same window. theBinaryBaseHandlerKeepsNoRequestStateInAnInstanceField() pinning "no instance fields" via reflection rather than "no field named rawBytes" is a nice touch - it survives a future rename.
  • The bookmark emission removed from PostPrometheusWriteHandler (resolveHAReplicatedDatabase/emitCommitIndexBookmark/the HAReplicatedDatabase import) isn't a regression - DatabaseAbstractHandler.execute() already does this generically for every handler on the base class (lines ~119, ~127, ~183), so the manual call was redundant once reparented.

Test coverage

The new Issue7681GrafanaPrometheusHttpSessionIT is thorough: all ten routes' session echo, the write-vs-read refusal asymmetry, cross-principal session rejection, session-work isolation (reads don't disturb the caller's uncommitted work), and the concurrency + reflection pair for the binary-handler fix. Good discipline pinning the post-rollback survival of an auto-created type/sample (issue #7410 boundary) rather than assuming it.

Nits

  • GetPromQLQueryHandler.java and GetPromQLQueryRangeHandler.java both have a leftover double blank line where import java.util.Deque; was removed (line 31-32 in each). Trivial, but easy to squash.

Worth double-checking, not blocking

  • The residual-risk item the PR description already calls out (a nonexistent database on these ten routes now answers plain 404 before any body/parameter validation, where a couple of routes used to answer a more specific 400/204) is a real, deliberate behavior change. It's consistent with what #7402 already did for /api/v1/ts/write, and I couldn't find a test pinning the old ordering, but it's worth flagging to anyone with an existing integration that depends on the old response shape for a missing database.
  • The filed follow-up (#7722, IO-thread scan on the two PromQL discovery endpoints when no session header is present) is correctly left out of scope here - the mustExecuteOnWorkerThread(exchange) override only dispatches the session-carrying case, which is what this issue is actually about.

Nothing else jumped out - the transaction/session semantics match the established #7402 pattern consistently across all ten handlers, and the security-relevant paths (authz check ordering, principal binding, per-type ACL preflight before schema mutation) are preserved.

…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>
@claude

claude Bot commented Sep 16, 2026

Copy link
Copy Markdown

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)

  • Bookmark emission removal in PostPrometheusWriteHandler: the diff deletes the handler's own resolveHAReplicatedDatabase/emitCommitIndexBookmark calls. That looked like a dropped feature at first, but DatabaseAbstractHandler.execute already resolves haDbForRead unconditionally and calls both emitCommitIndexBookmarkOnResponseCommit (before the try, fires on success and failure via the response-commit listener) and the eager emitCommitIndexBookmark after execute() returns. So the write path keeps the same read-your-writes bookmark behavior, including on error, and the duplication is correctly removed rather than the feature being lost.
  • Security parity: checkAuthorizationOnDatabase did two things: canAccessToDatabase and binding the principal onto DatabaseContext for per-type ACL enforcement (GHSA-c23x-pqcj-7hfm). DatabaseAbstractHandler.execute does both (around lines 70 and 89-91), so moving these ten handlers over doesn't weaken either GHSA fix; it is arguably cleaner since it avoids the BOUND_PRINCIPAL_DB ThreadLocal cleanup dance AbstractServerHttpHandler needs for the hand-rolled version.
  • ownTransaction gate in PostPrometheusWriteHandler: correctly scoped, commit()/rollback() are only called when this handler opened the transaction itself, so a write running inside a caller's session can no longer accidentally settle that session's transaction, and the nested-transaction-depth exhaustion the PR describes (auto-create needing headroom under maxNested) is a real bug this genuinely fixes.
  • AbstractBinaryHttpHandler's field-to-exchange-attachment change: legitimate fix for a real concurrency bug (shared mutable field on a singleton handler). The new theBinaryBaseHandlerKeepsNoRequestStateInAnInstanceField reflection test is a good regression guard, and its javadoc is honest that the concurrency test alone wouldn't have caught the original bug in this harness.
  • Import cleanup from the second commit is complete, no leftover unused imports or double-blank-lines in the five files that lost Deque.

Minor observations (non-blocking)

  1. carriesSessionId's presence-only check in DatabaseAbstractHandler.java (sessionId != null && !sessionId.isEmpty()) treats a header present-but-empty-string as carrying a session, dispatching to a worker thread for a value that can never resolve. Pre-existing behavior lifted from GetTimeSeriesLatestHandler, not introduced here, so not a regression, just noting it wasn't tightened while it was being centralized.
  2. concurrentRemoteWritesDoNotIngestEachOthersBodies spins up a 6-thread pool with a 60s invokeAll timeout. It is an IT (Failsafe lane), not a unit test, so the slow-tag convention in CLAUDE.md may not strictly apply, but if it runs noticeably long in CI it would be a candidate for that tag or for the slow/benchmark lane guidance to be extended to ITs.
  3. The residual-risk items called out in the PR description (404-before-body-validation ordering change, unreachable PromQL database-parameter 400) are real but correctly scoped as accepted/unreachable, and Two PromQL discovery endpoints answer a full-range sample scan on an Undertow IO thread #7722 (IO-thread scan on the two PromQL discovery reads) is fairly filed as pre-existing and out of scope.

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>
@claude

claude Bot commented Sep 16, 2026

Copy link
Copy Markdown

Review

Reviewed 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

  • Auth parity preserved. The removed hand-rolled checkAuthorizationOnDatabase(user, databaseName) calls are subsumed by DatabaseAbstractHandler.execute's own user.canAccessToDatabase(...) gate (DatabaseAbstractHandler.java:70), so there's no authorization regression from dropping those calls.
  • The AttachmentKey fix for the shared-instance-field bug is real and correctly scoped. AbstractBinaryHttpHandler previously stored rawBytes as an instance field on a singleton handler — a genuine concurrent-request data race (confirmed by the new reflection test theBinaryBaseHandlerKeepsNoRequestStateInAnInstanceField). Moving it to an HttpServerExchange attachment is the right fix, and gating it on requiresJsonPayload()/blocking dispatch looks consistent with the rest of the base class.
  • emitCommitIndexBookmark/resolveHAReplicatedDatabase removal from PostPrometheusWriteHandler is not a functional loss — DatabaseAbstractHandler.execute already does this generically for every request that goes through it (DatabaseAbstractHandler.java:119,127,178), so the explicit per-handler calls were redundant once the class was reparented.
  • The ownTransaction gate in PostPrometheusWriteHandler correctly avoids stacking a nested transaction on top of an active session transaction, respecting DatabaseContext.maxNested. The commit/rollback calls are properly gated on the same flag so a handler that didn't open the transaction can't inadvertently settle the caller's session transaction.
  • carriesSessionId / setTransactionInThreadLocal / removeSession intentionally use the same "header present" test (not a blank-check) — reasoned about and left as pre-existing behavior rather than silently tightened, which is the right call given the two call sites need to agree.

Minor observations (non-blocking)

  • Residual risk is real but small and consciously accepted: a request to a nonexistent database on these 10 routes now gets 404 before the old 400/{"error":...} body validation runs, since DatabaseAbstractHandler resolves database before calling execute. The PR description argues this convincingly (matches HTTP /api/v1/ts read routes ignore arcadedb-session-id and read outside the session transaction #7402's precedent, no test pins the old ordering), so I agree this is acceptable as documented.
  • Known gap Two PromQL discovery endpoints answer a full-range sample scan on an Undertow IO thread #7722 (PromQL discovery endpoints scanning on an IO thread when no session header is present) is pre-existing and out of scope here — correctly filed separately rather than silently expanded into this PR's diff.
  • The GetGrafanaHealthHandler/GetGrafanaMetadataHandler echo of exchange.getQueryParameters().get("database").getFirst() rather than db.getName() is a deliberate, reasonable choice (avoids the echo diverging if the server ever resolves aliases) — just flagging it as an intentional behavior choice for reviewers scanning the diff quickly.

Test coverage

The new Issue7681GrafanaPrometheusHttpSessionIT (719 lines, 17 tests) is exceptionally thorough: it covers all ten routes' session-echo behavior, the write-vs-read refusal asymmetry, cross-principal session rejection, session teardown leaving the caller's own uncommitted work intact, and a concurrency test for the instance-field race with a companion reflection test that actually fails against the pre-fix code (the concurrency test alone was shown not to, and the PR is transparent about that limitation rather than hiding it). This is a good model for regression tests on this codebase.

Style/convention compliance

  • Follows the codebase's final and import conventions.
  • No new dependencies introduced.
  • No System.out debug statements found.
  • OpenAPI spec doc changes are refactored into SpecBuilders shared constants rather than duplicated three times, matching the "reuse existing components" guidance.

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.

@robfrank
robfrank merged commit 7463881 into main Sep 16, 2026
29 of 32 checks passed
@robfrank
robfrank deleted the fix/7681-grafana-prometheus-ts-session-id branch September 16, 2026 16:03
lvca added a commit that referenced this pull request Sep 16, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant