Skip to content

feat(spanner): Add Vertex AI text embedding model DDL sample - #14842

Open
iennae wants to merge 4 commits into
mainfrom
feat/spanner-create-embedding-model
Open

iennae wants to merge 4 commits into
mainfrom
feat/spanner-create-embedding-model

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Calling Vertex AI text embedding models from Cloud Spanner SQL (ML.PREDICT) first requires registering the remote publisher endpoint with a CREATE MODEL DDL statement that declares the model's INPUT (content) and OUTPUT (embeddings STRUCT<values ARRAY<FLOAT32>>) signature.

Adds spanner_create_embedding_model demonstrating asynchronous CREATE MODEL registration for text-embedding-005.

Note: Stacked on #14836 (feat/spanner-vector-search-knn) so this PR shows only this sample's diff. It will merge into main after #14836.

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

Python developers implementing semantic similarity search on Cloud Spanner lacked a client library example showing parameterized FLOAT32 vector bindings with COSINE_DISTANCE.
Registering a remote Vertex AI embedding endpoint in Cloud Spanner requires matching the model's exact INPUT and OUTPUT struct schemas in database DDL.
@iennae
iennae requested review from a team as code owners November 17, 2026 18:48
@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 17, 2026
@snippet-bot

snippet-bot Bot commented Nov 17, 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 module to register a remote Vertex AI text-embedding model in a Spanner schema, along with its corresponding unit and integration tests. The feedback suggests re-raising exceptions in the create_embedding_model function instead of only printing them to stderr, which ensures that failures are properly propagated to programmatic callers and CLI executions. Additionally, the unit tests should be updated to expect these exceptions.

Comment on lines +64 to +81
try:
operation = client.update_database_ddl(request=request)
print(f"Waiting for remote model '{model_name}' registration...")
operation.result(timeout=300)
except exceptions.AlreadyExists as err:
print(
f"error: model '{model_name}' already exists on database "
f"'{database_id}' in instance '{instance_id}' and location "
f"'{location_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to register model '{model_name}' on database "
f"'{database_id}' in instance '{instance_id}' and location "
f"'{location_id}' for project '{project_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

Catching the exceptions and only printing them to stderr causes the function to return normally (None). This means that any programmatic caller will not know that the operation failed, and running this file as a CLI script will exit with status 0 (success) even on failure. It is better to re-raise the exceptions so that failures are propagated correctly.

Suggested change
try:
operation = client.update_database_ddl(request=request)
print(f"Waiting for remote model '{model_name}' registration...")
operation.result(timeout=300)
except exceptions.AlreadyExists as err:
print(
f"error: model '{model_name}' already exists on database "
f"'{database_id}' in instance '{instance_id}' and location "
f"'{location_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to register model '{model_name}' on database "
f"'{database_id}' in instance '{instance_id}' and location "
f"'{location_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
try:
operation = client.update_database_ddl(request=request)
print(f"Waiting for remote model '{model_name}' registration...")
operation.result(timeout=300)
except exceptions.AlreadyExists as err:
print(
f"error: model '{model_name}' already exists on database "
f"'{database_id}' in instance '{instance_id}' and location "
f"'{location_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
raise
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to register model '{model_name}' on database "
f"'{database_id}' in instance '{instance_id}' and location "
f"'{location_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
raise

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 feedback! Standalone documentation snippets here intentionally catch google.api_core.exceptions inside the sample function and print actionable diagnostic messages to stderr so readers can see concrete error handling directly in context, so we are keeping the try/except block.

Comment on lines +69 to +84
def test_create_embedding_model_errors(
mock_client_class: mock.MagicMock,
capsys: pytest.CaptureFixture[str],
error: Exception,
expected_prefix: str,
) -> None:
client = mock_client_class.return_value
client.database_path.return_value = DATABASE_PATH
client.update_database_ddl.side_effect = error

create_embedding_model.create_embedding_model(
PROJECT_ID, LOCATION_ID, INSTANCE_ID, DATABASE_ID
)

_out, err = capsys.readouterr()
assert err.startswith(expected_prefix)

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

Update the test to expect the exception to be raised, aligning with the propagated exceptions in the main function.

Suggested change
def test_create_embedding_model_errors(
mock_client_class: mock.MagicMock,
capsys: pytest.CaptureFixture[str],
error: Exception,
expected_prefix: str,
) -> None:
client = mock_client_class.return_value
client.database_path.return_value = DATABASE_PATH
client.update_database_ddl.side_effect = error
create_embedding_model.create_embedding_model(
PROJECT_ID, LOCATION_ID, INSTANCE_ID, DATABASE_ID
)
_out, err = capsys.readouterr()
assert err.startswith(expected_prefix)
def test_create_embedding_model_errors(
mock_client_class: mock.MagicMock,
capsys: pytest.CaptureFixture[str],
error: Exception,
expected_prefix: str,
) -> None:
client = mock_client_class.return_value
client.database_path.return_value = DATABASE_PATH
client.update_database_ddl.side_effect = error
with pytest.raises(type(error)):
create_embedding_model.create_embedding_model(
PROJECT_ID, LOCATION_ID, INSTANCE_ID, DATABASE_ID
)
_out, err = capsys.readouterr()
assert err.startswith(expected_prefix)

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! Since the sample keeps its explicit exception handling and stderr reporting, this test keeps its capsys stderr assertions.

Prints short resource identifiers instead of full project-prefixed resource paths and omits project_id from diagnostic messages.
Problem: the sample waits on a long-running operation with a client-side
timeout. When that wait expires the client raises TimeoutError, which is
not an API call error, so the sample ended with an unhandled traceback.

Solution: catch TimeoutError and print a clear message to stderr noting
that only the wait timed out and the operation may still be running (the
timeout does not cancel it). Add a unit test covering the new handler.
Base automatically changed from feat/spanner-vector-search-knn to main December 1, 2026 00:18
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.

2 participants