Skip to content

Reject open_blob with an unknown transaction handle - #40513

Merged
terrymanu merged 7 commits into
apache:masterfrom
rishi-rana:fix-firebird-open-blob-unknown-transaction-handle
Dec 4, 2026
Merged

terrymanu merged 7 commits into
apache:masterfrom
rishi-rana:fix-firebird-open-blob-unknown-transaction-handle

Conversation

@rishi-rana

Copy link
Copy Markdown
Contributor

Issue

Fixes #40510

FirebirdOpenBlobCommandExecutor opened a BLOB and returned success for op_open_blob/op_open_blob2 regardless of the transaction handle in the packet, including a handle that was never started. The real Firebird server rejects this with isc_bad_trans_handle.

Fix

Validate the transaction handle via FirebirdTransactionIdGenerator#isTransactionActive, throwing the existing InvalidTransactionHandleException on an unknown handle. This mirrors the identical check added for the sibling create_blob command (#40393) and already present in FirebirdExecuteStatementCommandExecutor, FirebirdBatchExecuteCommandExecutor, FirebirdCommitTransactionCommandExecutor, and FirebirdRollbackTransactionCommandExecutor — no new abstractions, exception types, or mapper registrations needed.

Verification

  • Reverted the fix locally and confirmed the new regression test (assertExecuteWithUnknownTransactionHandle) fails against the pre-fix code for the right reason, then restored it.
  • All tests in FirebirdOpenBlobCommandExecutorTest and FirebirdCreateBlobCommandExecutorTest pass with the fix.
  • spotless:apply/checkstyle:check -Pcheck clean on both changed files; no line exceeds 200 characters.

AI assistance disclosure

Assisted with AI Claude (Claude Code) for investigating the root cause, implementing the fix, and writing the regression test. Affected files: FirebirdOpenBlobCommandExecutor.java, FirebirdOpenBlobCommandExecutorTest.java.

🤖 Generated with Claude Code

FirebirdOpenBlobCommandExecutor opened a BLOB and returned success for
any transaction handle, including one that was never started, unlike
the Firebird server and every other transaction-scoped executor in
this module.

