Skip to content

feat(spanner): Add per-statement DML RPC timeout sample - #14926

Open
iennae wants to merge 3 commits into
feat/spanner-select-for-updatefrom
feat/spanner-set-statement-timeout
Open

iennae wants to merge 3 commits into
feat/spanner-select-for-updatefrom
feat/spanner-set-statement-timeout

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_set_statement_timeout configuring an explicit RPC timeout on transaction.execute_update().

Note: Stacked on #14839 (feat/spanner-select-for-update) so this PR shows only this sample's diff. It will merge into main after #14839.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Bounding individual SQL or DML RPC latency inside a transaction passes timeout to transaction.execute_update(). Add a standalone spanner_set_statement_timeout sample and test suite.
@iennae
iennae requested review from a team as code owners November 18, 2026 04:54
@product-auto-label product-auto-label Bot added api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples. labels Nov 18, 2026
@snippet-bot

snippet-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces a new sample script and corresponding tests demonstrating how to execute a Spanner DML statement with an explicit per-statement RPC timeout. The feedback suggests several improvements to make the code more robust and idiomatic: allowing project_id to be optional to leverage Application Default Credentials (ADC) both in the function signature and the CLI argument parser, returning the row count directly from the transaction callback instead of using a nonlocal variable, and replacing the deprecated err.message with str(err) to prevent potential AttributeError exceptions in Python 3.

Comment on lines +23 to +25
def execute_statement_with_timeout(
project_id: str, instance_id: str, database_id: str
) -> None:

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.

medium

Allow project_id to be optional (str | None) so that the Spanner client can automatically infer the project ID from Application Default Credentials (ADC) when it is not explicitly provided.

Suggested change
def execute_statement_with_timeout(
project_id: str, instance_id: str, database_id: str
) -> None:
def execute_statement_with_timeout(
project_id: str | None, instance_id: str, database_id: str
) -> None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +35 to +46
inserted_rows = 0

def write_with_timeout(transaction: spanner_v1.transaction.Transaction) -> None:
nonlocal inserted_rows
inserted_rows = transaction.execute_update(
"INSERT INTO Singers (SingerId, FirstName, LastName) "
"VALUES (112, 'George', 'Washington')",
timeout=60.0,
)

try:
database.run_in_transaction(write_with_timeout)

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.

medium

Instead of using a nonlocal variable to capture the number of inserted rows from within the transaction callback, you can return the value directly from the callback. database.run_in_transaction automatically returns the value returned by the callback function. This is more idiomatic and avoids mutable nonlocal state.

Suggested change
inserted_rows = 0
def write_with_timeout(transaction: spanner_v1.transaction.Transaction) -> None:
nonlocal inserted_rows
inserted_rows = transaction.execute_update(
"INSERT INTO Singers (SingerId, FirstName, LastName) "
"VALUES (112, 'George', 'Washington')",
timeout=60.0,
)
try:
database.run_in_transaction(write_with_timeout)
def write_with_timeout(transaction: spanner_v1.transaction.Transaction) -> int:
return transaction.execute_update(
"INSERT INTO Singers (SingerId, FirstName, LastName) "
"VALUES (112, 'George', 'Washington')",
timeout=60.0,
)
try:
inserted_rows = database.run_in_transaction(write_with_timeout)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! Keeping this as is for consistency with the rest of this sample set: transaction callbacks record their result in an enclosing variable and the sample prints it after the transaction commits, rather than passing a return value back through run_in_transaction.

Comment on lines +47 to +58
except exceptions.DeadlineExceeded as err:
print(
f"error: DML statement exceeded 60s timeout on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: statement-timeout transaction failed on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)

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.

medium

In Python 3, accessing err.message is deprecated and can raise an AttributeError on standard exceptions. It is more idiomatic and robust to use str(err) or interpolate the exception object directly in the f-string.

Suggested change
except exceptions.DeadlineExceeded as err:
print(
f"error: DML statement exceeded 60s timeout on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: statement-timeout transaction failed on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
except exceptions.DeadlineExceeded as err:
print(
f"error: DML statement exceeded 60s timeout on database "
f"'{database_id}' in instance '{instance_id}': {err}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: statement-timeout transaction failed on database "
f"'{database_id}' in instance '{instance_id}': {err}",
file=sys.stderr,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: the handlers interpolate the exception directly (2ce5eab).

Comment on lines +74 to +78
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)

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.

medium

Change the default value of --project-id to None (by omitting the fallback string) so that the project ID can be inferred from Application Default Credentials (ADC) if the environment variable GOOGLE_CLOUD_PROJECT is not set, rather than falling back to a placeholder string.

Suggested change
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Problem: review of this sample identified correctness and robustness
improvements in the sample and its tests.

Solution: apply the accepted review suggestions and extend the tests to
cover the updated behavior. Details are in the review thread replies.

Files updated:
  - spanner/transactions/src/spanner_transactions/set_statement_timeout.py
Problem: multi-line SQL and DDL statements were written as adjacent string
fragments. That style is easy to get wrong (a missing trailing space joins
two SQL tokens) and is harder to read than the statement itself, and the
samples in this set mixed it with triple-quoted SQL.

Solution: write each multi-line statement as a single triple-quoted string,
matching the layout already used by the other samples. Only whitespace
between SQL tokens changes; the statements are otherwise identical.

Files updated:
  - spanner/transactions/src/spanner_transactions/set_statement_timeout.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant