From 433d99f7e720dd4c13e618bd08fdde0cb386d907 Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Tue, 17 Nov 2026 18:28:55 +0000 Subject: [PATCH 1/7] feat(spanner): Add ScaNN vector index DDL sample Approximate nearest neighbors search in Cloud Spanner requires creating a NON NULL-filtered ScaNN vector index via asynchronous database DDL, which previously had only SQL examples. --- .../create_vector_index.py | 101 ++++++++++++ .../tests/create_vector_index_test.py | 152 ++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py create mode 100644 spanner/search_and_ai/tests/create_vector_index_test.py diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py new file mode 100644 index 0000000000..91b362cb36 --- /dev/null +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py @@ -0,0 +1,101 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START spanner_create_vector_index] +import sys + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 + + +def create_vector_index(project_id: str, instance_id: str, database_id: str) -> None: + """Creates a ScaNN vector index on a fixed-length FLOAT32 embedding column. + + Args: + project_id: The Google Cloud project ID. + instance_id: The Enterprise-edition Spanner instance ID. + database_id: The Spanner database ID containing the Documents table. + """ + client = spanner_admin_database_v1.DatabaseAdminClient() + database_path = client.database_path(project_id, instance_id, database_id) + index_name = "DocEmbeddingIndex" + + # STORING WordCount lets ANN queries filter at the vector index leaf level. + ddl_statement = ( + f"CREATE VECTOR INDEX {index_name} " + "ON Documents(DocEmbedding) " + "STORING (WordCount) " + "OPTIONS (distance_type = 'COSINE')" + ) + request = spanner_admin_database_v1.UpdateDatabaseDdlRequest( + database=database_path, + statements=[ddl_statement], + ) + + try: + operation = client.update_database_ddl(request=request) + print(f"Waiting for vector index '{index_name}' creation to complete...") + operation.result(timeout=300) + except (exceptions.AlreadyExists, exceptions.FailedPrecondition) as err: + print( + f"error: vector index '{index_name}' already exists or preconditions " + f"failed on database '{database_id}' in instance '{instance_id}' " + f"for project '{project_id}': {err.message}", + file=sys.stderr, + ) + except exceptions.GoogleAPICallError as err: + print( + f"error: failed to create vector index '{index_name}' on database " + f"'{database_id}' in instance '{instance_id}' for project " + f"'{project_id}': {err.message}", + file=sys.stderr, + ) + else: + print(f"Resource ID: {database_path}") + print("Distance Type: COSINE") + print(f"Index Name: {index_name}") + + +# [END spanner_create_vector_index] + + +if __name__ == "__main__": + import argparse + import os + + parser = argparse.ArgumentParser( + description="Create a ScaNN vector index in Spanner." + ) + 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( + "--instance-id", + default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), + help="Spanner instance ID (default: $SPANNER_INSTANCE_ID)", + ) + parser.add_argument( + "--database-id", + default=os.environ.get("SPANNER_DATABASE_ID", "example-db"), + help="Spanner database ID (default: $SPANNER_DATABASE_ID)", + ) + args = parser.parse_args() + + create_vector_index( + project_id=args.project_id, + instance_id=args.instance_id, + database_id=args.database_id, + ) diff --git a/spanner/search_and_ai/tests/create_vector_index_test.py b/spanner/search_and_ai/tests/create_vector_index_test.py new file mode 100644 index 0000000000..e58dd35932 --- /dev/null +++ b/spanner/search_and_ai/tests/create_vector_index_test.py @@ -0,0 +1,152 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import runpy +from unittest import mock + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 +import pytest +from spanner_search_and_ai import create_vector_index + +from . import conftest + +PROJECT_ID = "example-project-id" +INSTANCE_ID = "example-instance" +DATABASE_ID = "example-db" +DATABASE_PATH = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}" +ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" + + +@mock.patch(ADMIN_CLIENT) +def test_create_vector_index_success( + mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] +) -> None: + client = mock_client_class.return_value + client.database_path.return_value = DATABASE_PATH + + create_vector_index.create_vector_index(PROJECT_ID, INSTANCE_ID, DATABASE_ID) + + request = client.update_database_ddl.call_args.kwargs["request"] + assert request.database == DATABASE_PATH + assert "CREATE VECTOR INDEX DocEmbeddingIndex" in request.statements[0] + client.update_database_ddl.return_value.result.assert_called_once_with(timeout=300) + + out, err = capsys.readouterr() + assert "Waiting for vector index 'DocEmbeddingIndex'" in out + assert f"Resource ID: {DATABASE_PATH}" in out + assert "Distance Type: COSINE" in out + assert "Index Name: DocEmbeddingIndex" in out + assert err == "" + + +@pytest.mark.parametrize( + "error, expected_prefix", + [ + ( + exceptions.FailedPrecondition("Duplicate name"), + "error: vector index 'DocEmbeddingIndex' already exists", + ), + ( + exceptions.PermissionDenied("denied"), + "error: failed to create vector index 'DocEmbeddingIndex'", + ), + ], +) +@mock.patch(ADMIN_CLIENT) +def test_create_vector_index_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_vector_index.create_vector_index(PROJECT_ID, INSTANCE_ID, DATABASE_ID) + + _out, err = capsys.readouterr() + assert err.startswith(expected_prefix) + + +@mock.patch(ADMIN_CLIENT) +def test_create_vector_index_cli_entrypoint( + mock_client_class: mock.MagicMock, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + mock_client_class.return_value.database_path.return_value = DATABASE_PATH + monkeypatch.setattr( + "sys.argv", + [ + "create_vector_index.py", + "--project-id", + PROJECT_ID, + "--instance-id", + INSTANCE_ID, + "--database-id", + DATABASE_ID, + ], + ) + + runpy.run_module("spanner_search_and_ai.create_vector_index", run_name="__main__") + + assert "Index Name: DocEmbeddingIndex" in capsys.readouterr().out + + +@conftest.live_only +def test_create_vector_index_live( + capsys: pytest.CaptureFixture[str], +) -> None: + admin_client = spanner_admin_database_v1.DatabaseAdminClient() + db_path = admin_client.database_path( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + ) + admin_client.update_database_ddl( + request=spanner_admin_database_v1.UpdateDatabaseDdlRequest( + database=db_path, + statements=["DROP VECTOR INDEX IF EXISTS DocEmbeddingIndex"], + ) + ).result(timeout=300) + + try: + create_vector_index.create_vector_index( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + ) + out, err = capsys.readouterr() + assert err == "" + assert "Index Name: DocEmbeddingIndex" in out + + # Duplicate creation exercises the FailedPrecondition error arm cleanly. + create_vector_index.create_vector_index( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + ) + _dup_out, dup_err = capsys.readouterr() + assert dup_err.startswith( + "error: vector index 'DocEmbeddingIndex' already exists" + ) + finally: + admin_client.update_database_ddl( + request=spanner_admin_database_v1.UpdateDatabaseDdlRequest( + database=db_path, + statements=["DROP VECTOR INDEX IF EXISTS DocEmbeddingIndex"], + ) + ).result(timeout=300) From 8d8de5c26f7cf44ac69596cb017b46024ef6e25e Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Tue, 17 Nov 2026 20:35:42 +0000 Subject: [PATCH 2/7] fix(spanner): Add IS NOT NULL filter to ScaNN vector index DDL Including WHERE DocEmbedding IS NOT NULL allows the vector index DDL to succeed on both NOT NULL and nullable embedding columns. --- .../src/spanner_search_and_ai/create_vector_index.py | 1 + spanner/search_and_ai/tests/create_vector_index_test.py | 1 + 2 files changed, 2 insertions(+) diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py index 91b362cb36..dd62efc63b 100644 --- a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py @@ -36,6 +36,7 @@ def create_vector_index(project_id: str, instance_id: str, database_id: str) -> f"CREATE VECTOR INDEX {index_name} " "ON Documents(DocEmbedding) " "STORING (WordCount) " + "WHERE DocEmbedding IS NOT NULL " "OPTIONS (distance_type = 'COSINE')" ) request = spanner_admin_database_v1.UpdateDatabaseDdlRequest( diff --git a/spanner/search_and_ai/tests/create_vector_index_test.py b/spanner/search_and_ai/tests/create_vector_index_test.py index e58dd35932..8b6eceb126 100644 --- a/spanner/search_and_ai/tests/create_vector_index_test.py +++ b/spanner/search_and_ai/tests/create_vector_index_test.py @@ -41,6 +41,7 @@ def test_create_vector_index_success( request = client.update_database_ddl.call_args.kwargs["request"] assert request.database == DATABASE_PATH assert "CREATE VECTOR INDEX DocEmbeddingIndex" in request.statements[0] + assert "WHERE DocEmbedding IS NOT NULL" in request.statements[0] client.update_database_ddl.return_value.result.assert_called_once_with(timeout=300) out, err = capsys.readouterr() From 8fb432cc3b3a47c488e338fdf2b3c37b5feee80b Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Wed, 18 Nov 2026 00:38:09 +0000 Subject: [PATCH 3/7] fix(spanner): Omit project_id from sample stdout and stderr output Prints short resource identifiers instead of full project-prefixed resource paths and omits project_id from diagnostic messages. --- .../src/spanner_search_and_ai/create_vector_index.py | 10 +++++----- .../search_and_ai/tests/create_vector_index_test.py | 5 ++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py index dd62efc63b..1774af3136 100644 --- a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py @@ -51,19 +51,19 @@ def create_vector_index(project_id: str, instance_id: str, database_id: str) -> except (exceptions.AlreadyExists, exceptions.FailedPrecondition) as err: print( f"error: vector index '{index_name}' already exists or preconditions " - f"failed on database '{database_id}' in instance '{instance_id}' " - f"for project '{project_id}': {err.message}", + f"failed on database '{database_id}' in instance '{instance_id}': " + f"{err.message}", file=sys.stderr, ) except exceptions.GoogleAPICallError as err: print( f"error: failed to create vector index '{index_name}' on database " - f"'{database_id}' in instance '{instance_id}' for project " - f"'{project_id}': {err.message}", + f"'{database_id}' in instance '{instance_id}'" + f": {err.message}", file=sys.stderr, ) else: - print(f"Resource ID: {database_path}") + print(f"Resource ID: {database_id}") print("Distance Type: COSINE") print(f"Index Name: {index_name}") diff --git a/spanner/search_and_ai/tests/create_vector_index_test.py b/spanner/search_and_ai/tests/create_vector_index_test.py index 8b6eceb126..de09c833b1 100644 --- a/spanner/search_and_ai/tests/create_vector_index_test.py +++ b/spanner/search_and_ai/tests/create_vector_index_test.py @@ -46,7 +46,8 @@ def test_create_vector_index_success( out, err = capsys.readouterr() assert "Waiting for vector index 'DocEmbeddingIndex'" in out - assert f"Resource ID: {DATABASE_PATH}" in out + assert f"Resource ID: {DATABASE_ID}" in out + assert PROJECT_ID not in out assert "Distance Type: COSINE" in out assert "Index Name: DocEmbeddingIndex" in out assert err == "" @@ -80,6 +81,8 @@ def test_create_vector_index_errors( _out, err = capsys.readouterr() assert err.startswith(expected_prefix) + assert PROJECT_ID not in err + assert PROJECT_ID not in err @mock.patch(ADMIN_CLIENT) From 9dea40a8c4822717e85f4b48cd0447470e3f0007 Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Wed, 18 Nov 2026 02:42:50 +0000 Subject: [PATCH 4/7] fix(spanner): Remove hardcoded static stdout lines from sample output Prints only runtime resource and query results instead of hardcoded string literals. --- .../src/spanner_search_and_ai/create_vector_index.py | 1 - spanner/search_and_ai/tests/create_vector_index_test.py | 1 - 2 files changed, 2 deletions(-) diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py index 1774af3136..d998870940 100644 --- a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py @@ -64,7 +64,6 @@ def create_vector_index(project_id: str, instance_id: str, database_id: str) -> ) else: print(f"Resource ID: {database_id}") - print("Distance Type: COSINE") print(f"Index Name: {index_name}") diff --git a/spanner/search_and_ai/tests/create_vector_index_test.py b/spanner/search_and_ai/tests/create_vector_index_test.py index de09c833b1..ec9cde377c 100644 --- a/spanner/search_and_ai/tests/create_vector_index_test.py +++ b/spanner/search_and_ai/tests/create_vector_index_test.py @@ -48,7 +48,6 @@ def test_create_vector_index_success( assert "Waiting for vector index 'DocEmbeddingIndex'" in out assert f"Resource ID: {DATABASE_ID}" in out assert PROJECT_ID not in out - assert "Distance Type: COSINE" in out assert "Index Name: DocEmbeddingIndex" in out assert err == "" From c09ed918e43f0c518333172a4fcd144c04667d28 Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Wed, 18 Nov 2026 21:40:41 +0000 Subject: [PATCH 5/7] fix(spanner): report operation wait timeouts in create_vector_index 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. --- .../src/spanner_search_and_ai/create_vector_index.py | 6 ++++++ spanner/search_and_ai/tests/create_vector_index_test.py | 1 + 2 files changed, 7 insertions(+) diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py index d998870940..257d0c884e 100644 --- a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py @@ -55,6 +55,12 @@ def create_vector_index(project_id: str, instance_id: str, database_id: str) -> f"{err.message}", file=sys.stderr, ) + except TimeoutError as err: + print( + f"error: timed out waiting for the operation on database '{database_id}' " + f"to complete; the operation may still be running: {err}", + file=sys.stderr, + ) except exceptions.GoogleAPICallError as err: print( f"error: failed to create vector index '{index_name}' on database " diff --git a/spanner/search_and_ai/tests/create_vector_index_test.py b/spanner/search_and_ai/tests/create_vector_index_test.py index ec9cde377c..400358081a 100644 --- a/spanner/search_and_ai/tests/create_vector_index_test.py +++ b/spanner/search_and_ai/tests/create_vector_index_test.py @@ -55,6 +55,7 @@ def test_create_vector_index_success( @pytest.mark.parametrize( "error, expected_prefix", [ + (TimeoutError("deadline"), "error: timed out waiting for the operation"), ( exceptions.FailedPrecondition("Duplicate name"), "error: vector index 'DocEmbeddingIndex' already exists", From 3452522194af51cba9d1a458c17d2e54e8a1158b Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Thu, 19 Nov 2026 04:41:32 +0000 Subject: [PATCH 6/7] style(spanner): use triple-quoted SQL strings in create_vector_index 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/search_and_ai/src/spanner_search_and_ai/create_vector_index.py --- .../spanner_search_and_ai/create_vector_index.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py index 257d0c884e..0ce61fc016 100644 --- a/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_vector_index.py @@ -32,13 +32,13 @@ def create_vector_index(project_id: str, instance_id: str, database_id: str) -> index_name = "DocEmbeddingIndex" # STORING WordCount lets ANN queries filter at the vector index leaf level. - ddl_statement = ( - f"CREATE VECTOR INDEX {index_name} " - "ON Documents(DocEmbedding) " - "STORING (WordCount) " - "WHERE DocEmbedding IS NOT NULL " - "OPTIONS (distance_type = 'COSINE')" - ) + ddl_statement = f""" + CREATE VECTOR INDEX {index_name} + ON Documents(DocEmbedding) + STORING (WordCount) + WHERE DocEmbedding IS NOT NULL + OPTIONS (distance_type = 'COSINE') + """ request = spanner_admin_database_v1.UpdateDatabaseDdlRequest( database=database_path, statements=[ddl_statement], From 50740639a79edc8b8099799746a638acb2c0b73b Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Fri, 4 Dec 2026 05:45:33 +0000 Subject: [PATCH 7/7] chore(spanner): apply review feedback to create_vector_index Problem: reviewers of this sample set asked for stricter and clearer tests and for a single source of truth for dependencies. Mocks were created without a spec, so a renamed client argument would pass silently; the mocked wait timeout was raised from the API call instead of from the operation's result; live tests did not say which environment variables they need; and some tests carried leftover or repeated lines. Package dependencies were pinned in both pyproject.toml and requirements.txt. Solution: where applicable to the files below, patch client classes with autospec=True, raise the mocked TimeoutError from operation.result(), document the required environment variables above each live test and skip when one is missing, remove unused or duplicated test lines, and join string literals that the formatter had left split on one line. For package scaffolding, read dependencies from requirements.txt and update the README install command to match. Files updated: - spanner/search_and_ai/tests/create_vector_index_test.py --- .../tests/create_vector_index_test.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/spanner/search_and_ai/tests/create_vector_index_test.py b/spanner/search_and_ai/tests/create_vector_index_test.py index 400358081a..f6e8cb6bd4 100644 --- a/spanner/search_and_ai/tests/create_vector_index_test.py +++ b/spanner/search_and_ai/tests/create_vector_index_test.py @@ -29,7 +29,7 @@ ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" -@mock.patch(ADMIN_CLIENT) +@mock.patch(ADMIN_CLIENT, autospec=True) def test_create_vector_index_success( mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] ) -> None: @@ -66,7 +66,7 @@ def test_create_vector_index_success( ), ], ) -@mock.patch(ADMIN_CLIENT) +@mock.patch(ADMIN_CLIENT, autospec=True) def test_create_vector_index_errors( mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str], @@ -75,17 +75,19 @@ def test_create_vector_index_errors( ) -> None: client = mock_client_class.return_value client.database_path.return_value = DATABASE_PATH - client.update_database_ddl.side_effect = error + if isinstance(error, TimeoutError): + client.update_database_ddl.return_value.result.side_effect = error + else: + client.update_database_ddl.side_effect = error create_vector_index.create_vector_index(PROJECT_ID, INSTANCE_ID, DATABASE_ID) _out, err = capsys.readouterr() assert err.startswith(expected_prefix) assert PROJECT_ID not in err - assert PROJECT_ID not in err -@mock.patch(ADMIN_CLIENT) +@mock.patch(ADMIN_CLIENT, autospec=True) def test_create_vector_index_cli_entrypoint( mock_client_class: mock.MagicMock, monkeypatch: pytest.MonkeyPatch, @@ -110,6 +112,8 @@ def test_create_vector_index_cli_entrypoint( assert "Index Name: DocEmbeddingIndex" in capsys.readouterr().out +# Live integration test: skipped unless RUN_INTEGRATION_TESTS=true is set along with +# GOOGLE_CLOUD_PROJECT, SPANNER_INSTANCE_ID, and SPANNER_DATABASE_ID. @conftest.live_only def test_create_vector_index_live( capsys: pytest.CaptureFixture[str],