Validate the handle via FirebirdTransactionIdGenerator#isTransactionActive,
throwing InvalidTransactionHandleException on an unknown handle, mirroring
the identical check in FirebirdCreateBlobCommandExecutor (apache#40393),
FirebirdExecuteStatementCommandExecutor, FirebirdBatchExecuteCommandExecutor,
FirebirdCommitTransactionCommandExecutor, and
FirebirdRollbackTransactionCommandExecutor.

Fixes apache#40510

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

@terrymanu terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

This PR checks whether a transaction is active before opening a BLOB, rejecting unknown transaction handles. The approach is reasonable, but validating the raw handle also rejects valid deferred transaction handles permitted by the Firebird protocol.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 1

Blocking Issues

  1. [P2] Resolve valid deferred transaction handles before validation

    • Evidence: The new validation directly checks the raw transaction ID. Protocol §7.1.1 permits 0xFFFF in deferred-send mode; the native implementation first resolves it to the most recently created object handle.
    • Impact: After negotiating lazy-send and starting transaction 1, a client may immediately open a BLOB using 0xFFFF. The new validation only recognizes 1 in the active set, incorrectly returning isc_bad_trans_handle. A reproduction against the current commit confirms that the literal handle 1 succeeds while the valid placeholder 65535 is rejected.
    • Required Change: Resolve valid deferred handles before validation, add regression coverage, and retain rejection of genuinely unknown handles.

Coverage

Public PR head: a3afd0898769f8664a5d71aa0260fef8f9bf9c50. Both changed files were fully reviewed; independent assessments and final evidence validation are complete.
Local Spotless, Checkstyle, and all 12 focused tests passed. This conclusion covers code correctness only; CI was not reviewed.

…eject

Mirrors the fixes accepted on PR apache#40511 for the same shared files:
FirebirdTransactionIdGenerator#isTransactionActive now resolves Firebird's
INVALID_OBJECT sentinel (0xFFFF) to the connection's most recently started
transaction instead of rejecting it outright, matching terrymanu's review
finding on this PR. FirebirdFrontendEngine#handleException now also excludes
InvalidTransactionHandleException from poisoning the active transaction,
proactively porting apache#40511's P1 fix since this branch throws the same
exception type and has the identical latent regression.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@rishi-rana

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in c2e660c.

Resolve valid deferred transaction handles before validation

Confirmed and fixed. Checked the real mechanism in Firebird's own rem_port::getHandle (remote.h): under lazy-send, INVALID_OBJECT (0xFFFF) resolves to the connection's most recently allocated object of any type. This codebase tracks object IDs per type with no unified cross-type "last object" counter, so FirebirdTransactionIdGenerator#isTransactionActive now resolves that sentinel to the connection's most recently started transaction specifically. Documented that narrower scope in the field's Javadoc. Added assertIsTransactionActiveResolvesLazyResponseSentinelToMostRecentTransaction, verified it fails against the pre-fix code.

While addressing this, I also found the same regression this fix pattern previously caused on PR #40511 was latent here too: FirebirdOpenBlobCommandExecutor throws the same InvalidTransactionHandleException, which reaches FirebirdFrontendEngine#handleException and would poison an unrelated active transaction on an unknown-handle rejection. Proactively excluded it there as well, mirroring #40511's fix, with a corresponding test case.

Verification

All affected tests pass (FirebirdFrontendEngineTest, FirebirdTransactionIdGeneratorTest, FirebirdOpenBlobCommandExecutorTest, plus the sibling executors sharing isTransactionActive); spotless:check checkstyle:check -Pcheck clean; no line exceeds 200 characters in the diff.

@rishi-rana
rishi-rana requested a review from terrymanu November 18, 2026 02:15
rishi-rana and others added 2 commits November 17, 2026 18:39
…-blob-unknown-transaction-handle

# Conflicts:
#	proxy/frontend/dialect/firebird/src/main/java/org/apache/shardingsphere/proxy/frontend/firebird/FirebirdFrontendEngine.java
#	proxy/frontend/dialect/firebird/src/test/java/org/apache/shardingsphere/proxy/frontend/firebird/FirebirdFrontendEngineTest.java
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

@terrymanu terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

This PR validates transaction handles before opening BLOBs and prevents unknown-handle errors from marking the current transaction as failed. The validation boundary is appropriate, but deferred-handle handling still has three runtime defects and two explicit repository standards violations.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 5

Protocol compatibility, transaction cleanup, and standards issues require correction.

Blocking Issues

  1. [P2] Valid native XDR sentinel handles are still rejected

    • Evidence: The new validation recognizes only positive 65535. Native Firebird encodes transaction handles through signed xdr_short, transmitting the sentinel as 0xFFFFFFFF; the current packet decoder produces -1. An actual-packet reproduction against the exact head confirms that this throws InvalidTransactionHandleException. See the protocol mapping and XDR encoding.
    • Impact: Valid deferred-send BLOB open requests receive isc_bad_trans_handle. The previously reported issue is only partially fixed.
    • Required Change: Correctly interpret valid handle encodings and add regression coverage using actual wire packets.
  2. [P2] Deferred commit and rollback leave the transaction registered

    • Evidence: The new mapping affects validation only; commit and rollback still pass raw 65535 to closeTransaction. Reproductions confirm that both commands return success while the concrete transaction ID remains active.
    • Impact: Starting the next transaction throws ExcessTransactionsException. The added test closes the concrete ID and therefore misses this failure path.
    • Required Change: Use the resolved handle consistently throughout validation, execution, and cleanup. Cover starting another transaction after deferred commit and rollback.
  3. [P2] The sentinel incorrectly resolves to the latest transaction

    • Evidence: The current mapping always selects the most recently started transaction. The native implementation resolves the sentinel only in lazy mode and targets the connection’s most recently allocated object of any type. A reproduction of “start transaction → allocate statement → open BLOB using the sentinel” still returns success.
    • Impact: Requests that should fail because the referenced object is not a transaction are accepted. The shared validation also allows commit and rollback to act incorrectly on the current transaction.
    • Required Change: Preserve the protocol semantics for negotiated mode, the connection’s latest object, and object type. Documenting the implementation limitation in Javadoc does not replace that contract.
  4. [P2] Added private-declaration Javadocs contain prohibited implementation explanations

    • Evidence: FirebirdFrontendEngine.java:58–65 and FirebirdTransactionIdGenerator.java:35–41 add implementation details, design rationale, and scenario explanations. The Javadoc rules explicitly restrict such descriptions for ordinary declarations.
    • Impact: Both added comments violate the applicable written standard. These private declarations do not qualify for the comprehensive user-facing API/SPI contract exception.
    • Required Change: Use short, accurate responsibility or action descriptions while preserving necessary public contract documentation.
  5. [P2] The modified argument list violates the required wrapping form

    • Evidence: The complete Stream.of statement at FirebirdFrontendEngineTest.java:129–130 contains 232 characters but retains three list elements on its opening line. The line-wrapping rules require each top-level element of a wrapped outer list to occupy its own continuation line.
    • Impact: This violates an explicit manual verification rule. Passing Spotless and Checkstyle does not establish compliance with that rule.
    • Required Change: Keep the invocation opening on the first line and place each top-level Arguments.of on a separate continuation line.

Coverage

Public head: dc6fc4ae6794df0f5255269893ca48415f270dac. All 6 changed files and affected call paths were reviewed; both independent assessments and final evidence validation are complete.
Checkstyle and Spotless selected all six files and passed. All 61 related tests passed; additional reproductions confirmed the runtime defects above.
This conclusion covers code correctness only. CI was not reviewed, and the full E2E suite was not run.

…st object

The INVALID_OBJECT placeholder is only valid when lazy send was negotiated and
the connection's most recently allocated object is a transaction, and it can
arrive as 0xFFFF or as the sign-extended -1 that xdr_short produces. Commit and
rollback now use the resolved ID for validation, execution and cleanup so the
transaction no longer stays registered after a placeholder commit or rollback.

Assisted with AI Claude (Claude Code). Affected files: FirebirdLatestObjectRegistry,
FirebirdTransactionIdGenerator, FirebirdStatementIdGenerator, FirebirdBlobHandleGenerator,
FirebirdCommit/RollbackTransactionCommandExecutor, FirebirdAcceptPacket,
FirebirdAuthenticationEngine, FirebirdFrontendEngine and their tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@rishi-rana

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in cf53b52.

[P2] Valid native XDR sentinel handles are still rejected

Both 0xFFFF and the sign-extended -1 (FFFFFFFF) are now recognised. The OPEN_BLOB tests decode a real packet carrying FFFFFFFF.

[P2] Deferred commit and rollback leave the transaction registered

COMMIT and ROLLBACK now resolve the handle once and use it for validation, execution and closeTransaction. The new tests assert no transaction is active afterwards, so the next START succeeds.

[P2] The sentinel incorrectly resolves to the latest transaction

The placeholder is now accepted only when lazy send was negotiated at handshake (PORT_lazy) and the connection's most recently allocated object is a transaction. The transaction, statement and BLOB-handle generators record each allocation. Otherwise the request is rejected with InvalidTransactionHandleException. The start-transaction, allocate-statement, then open-BLOB sequence is now covered, along with lazy-off.

[P2] Javadocs and [P2] Stream.of wrapping

I removed the Javadoc on isRecoverableException and the constant's Javadoc, and rewrapped the argument list to one Arguments.of(...) per line.

🤖 Generated with Claude Code

@rishi-rana
rishi-rana requested a review from terrymanu November 28, 2026 22:39

@terrymanu terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

This PR validates transaction handles before opening BLOBs and resolves deferred handles according to the negotiated mode and most recently allocated object. Commit and rollback now clean up transactions using the resolved handle, fixing the previously reported runtime issues. The remaining blockers concern test isolation and explicit repository standards.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 5

The following issues violate explicit requirements in the current CODE_OF_CONDUCT.md.

Blocking Issues

  1. [P2] Restore the protocol-version cache after the new authentication test

    • Evidence: Authentication test lines 150–153 execute the real CONNECT flow, which writes to FirebirdConnectionProtocolVersion, but the finally block clears only the separate latest-object registry.
    • Impact: The protocol version for connection 1 remains in the global cache, violating the requirement to restore static state.
    • Required Change: Restore the cache’s previous state or mock the protocol-version cache owner.
  2. [P2] Apply the high-frequency code standards to the new methods

    • Evidence: The new resolveTransactionId and registry allocation and lookup methods run on repeated SQL, transaction and object-allocation paths without HighFrequencyInvocation. Their private helper also concatenates strings with +.
    • Impact: This violates the required annotation and helper-method restrictions. No performance regression has been established.
    • Required Change: Add annotations at the smallest accurate method scopes and make the relevant private helpers comply with the high-frequency code restrictions.
  3. [P2] Thirteen new parameterized tests provide only two argument sets

    • Evidence: The OPEN_BLOB tests, together with the COMMIT, ROLLBACK and transaction-ID generator tests, contain thirteen new parameterized methods providing only {0xFFFF, -1}.
    • Impact: This violates the requirement for at least three meaningful argument sets per parameterized test.
    • Required Change: Preserve coverage of both encodings using ordinary tests or reorganize them into compliant parameterized scenarios. Do not add duplicate arguments merely to reach the minimum.
  4. [P2] Use the required Boolean assertion form

    • Evidence: Authentication test line 151 compares Boolean values using assertThat(..., is(expectedLazy)).
    • Impact: This violates the requirement to use assertTrue or assertFalse for Boolean assertions.
    • Required Change: Use the prescribed Boolean assertion form while preserving both expected outcomes.
  5. [P2] Place the new private helper immediately after an actual caller

    • Evidence: setLatestObjectTransaction at line 102 immediately follows unregisterConnection, which does not call it. Its actual callers are at lines 69 and 78.
    • Impact: This violates the requirement to place private helpers immediately after their callers.
    • Required Change: Move the helper immediately after one of its actual callers. This finding does not require a shared helper to follow its first caller specifically.

Coverage

Public PR head: cf53b52bc0d9af2d5bf4174b6fb38168f3c20853. All 20 files and 65 changed blocks were reviewed; independent assessments and consolidated validation are complete.
Checkstyle and Spotless passed for all 20 files. After recompiling the current sources, all 137 focused JUnit tests passed.
The Maven test attempts were limited by project-scanning timeout and missing SNAPSHOT dependencies; alternative verification used cached dependencies. This conclusion covers code correctness only. CI and database integration tests were not reviewed or executed.

Mask the wire transaction handle to 16 bits before lookup so sign-extended
concrete handles resolve, mark the per-allocation registry paths as high
frequency, make the registry constructor private, order private helpers
after their callers, restore protocol-version state in the authentication
test, and replace two-case parameterized tests with ordinary tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@rishi-rana

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in 221a95d.

[P2] Restore the protocol-version cache after the authentication test

The test now unsets the FirebirdConnectionProtocolVersion entry for connection 1 after the CONNECT flow.

[P2] High-frequency standards

resolveTransactionId, markTransactionAllocated, markNonTransactionAllocated and isLazyTransactionLatest are annotated with @HighFrequencyInvocation. The private lookup helper builds its message with String.format instead of +.

[P2] Two-case parameterized tests

The thirteen tests are now ordinary tests. The accepted-sentinel tests use the sign-extended -1 that native Firebird sends. The rejection tests use 0xFFFF. The resolver tests cover both encodings.

[P2] Boolean assertion form

The authentication cases use assertTrue and assertFalse.

[P2] Private helper placement

setLatestObjectTransaction now follows markTransactionAllocated, one of its callers. getType and createPacket also follow their first callers.

Also, resolveTransactionId now masks the wire handle to 16 bits, so a sign-extended concrete handle such as FFFF8000 resolves to transaction 32768 instead of being rejected. It is covered by a regression test for OPEN_BLOB.

🤖 Generated with Claude Code

@rishi-rana
rishi-rana requested a review from terrymanu December 1, 2026 01:58

@terrymanu terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

This PR validates transaction handles before opening BLOBs and adds lazy-handle resolution and transaction cleanup. The fix direction is sound, but the new 16-bit mask conflicts with the existing ID allocator and breaks long-lived connections.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 1

The following is a confirmed subset of blocking issues. Formal confirmation limitations are described under Coverage.

Blocking Issues

  1. [P1] The valid handle for the 65,536th transaction is rejected

    • Evidence: The new resolution logic masks 65536 to 0, while the allocator still generates and registers 65536. A comparison using the exact base and head generator sources confirmed that the base accepts this handle, whereas the head rejects it while retaining the active transaction. Jaybird 5.0.13 sends the integer handle back unchanged.
    • Impact: After a connection completes 65,535 transactions, execution, commit, and rollback fail for the next transaction. Its active registration cannot be cleared, so subsequent transaction starts are also rejected. Reconnecting is required.
    • Required Change: Align the handle domain used by ID allocation, packet resolution, and cleanup. Preserve signed-handle and lazy-handle semantics, and add regression coverage across the 65535/65536 boundary.

Coverage

Public head: 221a95dc64a38c0dccb2821e8854f6618aaef690. Two independent source reviews covered all 20 changed files. Checkstyle and Spotless covered all changed files and passed.

The affected production sources and all 10 changed test classes compiled successfully. Of 122 JUnit tests, 48 passed and 74 failed. Failures involved cached dependency and SPI conflicts, so the complete suite was not verified as passing.

The exact head Git object was unavailable locally. Ledger initialization failed and session validation could not complete; formal confirmation is therefore not claimed. This assessment covers code correctness only. CI was not reviewed, and E2E tests were not run.

Allocate transaction handles from 1 to 0xFFFE and wrap around, so every
handle returned by START survives the 16-bit normalization applied to
COMMIT, ROLLBACK and lookups, and never equals the lazy placeholder.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@rishi-rana

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in 9098fc3.

[P1] The valid handle for the 65,536th transaction is rejected

FirebirdTransactionIdGenerator.nextTransactionId now allocates handles from 1 to 0xFFFE and wraps back to 1. That is the same 16-bit domain the lookup normalization uses. A handle returned by START therefore survives the & 0xFFFF applied to COMMIT, ROLLBACK and lookups, including for OPEN_BLOB. The allocator never produces 0 or the 0xFFFF placeholder. Signed-handle and lazy-handle resolution are unchanged.

Regression tests cover the wrap in the generator (65534 followed by 1) and, for both COMMIT and ROLLBACK, a START after 65,535 completed transactions that completes and leaves no active transaction.

🤖 Generated with Claude Code

@terrymanu terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

This PR adds transaction-handle validation before opening BLOBs and improves deferred-handle resolution and transaction cleanup. No additional blocking design or implementation issues were found.

Result

Review Result: Mergeable

The code review passes under the two naming exceptions explicitly accepted for this review.

Evidence

  • Invalid-handle rejection, deferred-handle resolution, transaction-ID wrapping, and connection-resource cleanup have been verified.
  • The optional lambda parameter and lastTransactionId actual-value naming remain non-blocking for this PR and will be corrected in a follow-up PR. The repository’s general naming standards remain applicable.

Coverage

Reviewed head: 9098fc3414d51c13ad11b9f0a718087adfa09725, covering all 20 changed files. Both independent reassessments and final session validation passed.

Checkstyle and Spotless passed. Previously passing results for the same commit were reused: 1,103 unit tests and four cross-module checks.

This assessment covers code correctness only. CI was not reviewed; the full Maven reactor and live-database end-to-end tests were not run.

@terrymanu terrymanu added this to the 5.5.4 milestone Dec 4, 2026
@terrymanu
terrymanu merged commit 9982751 into apache:master Dec 4, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Firebird Proxy opens a BLOB with an unknown transaction handle

2 participants