Skip to content

fix(cockroachdb): preserve structured query results during txn retry replay - #11861

Merged
naorpeled merged 2 commits into
typeorm:masterfrom
naorpeled:fix/cockroach-db-transaction-not-using-useStructuredResult
Dec 20, 2025
Merged

naorpeled merged 2 commits into
typeorm:masterfrom
naorpeled:fix/cockroach-db-transaction-not-using-useStructuredResult

Conversation

@naorpeled

Copy link
Copy Markdown
Member

Summary

CockroachDB transaction retry (40001) replays the recorded queries via ROLLBACK TO SAVEPOINT cockroach_restart.

During that replay, TypeORM was not preserving the original useStructuredResult flag per query. That can change the return shape of re-executed queries during retries, which in turn can prevent generated values (e.g. primary keys) from being propagated back onto entities after a retried INSERT.

On CockroachDB v24 this shows up in test/github-issues/9984 where post.id can remain undefined after a retried transaction, and later findOneBy({ id: post.id }) fails (especially now that strict handling for undefined where values is enabled).

Fix

  • Record useStructuredResult alongside { query, parameters } in the Cockroach retry buffer.
  • Replay each stored query using the same useStructuredResult value it had originally.

Why it’s needed

  • Keeps retry replay behavior consistent with the original execution.
  • Ensures generated values/IDs are applied the same way on retry as on the first attempt.
  • Prevents follow-up queries from seeing undefined identifiers after a retried write.

Tests

  • Reproduces/fixes the failure in github issues > #9984 on CockroachDB v24 with inject_retry_errors_enabled=true.

CockroachQueryRunner replays stored queries when it hits a 40001 retryable
serialization error. Those stored queries were replayed without the original
useStructuredResult flag, which can change the returned shape during retries.

In practice this can prevent generated values (e.g. primary keys) from being
propagated back to entities after a retried INSERT, leaving e.g. post.id
undefined. With strict invalidWhereValuesBehavior, that later surfaces as a
TypeORMError when building a where condition.

This change stores and replays useStructuredResult alongside query+params so
retries behave the same as the initial execution.
Copilot AI review requested due to automatic review settings December 20, 2025 19:50
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

9984 - PR Code Verified

Compliant requirements:

  • Properly handle TransactionRetryWithProtoRefreshError (error code 40001) in CockroachDB by preserving query execution context during retry
  • Client retries the transaction by replaying queries with correct parameters

Requires further human verification:

  • Verify that the fix prevents application crashes that require full restart when TransactionRetryWithProtoRefreshError occurs
  • Confirm that try/catch blocks can now properly catch and handle the error in real-world scenarios
  • Test with actual CockroachDB cluster under concurrent write load to ensure the retry mechanism works as expected
  • Validate that the fix handles all edge cases mentioned in CockroachDB's transaction retry error reference documentation
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Type Safety

The queries array now stores objects with a useStructuredResult boolean field, but there's no validation that this field is always provided. If useStructuredResult is undefined in the original call, it could lead to inconsistent behavior during retry.

protected queries: {
    query: string
    parameters?: any[]
    useStructuredResult: boolean
}[] = []
Potential Undefined

When replaying queries during retry, the code passes q.useStructuredResult to the query method. If this value was not properly captured or is undefined, it could cause the retry to behave differently than the original execution, potentially leading to the same issue the PR aims to fix.

result = await this.query(
    q.query,
    q.parameters,
    q.useStructuredResult,
)

@pkg-pr-new

pkg-pr-new Bot commented Dec 20, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11861
    

commit: e10cc47

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 20, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to e10cc47

CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve all query results during retry

Fix the transaction retry logic to return the correct query result instead of
only the last one. The current implementation overwrites the result in a loop,
returning the result of the final query in the transaction, which is a bug.

src/driver/cockroachdb/CockroachQueryRunner.ts [365-377]

-let result = undefined
+const results: any[] = []
 for (const q of this.queries) {
     this.driver.connection.logger.logQuery(
         `Retrying transaction for query "${q.query}"`,
         q.parameters,
         this,
     )
-    result = await this.query(
+    const queryResult = await this.query(
         q.query,
         q.parameters,
         q.useStructuredResult,
     )
+    results.push(queryResult)
 }
+result = results.length === 1 ? results[0] : results

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a significant bug where, during a transaction retry, the result variable is overwritten in each iteration, causing only the result of the last query to be returned. This leads to incorrect behavior and potential data loss for the calling code, which would expect the result of the specific query it invoked.

High
  • More

Previous suggestions

Suggestions up to commit 1db215c
CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix incorrect result on transaction retry

Fix a bug in the transaction retry logic to ensure the correct result is
returned. The current implementation returns the result of the last query in the
transaction, not the one that failed and initiated the retry.

src/driver/cockroachdb/CockroachQueryRunner.ts [365-402]

-let result = undefined
+const originalQuery = this.queries.pop()!
+
 for (const q of this.queries) {
     this.driver.connection.logger.logQuery(
         `Retrying transaction for query "${q.query}"`,
         q.parameters,
         this,
     )
-    result = await this.query(
+    await this.query(
         q.query,
         q.parameters,
         q.useStructuredResult,
     )
 }
+
+this.driver.connection.logger.logQuery(
+    `Retrying transaction for query "${originalQuery.query}"`,
+    originalQuery.parameters,
+    this,
+)
+const result = await this.query(
+    originalQuery.query,
+    originalQuery.parameters,
+    originalQuery.useStructuredResult,
+)
+
 this.transactionRetries = 0
 this.storeQueries = true
 
 return result
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug where a transaction retry returns the result of the last replayed query instead of the one that originally failed, and provides a correct fix.

High

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a critical bug in CockroachDB's transaction retry mechanism where the useStructuredResult flag was not preserved during query replay after a 40001 error (transaction retry). This caused INSERT operations to fail to propagate generated IDs back to entities during retries, leading to undefined primary keys and subsequent query failures.

Key Changes

  • Added useStructuredResult field to the internal query recording structure
  • Preserved the flag when storing queries during transaction execution
  • Restored the flag when replaying queries after transaction rollback

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks LGTM @naorpeled

@gioboa

gioboa commented Dec 20, 2025

Copy link
Copy Markdown
Collaborator

Are we closing any issue with this fix?

@naorpeled

Copy link
Copy Markdown
Member Author

Are we closing any issue with this fix?

Doesn't seem like it, I tried to search but couldn't find any relevant ones

@coveralls

coveralls commented Dec 20, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.909% (-0.001%) from 80.91%
when pulling e10cc47 on naorpeled:fix/cockroach-db-transaction-not-using-useStructuredResult
into 9f67f57 on typeorm:master.

@naorpeled
naorpeled requested a review from G0maa December 20, 2025 20:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

6 participants