diff --git a/acceptance/bin/hook.py b/acceptance/bin/hook.py new file mode 100755 index 00000000000..074a675157e --- /dev/null +++ b/acceptance/bin/hook.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Make the testserver send a request of its own when a request of the test arrives. + +Usage: hook.py [--clock-offset-ms N] PATTERN OFFSET TIMES REQUEST [BODY] + + --clock-offset-ms shift the time the handler of REQUEST sees by N milliseconds, e.g. -30000 + for a resource created 30 seconds ago. Only handlers that take the time + from the request honor it (today: the vector search endpoint create). + PATTERN HTTP method and path of the request to wait for, as for fault.py: + * matches within one path segment, ** spans / + OFFSET number of matching requests to let through before the hook runs + TIMES number of times to run the hook + REQUEST HTTP method and path of the request to send, e.g. + "POST /api/2.0/vector-search/endpoints" + BODY optional body of the request to send + +The server handles REQUEST after the matching request is handled (or failed by a fault +rule) and before its response is sent. So REQUEST lands between that request and the next +one the CLI sends, whatever the speed of the machine: use it for what another client does +in the middle of a command, instead of a background process and a sleep. REQUEST is sent +with the current DATABRICKS_TOKEN, is recorded like any other request, and fails the test +if it is answered with an error. + +The rule is scoped to the current DATABRICKS_TOKEN so it only affects +the test that registers it, even when tests share a server. +""" + +import json +import os +import sys +import urllib.request + +host = os.environ.get("DATABRICKS_HOST", "") +token = os.environ.get("DATABRICKS_TOKEN", "") + +if not host: + print("DATABRICKS_HOST not set", file=sys.stderr) + sys.exit(1) + +args = sys.argv[1:] + +clock_offset_ms = 0 +if "--clock-offset-ms" in args: + i = args.index("--clock-offset-ms") + clock_offset_ms = int(args[i + 1]) + del args[i : i + 2] + +if len(args) not in (4, 5) or " " not in args[3]: + print( + f"usage: {sys.argv[0]} [--clock-offset-ms N] PATTERN OFFSET TIMES REQUEST [BODY]", + file=sys.stderr, + ) + sys.exit(1) + +pattern, offset, times = args[0], int(args[1]), int(args[2]) +method, path = args[3].split(" ", 1) +body = args[4] if len(args) == 5 else "" + +data = json.dumps( + { + "pattern": pattern, + "offset": offset, + "times": times, + "method": method, + "path": path, + "body": body, + "clock_offset_ms": clock_offset_ms, + } +).encode() + +req = urllib.request.Request( + f"{host}/__testserver/hook", + data=data, + headers={"Content-Type": "application/json", "Authorization": f"Bearer {token}"}, + method="POST", +) +urllib.request.urlopen(req) diff --git a/acceptance/bundle/resources/postgres_projects/create_504_foreign/databricks.yml b/acceptance/bundle/resources/postgres_projects/create_504_foreign/databricks.yml new file mode 100644 index 00000000000..b95ebe35d2c --- /dev/null +++ b/acceptance/bundle/resources/postgres_projects/create_504_foreign/databricks.yml @@ -0,0 +1,12 @@ +bundle: + name: test-bundle + +sync: + paths: [] + +resources: + postgres_projects: + my_project: + project_id: test-pg-proj + display_name: "Test Postgres Project" + pg_version: 16 diff --git a/acceptance/bundle/resources/postgres_projects/create_504_foreign/out.test.toml b/acceptance/bundle/resources/postgres_projects/create_504_foreign/out.test.toml new file mode 100644 index 00000000000..15c32f324ac --- /dev/null +++ b/acceptance/bundle/resources/postgres_projects/create_504_foreign/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = [] diff --git a/acceptance/bundle/resources/postgres_projects/create_504_foreign/output.txt b/acceptance/bundle/resources/postgres_projects/create_504_foreign/output.txt new file mode 100644 index 00000000000..e0ce40eff3c --- /dev/null +++ b/acceptance/bundle/resources/postgres_projects/create_504_foreign/output.txt @@ -0,0 +1,56 @@ + +=== Outside the bundle, create a project with the project_id the bundle uses + +>>> [CLI] postgres create-project test-pg-proj --json {"spec": {"display_name": "Test Postgres Project", "pg_version": 16}} +{ + "name": "projects/test-pg-proj" +} + +=== Deploy fails: the project_id is taken + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files... +Error: cannot create resources.postgres_projects.my_project: A project with this resource name already exists in the workspace. (400 BAD_REQUEST) + +Endpoint: POST [DATABRICKS_URL]/api/2.0/postgres/projects?project_id=test-pg-proj +HTTP Status: 400 Bad Request +API error_code: BAD_REQUEST +API message: A project with this resource name already exists in the workspace. + +Files: 0 uploaded, 0 deleted + +=== The same deploy, but its create request fails with a 504 that the backend did not apply: deploy takes the project + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files... +Created postgres_projects.my_project +Files: 0 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --get --summary //postgres/projects +POST /api/2.0/postgres/projects project_id=test-pg-proj +GET /api/2.0/postgres/projects/test-pg-proj +GET /api/2.0/postgres/projects/test-pg-proj/branches/production + +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged + +=== Destroy deletes the project the bundle did not create + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.postgres_projects.my_project + +This action will result in the deletion of the following Lakebase projects along with +all their branches, databases, and endpoints. All data stored in them will be permanently lost: + delete resources.postgres_projects.my_project + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/test-bundle/default + +Destroy: 1 deleted + +>>> print_requests.py --summary //postgres/projects +DELETE /api/2.0/postgres/projects/test-pg-proj + +>>> musterr [CLI] postgres get-project projects/test-pg-proj +Error: project id not found [TraceId: [UUID]] diff --git a/acceptance/bundle/resources/postgres_projects/create_504_foreign/script b/acceptance/bundle/resources/postgres_projects/create_504_foreign/script new file mode 100644 index 00000000000..1a4ea1a2457 --- /dev/null +++ b/acceptance/bundle/resources/postgres_projects/create_504_foreign/script @@ -0,0 +1,25 @@ +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI postgres delete-project projects/test-pg-proj >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +title "Outside the bundle, create a project with the project_id the bundle uses" +trace $CLI postgres create-project test-pg-proj --json '{"spec": {"display_name": "Test Postgres Project", "pg_version": 16}}' | jq '{name}' + +title "Deploy fails: the project_id is taken" +trace musterr $CLI bundle deploy +rm -f "$OUT_REQUESTS" + +title "The same deploy, but its create request fails with a 504 that the backend did not apply: deploy takes the project" +fault.py "POST /api/2.0/postgres/projects" 504 0 1 DEADLINE_EXCEEDED +trace $CLI bundle deploy +trace print_requests.py --get --summary //postgres/projects +trace $CLI bundle plan + +title "Destroy deletes the project the bundle did not create" +trace $CLI bundle destroy --auto-approve +trace print_requests.py --summary //postgres/projects +trace musterr $CLI postgres get-project projects/test-pg-proj diff --git a/acceptance/bundle/resources/postgres_projects/create_504_foreign/test.toml b/acceptance/bundle/resources/postgres_projects/create_504_foreign/test.toml new file mode 100644 index 00000000000..a25564d66a4 --- /dev/null +++ b/acceptance/bundle/resources/postgres_projects/create_504_foreign/test.toml @@ -0,0 +1,7 @@ +Badness = "After a create request fails with a 504, deploy looks the project up by name and takes any project created less than a minute before the request. The read response has status.owner, which is not checked. Here the project was created outside the bundle, and the 504 was returned before the backend handled the request, so the bundle created nothing; without the 504 the same deploy fails with 'already exists'. Destroy then deletes the project and its data. Deploy should take a project only when it can tell that its own request created it, and otherwise fail as it does without the 504." + +Cloud = false +EnvMatrix.READPLAN = [] +Env.DATABRICKS_BUNDLE_ENGINE = "direct" +Env.DATABRICKS_BUNDLE_RETRY_INTERVAL_MS = "100" +SuppressLines.warn_retry = "" diff --git a/acceptance/bundle/resources/schemas/create_504_foreign/databricks.yml.tmpl b/acceptance/bundle/resources/schemas/create_504_foreign/databricks.yml.tmpl new file mode 100644 index 00000000000..558715aca0e --- /dev/null +++ b/acceptance/bundle/resources/schemas/create_504_foreign/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: schema-504-foreign-$UNIQUE_NAME + +sync: + paths: [] + +resources: + schemas: + my_schema: + catalog_name: main + name: test-schema-$UNIQUE_NAME diff --git a/acceptance/bundle/resources/schemas/create_504_foreign/out.test.toml b/acceptance/bundle/resources/schemas/create_504_foreign/out.test.toml new file mode 100644 index 00000000000..15c32f324ac --- /dev/null +++ b/acceptance/bundle/resources/schemas/create_504_foreign/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = [] diff --git a/acceptance/bundle/resources/schemas/create_504_foreign/output.txt b/acceptance/bundle/resources/schemas/create_504_foreign/output.txt new file mode 100644 index 00000000000..4263b723020 --- /dev/null +++ b/acceptance/bundle/resources/schemas/create_504_foreign/output.txt @@ -0,0 +1,56 @@ + +=== Outside the bundle, the deploying user creates a schema with the name the bundle uses + +>>> [CLI] schemas create test-schema-[UNIQUE_NAME] main +{ + "full_name": "main.test-schema-[UNIQUE_NAME]", + "created_by": "[USERNAME]" +} + +=== Deploy fails: the name is taken + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/schema-504-foreign-[UNIQUE_NAME]/default/files... +Error: cannot create resources.schemas.my_schema: Schema 'test-schema-[UNIQUE_NAME]' already exists (400 SCHEMA_ALREADY_EXISTS) + +Endpoint: POST [DATABRICKS_URL]/api/2.1/unity-catalog/schemas +HTTP Status: 400 Bad Request +API error_code: SCHEMA_ALREADY_EXISTS +API message: Schema 'test-schema-[UNIQUE_NAME]' already exists + +Files: 0 uploaded, 0 deleted + +=== The same deploy, but its create request fails with a 504 that the backend did not apply: deploy takes the schema + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/schema-504-foreign-[UNIQUE_NAME]/default/files... +Created schemas.my_schema +Files: 0 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --get --summary //unity-catalog/schemas //scim/v2/Me +POST /api/2.1/unity-catalog/schemas +GET /api/2.1/unity-catalog/schemas/main.test-schema-[UNIQUE_NAME] +GET /api/2.0/preview/scim/v2/Me + +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged + +=== Destroy deletes the schema the bundle did not create + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.my_schema + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.my_schema + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/schema-504-foreign-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> print_requests.py --summary //unity-catalog/schemas +DELETE /api/2.1/unity-catalog/schemas/main.test-schema-[UNIQUE_NAME] force=true + +>>> musterr [CLI] schemas get main.test-schema-[UNIQUE_NAME] +Error: Schema 'main.test-schema-[UNIQUE_NAME]' does not exist. diff --git a/acceptance/bundle/resources/schemas/create_504_foreign/script b/acceptance/bundle/resources/schemas/create_504_foreign/script new file mode 100644 index 00000000000..6ba18c24a1f --- /dev/null +++ b/acceptance/bundle/resources/schemas/create_504_foreign/script @@ -0,0 +1,29 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +SCHEMA="main.test-schema-$UNIQUE_NAME" + +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI schemas delete "$SCHEMA" --force >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +title "Outside the bundle, the deploying user creates a schema with the name the bundle uses" +trace $CLI schemas create "test-schema-$UNIQUE_NAME" main | jq '{full_name, created_by}' + +title "Deploy fails: the name is taken" +trace musterr $CLI bundle deploy +rm -f "$OUT_REQUESTS" + +title "The same deploy, but its create request fails with a 504 that the backend did not apply: deploy takes the schema" +fault.py "POST /api/2.1/unity-catalog/schemas" 504 0 1 DEADLINE_EXCEEDED +trace $CLI bundle deploy +trace print_requests.py --get --summary //unity-catalog/schemas //scim/v2/Me +trace $CLI bundle plan + +title "Destroy deletes the schema the bundle did not create" +trace $CLI bundle destroy --auto-approve +trace print_requests.py --summary //unity-catalog/schemas +trace musterr $CLI schemas get "$SCHEMA" diff --git a/acceptance/bundle/resources/schemas/create_504_foreign/test.toml b/acceptance/bundle/resources/schemas/create_504_foreign/test.toml new file mode 100644 index 00000000000..beb4bcc3fb6 --- /dev/null +++ b/acceptance/bundle/resources/schemas/create_504_foreign/test.toml @@ -0,0 +1,10 @@ +Badness = "After a create request fails with a 504, deploy looks the schema up by name and takes a schema that the deploying user created less than a minute before the request. That does not tell the bundle's own schema from one the same user created another way: another bundle or target, a script, or the same service principal in another CI job. Here the 504 was returned before the backend handled the request, so the bundle created nothing; without the 504 the same deploy fails with 'already exists'. Destroy then deletes the schema. Deploy should take a schema only when it can tell that its own request created it, and otherwise fail as it does without the 504." + +# Faults are injected through the testserver. +Cloud = false +EnvMatrix.READPLAN = [] +Env.DATABRICKS_BUNDLE_ENGINE = "direct" +Env.DATABRICKS_BUNDLE_RETRY_INTERVAL_MS = "100" +SuppressLines.warn_retry = "" + +Ignore = ["databricks.yml"] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/databricks.yml.tmpl b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/databricks.yml.tmpl new file mode 100644 index 00000000000..6ae84a02d69 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: vs-endpoint-503-replayed-$UNIQUE_NAME + +sync: + paths: [] + +resources: + vector_search_endpoints: + my_endpoint: + name: vs-endpoint-$UNIQUE_NAME + endpoint_type: STANDARD diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/out.test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/out.test.toml new file mode 100644 index 00000000000..19b5b15d11f --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/output.txt b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/output.txt new file mode 100644 index 00000000000..36737c41bf2 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/output.txt @@ -0,0 +1,42 @@ + +=== The create request is applied but answered with a 503: the SDK repeats it, and the repeat fails because the endpoint exists + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-503-replayed-[UNIQUE_NAME]/default/files... +Error: cannot create resources.vector_search_endpoints.my_endpoint: AI Search endpoint vs-endpoint-[UNIQUE_NAME] already exists. Please try again with a different endpoint name. (409 ALREADY_EXISTS) + +Endpoint: POST [DATABRICKS_URL]/api/2.0/vector-search/endpoints +HTTP Status: 409 Conflict +API error_code: ALREADY_EXISTS +API message: AI Search endpoint vs-endpoint-[UNIQUE_NAME] already exists. Please try again with a different endpoint name. + +Files: 0 uploaded, 0 deleted + +>>> print_requests.py --get --summary //vector-search/endpoints +POST /api/2.0/vector-search/endpoints +POST /api/2.0/vector-search/endpoints + +=== The endpoint exists, but it is not in the bundle's state + +>>> [CLI] vector-search-endpoints get-endpoint vs-endpoint-[UNIQUE_NAME] +{ + "name": "vs-endpoint-[UNIQUE_NAME]" +} + +>>> [CLI] bundle plan +create vector_search_endpoints.my_endpoint + +Plan: 1 to add, 0 to change, 0 to delete, 0 unchanged + +=== The next deploy fails the same way + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-503-replayed-[UNIQUE_NAME]/default/files... +Error: cannot create resources.vector_search_endpoints.my_endpoint: AI Search endpoint vs-endpoint-[UNIQUE_NAME] already exists. Please try again with a different endpoint name. (409 ALREADY_EXISTS) + +Endpoint: POST [DATABRICKS_URL]/api/2.0/vector-search/endpoints +HTTP Status: 409 Conflict +API error_code: ALREADY_EXISTS +API message: AI Search endpoint vs-endpoint-[UNIQUE_NAME] already exists. Please try again with a different endpoint name. + +Files: 0 uploaded, 0 deleted diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/script b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/script new file mode 100644 index 00000000000..617bac397bf --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/script @@ -0,0 +1,24 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +ENDPOINT="vs-endpoint-$UNIQUE_NAME" + +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI vector-search-endpoints delete-endpoint "$ENDPOINT" >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +# The SDK repeats a request that is answered with a 503 on its own, so deploy never sees the 503. +title "The create request is applied but answered with a 503: the SDK repeats it, and the repeat fails because the endpoint exists" +fault.py --after-handler "POST /api/2.0/vector-search/endpoints" 503 0 1 +trace musterr $CLI bundle deploy +trace print_requests.py --get --summary //vector-search/endpoints + +title "The endpoint exists, but it is not in the bundle's state" +trace $CLI vector-search-endpoints get-endpoint "$ENDPOINT" | jq '{name}' +trace $CLI bundle plan + +title "The next deploy fails the same way" +trace musterr $CLI bundle deploy diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/test.toml new file mode 100644 index 00000000000..66370939a1b --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-503-replayed/test.toml @@ -0,0 +1,4 @@ +Badness = "A create request that the backend applied but answered with a 503 is repeated by the SDK. The repeat fails with 'already exists', and deploy returns that error without looking the endpoint up: it only does that when the error it sees itself leaves the outcome unknown, as a 504 does (see create-504). The endpoint the bundle created is left outside its state, and every later deploy fails with 'already exists' until the endpoint is deleted or bound by hand. Deploy should end up with the endpoint in its state, as it does after a 504." + +# Faults are injected through the testserver. +Cloud = false diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/databricks.yml.tmpl b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/databricks.yml.tmpl new file mode 100644 index 00000000000..444ce7d5f9b --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: vs-endpoint-504-foreign-during-$UNIQUE_NAME + +sync: + paths: [] + +resources: + vector_search_endpoints: + my_endpoint: + name: vs-endpoint-$UNIQUE_NAME + endpoint_type: STANDARD diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/out.test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/out.test.toml new file mode 100644 index 00000000000..19b5b15d11f --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/output.txt b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/output.txt new file mode 100644 index 00000000000..0ee77d67bfc --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/output.txt @@ -0,0 +1,33 @@ + +=== The bundle's create request fails with a 504 that the backend did not apply. Before deploy repeats it, an endpoint with the name the bundle uses is created outside the bundle: deploy takes it + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-during-[UNIQUE_NAME]/default/files... +Warn: deploying resources.vector_search_endpoints.my_endpoint: retrying after 504 Gateway Timeout from POST /api/2.0/vector-search/endpoints +Created vector_search_endpoints.my_endpoint +Files: 0 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --get --summary //vector-search/endpoints +POST /api/2.0/vector-search/endpoints +GET /api/2.0/vector-search/endpoints/vs-endpoint-[UNIQUE_NAME] +POST /api/2.0/vector-search/endpoints +POST /api/2.0/vector-search/endpoints +GET /api/2.0/vector-search/endpoints/vs-endpoint-[UNIQUE_NAME] +GET /api/2.0/vector-search/endpoints/vs-endpoint-[UNIQUE_NAME] + +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged + +=== Destroy deletes the endpoint the bundle did not create + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.vector_search_endpoints.my_endpoint + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-during-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> musterr [CLI] vector-search-endpoints get-endpoint vs-endpoint-[UNIQUE_NAME] +Error: Resource vectorsearch.EndpointInfo not found: vs-endpoint-[UNIQUE_NAME] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/script b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/script new file mode 100644 index 00000000000..12a02805eba --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/script @@ -0,0 +1,28 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +ENDPOINT="vs-endpoint-$UNIQUE_NAME" + +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI vector-search-endpoints delete-endpoint "$ENDPOINT" >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +# The testserver sends the outside create itself: when deploy's lookup arrives, after it finds no +# endpoint and before the lookup is answered. So the endpoint appears between the failed request +# and its repeat, whatever the speed of the machine. +title "The bundle's create request fails with a 504 that the backend did not apply. Before deploy repeats it, an endpoint with the name the bundle uses is created outside the bundle: deploy takes it" +fault.py "POST /api/2.0/vector-search/endpoints" 504 0 1 TEMPORARILY_UNAVAILABLE +hook.py "GET /api/2.0/vector-search/endpoints/$ENDPOINT" 0 1 "POST /api/2.0/vector-search/endpoints" "{\"name\": \"$ENDPOINT\", \"endpoint_type\": \"STANDARD\"}" +trace $CLI bundle deploy + +# The bundle's failed create, its lookup that finds nothing, the outside create, the bundle's +# repeat that is told the endpoint exists, and the lookups that find the endpoint. +trace print_requests.py --get --summary //vector-search/endpoints +trace $CLI bundle plan + +title "Destroy deletes the endpoint the bundle did not create" +trace $CLI bundle destroy --auto-approve +trace musterr $CLI vector-search-endpoints get-endpoint "$ENDPOINT" diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/test.toml new file mode 100644 index 00000000000..3b48c6441fb --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-during/test.toml @@ -0,0 +1,7 @@ +Badness = "After a create request fails with a 504, deploy looks the endpoint up by name, and repeats the request while the endpoint is missing. Here the endpoint is created outside the bundle between the failed request and the repeat. The repeat fails with 'already exists', the next lookup finds the endpoint, and deploy takes it: it was created after the first request, and by the deploying user. The bundle created nothing. Destroy then deletes the endpoint. From the API's answers deploy cannot tell this from its own first request being applied late, which is what the lookup after 'already exists' is for. Telling them apart needs something the create request carries and the read response returns, such as an idempotency token." + +# Faults are injected through the testserver. +Cloud = false + +Env.DATABRICKS_BUNDLE_RETRY_INTERVAL_MS = "100" +SuppressLines.warn_retry = "" diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/databricks.yml.tmpl b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/databricks.yml.tmpl new file mode 100644 index 00000000000..823854b1d13 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: vs-endpoint-504-foreign-earlier-$UNIQUE_NAME + +sync: + paths: [] + +resources: + vector_search_endpoints: + my_endpoint: + name: vs-endpoint-$UNIQUE_NAME + endpoint_type: STANDARD diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/out.test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/out.test.toml new file mode 100644 index 00000000000..19b5b15d11f --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/output.txt b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/output.txt new file mode 100644 index 00000000000..1ea75450ee2 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/output.txt @@ -0,0 +1,11 @@ + +=== The bundle's create request fails with a 504 that the backend did not apply. An endpoint with the name the bundle uses was created outside the bundle 30 seconds before the request: deploy takes it + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-earlier-[UNIQUE_NAME]/default/files... +Created vector_search_endpoints.my_endpoint +Files: 0 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/script b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/script new file mode 100644 index 00000000000..bf0d9619e0a --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/script @@ -0,0 +1,20 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +ENDPOINT="vs-endpoint-$UNIQUE_NAME" + +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI vector-search-endpoints delete-endpoint "$ENDPOINT" >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +# The testserver creates the endpoint when the bundle's create request arrives, with a create time +# 30 seconds before. So the endpoint is 30 seconds older than the request, whatever the speed of +# the machine. +title "The bundle's create request fails with a 504 that the backend did not apply. An endpoint with the name the bundle uses was created outside the bundle 30 seconds before the request: deploy takes it" +fault.py "POST /api/2.0/vector-search/endpoints" 504 0 1 TEMPORARILY_UNAVAILABLE +hook.py --clock-offset-ms -30000 "POST /api/2.0/vector-search/endpoints" 0 1 "POST /api/2.0/vector-search/endpoints" "{\"name\": \"$ENDPOINT\", \"endpoint_type\": \"STANDARD\"}" +errcode trace $CLI bundle deploy +trace $CLI bundle plan diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/test.toml new file mode 100644 index 00000000000..bd503a0208a --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-earlier/test.toml @@ -0,0 +1,7 @@ +Badness = "After a create request fails with a 504, deploy looks the endpoint up by name and takes one created up to a minute before the request. Here the endpoint was created outside the bundle 30 seconds before the bundle's create request, so that request cannot have created it. Deploy should fail as it does without the 504." + +# Faults are injected through the testserver. +Cloud = false + +Env.DATABRICKS_BUNDLE_RETRY_INTERVAL_MS = "100" +SuppressLines.warn_retry = "" diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/databricks.yml.tmpl b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/databricks.yml.tmpl new file mode 100644 index 00000000000..a7f82350f38 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: vs-endpoint-504-foreign-type-$UNIQUE_NAME + +sync: + paths: [] + +resources: + vector_search_endpoints: + my_endpoint: + name: vs-endpoint-$UNIQUE_NAME + endpoint_type: STANDARD diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/out.test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/out.test.toml new file mode 100644 index 00000000000..19b5b15d11f --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/output.txt b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/output.txt new file mode 100644 index 00000000000..9afde028381 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/output.txt @@ -0,0 +1,23 @@ + +=== Outside the bundle, create an endpoint with the name the bundle uses, but of another endpoint_type + +>>> [CLI] vector-search-endpoints create-endpoint vs-endpoint-[UNIQUE_NAME] STORAGE_OPTIMIZED --no-wait +{ + "name": "vs-endpoint-[UNIQUE_NAME]", + "endpoint_type": "STORAGE_OPTIMIZED" +} + +=== The bundle's create request fails with a 504 that the backend did not apply: deploy takes the endpoint + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-type-[UNIQUE_NAME]/default/files... +Created vector_search_endpoints.my_endpoint +Files: 0 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +=== The next deploy would delete the endpoint and create one of the bundle's type + +>>> [CLI] bundle plan +recreate vector_search_endpoints.my_endpoint + +Plan: 1 to add, 0 to change, 1 to delete, 0 unchanged diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/script b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/script new file mode 100644 index 00000000000..cf2d4c1ca8e --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/script @@ -0,0 +1,21 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +ENDPOINT="vs-endpoint-$UNIQUE_NAME" + +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI vector-search-endpoints delete-endpoint "$ENDPOINT" >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +title "Outside the bundle, create an endpoint with the name the bundle uses, but of another endpoint_type" +trace $CLI vector-search-endpoints create-endpoint "$ENDPOINT" STORAGE_OPTIMIZED --no-wait | jq '{name, endpoint_type}' + +title "The bundle's create request fails with a 504 that the backend did not apply: deploy takes the endpoint" +fault.py "POST /api/2.0/vector-search/endpoints" 504 0 1 TEMPORARILY_UNAVAILABLE +trace $CLI bundle deploy + +title "The next deploy would delete the endpoint and create one of the bundle's type" +trace $CLI bundle plan diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/test.toml new file mode 100644 index 00000000000..2ac2c0bdf7b --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign-type/test.toml @@ -0,0 +1,7 @@ +Badness = "After a create request fails with a 504, deploy looks the endpoint up by name and takes one created less than a minute before the request without comparing it with the request. Here the endpoint was created outside the bundle with another endpoint_type. An endpoint the bundle's request created has the requested type, so this one cannot be the bundle's. The next plan is a recreate, so the next deploy deletes it. Deploy should fail as it does without the 504." + +# Faults are injected through the testserver. +Cloud = false + +Env.DATABRICKS_BUNDLE_RETRY_INTERVAL_MS = "100" +SuppressLines.warn_retry = "" diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/databricks.yml.tmpl b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/databricks.yml.tmpl new file mode 100644 index 00000000000..ae1c4165f2a --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: vs-endpoint-504-foreign-$UNIQUE_NAME + +sync: + paths: [] + +resources: + vector_search_endpoints: + my_endpoint: + name: vs-endpoint-$UNIQUE_NAME + endpoint_type: STANDARD diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/out.test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/out.test.toml new file mode 100644 index 00000000000..19b5b15d11f --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/output.txt b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/output.txt new file mode 100644 index 00000000000..3539e2b9a56 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/output.txt @@ -0,0 +1,53 @@ + +=== Outside the bundle, create an endpoint with the name the bundle uses + +>>> [CLI] vector-search-endpoints create-endpoint vs-endpoint-[UNIQUE_NAME] STANDARD --no-wait +{ + "name": "vs-endpoint-[UNIQUE_NAME]", + "endpoint_type": "STANDARD" +} + +=== Deploy fails: the name is taken + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-[UNIQUE_NAME]/default/files... +Error: cannot create resources.vector_search_endpoints.my_endpoint: AI Search endpoint vs-endpoint-[UNIQUE_NAME] already exists. Please try again with a different endpoint name. (409 ALREADY_EXISTS) + +Endpoint: POST [DATABRICKS_URL]/api/2.0/vector-search/endpoints +HTTP Status: 409 Conflict +API error_code: ALREADY_EXISTS +API message: AI Search endpoint vs-endpoint-[UNIQUE_NAME] already exists. Please try again with a different endpoint name. + +Files: 0 uploaded, 0 deleted + +=== The same deploy, but its create request fails with a 504 that the backend did not apply: deploy takes the endpoint + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-[UNIQUE_NAME]/default/files... +Created vector_search_endpoints.my_endpoint +Files: 0 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --get --summary //vector-search/endpoints +POST /api/2.0/vector-search/endpoints +GET /api/2.0/vector-search/endpoints/vs-endpoint-[UNIQUE_NAME] +GET /api/2.0/vector-search/endpoints/vs-endpoint-[UNIQUE_NAME] + +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged + +=== Destroy deletes the endpoint the bundle did not create + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.vector_search_endpoints.my_endpoint + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/vs-endpoint-504-foreign-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> print_requests.py --summary //vector-search/endpoints +DELETE /api/2.0/vector-search/endpoints/vs-endpoint-[UNIQUE_NAME] + +>>> musterr [CLI] vector-search-endpoints get-endpoint vs-endpoint-[UNIQUE_NAME] +Error: Resource vectorsearch.EndpointInfo not found: vs-endpoint-[UNIQUE_NAME] diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/script b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/script new file mode 100644 index 00000000000..88be3efc087 --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/script @@ -0,0 +1,29 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +ENDPOINT="vs-endpoint-$UNIQUE_NAME" + +cleanup() { + # Whatever destroy left behind. + errcode $CLI bundle destroy --auto-approve > LOG.cleanup 2>&1 + errcode $CLI vector-search-endpoints delete-endpoint "$ENDPOINT" >> LOG.cleanup 2>&1 + rm -f "$OUT_REQUESTS" +} +trap cleanup EXIT + +title "Outside the bundle, create an endpoint with the name the bundle uses" +trace $CLI vector-search-endpoints create-endpoint "$ENDPOINT" STANDARD --no-wait | jq '{name, endpoint_type}' + +title "Deploy fails: the name is taken" +trace musterr $CLI bundle deploy +rm -f "$OUT_REQUESTS" + +title "The same deploy, but its create request fails with a 504 that the backend did not apply: deploy takes the endpoint" +fault.py "POST /api/2.0/vector-search/endpoints" 504 0 1 TEMPORARILY_UNAVAILABLE +trace $CLI bundle deploy +trace print_requests.py --get --summary //vector-search/endpoints +trace $CLI bundle plan + +title "Destroy deletes the endpoint the bundle did not create" +trace $CLI bundle destroy --auto-approve +trace print_requests.py --summary //vector-search/endpoints +trace musterr $CLI vector-search-endpoints get-endpoint "$ENDPOINT" diff --git a/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/test.toml b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/test.toml new file mode 100644 index 00000000000..d730cb105ac --- /dev/null +++ b/acceptance/bundle/resources/vector_search_endpoints/create-504-foreign/test.toml @@ -0,0 +1,7 @@ +Badness = "After a create request fails with a 504, deploy looks the endpoint up by name and takes any endpoint created less than a minute before the request, without knowing who created it. Here the endpoint was created outside the bundle, and the 504 was returned before the backend handled the request, so the bundle created nothing; without the 504 the same deploy fails with 'already exists'. Destroy then deletes the endpoint. Deploy should take an endpoint only when it can tell that its own request created it, and otherwise fail as it does without the 504." + +# Faults are injected through the testserver. +Cloud = false + +Env.DATABRICKS_BUNDLE_RETRY_INTERVAL_MS = "100" +SuppressLines.warn_retry = "" diff --git a/libs/testserver/fake_workspace.go b/libs/testserver/fake_workspace.go index 2f26de954c8..fe9e2a14863 100644 --- a/libs/testserver/fake_workspace.go +++ b/libs/testserver/fake_workspace.go @@ -149,6 +149,18 @@ func nowMilli() int64 { return lastNowMilli } +// nowMilli is nowMilli for a handler that stamps a resource with the time of this request. A +// request sent by a hook can shift it, so that a test gets e.g. a resource that was created 30 +// seconds ago without waiting for 30 seconds. Handlers that call the package-level nowMilli +// ignore the shift. +func (r Request) nowMilli() int64 { + if r.Context == nil { + return nowMilli() + } + offset, _ := r.Context.Value(clockOffsetKey{}).(int64) + return nowMilli() + offset +} + // nextTimestamp returns a strictly-increasing RFC3339 timestamp with nanosecond // precision. The sub-second component keeps distinct events ordered even within the // same wall-clock second, which the dashboard publish lifecycle relies on to compare diff --git a/libs/testserver/fault.go b/libs/testserver/fault.go index 2ee2e83dbd2..6dd836e2a96 100644 --- a/libs/testserver/fault.go +++ b/libs/testserver/fault.go @@ -51,7 +51,9 @@ func (fr *FaultRules) SetAfterHandler(token, pattern string, statusCode int, bod fr.set(token, pattern, statusCode, body, offset, times, true, bodyContains) } -func (fr *FaultRules) set(token, pattern string, statusCode int, body string, offset, times int, afterHandler bool, bodyContains string) { +// compileRequestPattern turns a "METHOD /path" pattern, in which "*" matches within a path segment +// and "**" across path segments, into a matcher for the whole request. +func compileRequestPattern(pattern string) *regexp.Regexp { // Escape regex characters so the pattern starts as literal text. escapedPattern := regexp.QuoteMeta(pattern) @@ -62,7 +64,11 @@ func (fr *FaultRules) set(token, pattern string, statusCode int, body string, of ) // Anchor both ends to match the whole request. - matcher := regexp.MustCompile("^" + wildcards.Replace(escapedPattern) + "$") + return regexp.MustCompile("^" + wildcards.Replace(escapedPattern) + "$") +} + +func (fr *FaultRules) set(token, pattern string, statusCode int, body string, offset, times int, afterHandler bool, bodyContains string) { + matcher := compileRequestPattern(pattern) fr.mu.Lock() defer fr.mu.Unlock() diff --git a/libs/testserver/hook.go b/libs/testserver/hook.go new file mode 100644 index 00000000000..0514a4cfca3 --- /dev/null +++ b/libs/testserver/hook.go @@ -0,0 +1,119 @@ +package testserver + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync" +) + +// hookRule makes the server send a request of its own when a request that matches pattern +// arrives. The request stands for another client that acts at a known point of the test's request +// sequence, e.g. one that creates a resource between a failed create request and its repeat. A +// script can only approximate that with sleeps and background processes. +type hookRule struct { + pattern *regexp.Regexp + offset int + times int + + // The request to send, with the token of the request that matched. + method string + path string + body string + // clockOffsetMs shifts the time the handler of this request sees; see Request.nowMilli. + clockOffsetMs int64 +} + +type hookRules struct { + mu sync.Mutex + rules map[faultRuleKey]*hookRule +} + +func newHookRules() *hookRules { + return &hookRules{rules: make(map[faultRuleKey]*hookRule)} +} + +func (hr *hookRules) set(token, pattern string, rule hookRule) { + rule.pattern = compileRequestPattern(pattern) + hr.mu.Lock() + defer hr.mu.Unlock() + hr.rules[faultRuleKey{token: token, pattern: pattern}] = &rule +} + +// check returns the hook to run for this request and advances its counters, or nil. offset and +// times count as they do for a fault rule. +func (hr *hookRules) check(method, path, token string) *hookRule { + requestPattern := method + " " + path + + hr.mu.Lock() + defer hr.mu.Unlock() + + for key, rule := range hr.rules { + if key.token != token || !rule.pattern.MatchString(requestPattern) { + continue + } + if rule.offset > 0 { + rule.offset-- + return nil + } + rule.times-- + if rule.times <= 0 { + delete(hr.rules, key) + } + result := *rule + return &result + } + return nil +} + +type clockOffsetKey struct{} + +// sendHookRequest handles the hook's request as if a client had sent it with the given token: it +// is recorded and subject to fault and hook rules like any other request. A hook whose request +// matches its own pattern therefore runs again inside that request while it has times left. Its +// counters were advanced before the request was sent, so it stops when they are used up. +func (s *Server) sendHookRequest(ctx context.Context, token string, hook *hookRule) { + ctx = context.WithValue(ctx, clockOffsetKey{}, hook.clockOffsetMs) + req := httptest.NewRequestWithContext(ctx, hook.method, hook.path, strings.NewReader(hook.body)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + s.ServeHTTP(rec, req) + if rec.Code >= http.StatusBadRequest { + s.t.Errorf("hook request %s %s failed: %d %s", hook.method, hook.path, rec.Code, rec.Body.String()) + } +} + +// hookEndpointHandler handles POST /__testserver/hook. +func hookEndpointHandler(hr *hookRules) HandlerFunc { + return func(req Request) any { + var body struct { + Pattern string `json:"pattern"` + Offset int `json:"offset"` + Times int `json:"times"` + Method string `json:"method"` + Path string `json:"path"` + Body string `json:"body"` + ClockOffsetMs int64 `json:"clock_offset_ms"` + } + if err := json.Unmarshal(req.Body, &body); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"error": err.Error()}} + } + if body.Method == "" || !strings.HasPrefix(body.Path, "/") || body.Times <= 0 { + return Response{StatusCode: 400, Body: map[string]string{"error": "a hook needs a method, a path that starts with / and times above 0"}} + } + hr.set(req.Token, body.Pattern, hookRule{ + pattern: nil, + offset: body.Offset, + times: body.Times, + method: body.Method, + path: body.Path, + body: body.Body, + clockOffsetMs: body.ClockOffsetMs, + }) + return Response{StatusCode: 200} + } +} diff --git a/libs/testserver/hook_test.go b/libs/testserver/hook_test.go new file mode 100644 index 00000000000..af63efa1610 --- /dev/null +++ b/libs/testserver/hook_test.go @@ -0,0 +1,140 @@ +package testserver_test + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "testing" + + "github.com/databricks/cli/libs/testserver" + "github.com/databricks/databricks-sdk-go/service/vectorsearch" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const hookTestToken = "dbapi-hook-test" + +// sendTestRequest sends a request with hookTestToken and returns the status and body of the response. +func sendTestRequest(t *testing.T, server *testserver.Server, method, path string, body any) (int, []byte) { + t.Helper() + encoded, err := json.Marshal(body) + require.NoError(t, err) + req, err := http.NewRequest(method, server.URL+path, bytes.NewReader(encoded)) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+hookTestToken) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + require.NoError(t, err) + return resp.StatusCode, respBody +} + +func TestServerHookSendsItsRequestBeforeTheMatchingRequestIsAnswered(t *testing.T) { + var events []string + server := testserver.New(t) + server.Handle("GET", "/things/{name}", func(req testserver.Request) any { + events = append(events, "GET "+req.Vars["name"]) + return testserver.Response{StatusCode: 404, Body: map[string]string{"message": "not found"}} + }) + server.Handle("POST", "/things", func(req testserver.Request) any { + events = append(events, "POST "+string(req.Body)+" as "+req.Token) + return map[string]string{"status": "created"} + }) + + status, _ := sendTestRequest(t, server, "POST", "/__testserver/hook", map[string]any{ + "pattern": "GET /things/*", + "offset": 1, + "times": 1, + "method": "POST", + "path": "/things", + "body": "x", + }) + require.Equal(t, 200, status) + + // The offset lets the first matching request through. + status, _ = sendTestRequest(t, server, "GET", "/things/a", nil) + assert.Equal(t, 404, status) + assert.Equal(t, []string{"GET a"}, events) + + // The hook's request is handled after the handler of the matching request and before its + // response, with the same token; the matching request keeps its own response. + status, _ = sendTestRequest(t, server, "GET", "/things/b", nil) + assert.Equal(t, 404, status) + assert.Equal(t, []string{"GET a", "GET b", "POST x as " + hookTestToken}, events) + + // times is used up. + sendTestRequest(t, server, "GET", "/things/c", nil) + assert.Equal(t, []string{"GET a", "GET b", "POST x as " + hookTestToken, "GET c"}, events) +} + +// A hook whose request matches its own pattern runs as many times as it was given, each run +// inside the request of the one before, and then stops. +func TestServerHookRunsItsTimesWhenItsRequestMatchesItsOwnPattern(t *testing.T) { + for _, times := range []int{1, 2} { + calls := 0 + server := testserver.New(t) + server.Handle("POST", "/things", func(req testserver.Request) any { + calls++ + return map[string]string{"status": "created"} + }) + + status, _ := sendTestRequest(t, server, "POST", "/__testserver/hook", map[string]any{ + "pattern": "POST /things", + "times": times, + "method": "POST", + "path": "/things", + }) + require.Equal(t, 200, status) + + sendTestRequest(t, server, "POST", "/things", nil) + assert.Equal(t, 1+times, calls) + + sendTestRequest(t, server, "POST", "/things", nil) + assert.Equal(t, 2+times, calls) + } +} + +func TestServerHookRejectsARuleWithoutARequest(t *testing.T) { + server := testserver.New(t) + status, _ := sendTestRequest(t, server, "POST", "/__testserver/hook", map[string]any{"pattern": "GET /things", "times": 1}) + assert.Equal(t, 400, status) +} + +// The create times are compared with each other, not with the clock of the test: the testserver +// hands out strictly increasing times. +func TestServerHookShiftsTheTimeOfItsRequest(t *testing.T) { + const offsetMs = -30_000 + server := testserver.New(t) + testserver.AddDefaultHandlers(server) + + createEndpoint := func(name string) { + status, body := sendTestRequest(t, server, "POST", "/api/2.0/vector-search/endpoints", map[string]string{"name": name, "endpoint_type": "STANDARD"}) + require.Equal(t, 200, status, string(body)) + } + createdAt := func(name string) int64 { + status, body := sendTestRequest(t, server, "GET", "/api/2.0/vector-search/endpoints/"+name, nil) + require.Equal(t, 200, status, string(body)) + var info vectorsearch.EndpointInfo + require.NoError(t, json.Unmarshal(body, &info)) + return info.CreationTimestamp + } + + createEndpoint("before") + status, _ := sendTestRequest(t, server, "POST", "/__testserver/hook", map[string]any{ + "pattern": "GET /api/2.0/vector-search/endpoints/before", + "times": 1, + "method": "POST", + "path": "/api/2.0/vector-search/endpoints", + "body": `{"name": "shifted", "endpoint_type": "STANDARD"}`, + "clock_offset_ms": offsetMs, + }) + require.Equal(t, 200, status) + before := createdAt("before") + createEndpoint("after") + + shifted := createdAt("shifted") + assert.Greater(t, shifted, before+offsetMs) + assert.Less(t, shifted, createdAt("after")+offsetMs) +} diff --git a/libs/testserver/server.go b/libs/testserver/server.go index a1aeeac4f0f..12bc8278678 100644 --- a/libs/testserver/server.go +++ b/libs/testserver/server.go @@ -68,6 +68,7 @@ type Server struct { kills *killRules faults *FaultRules + hooks *hookRules sqlHandler *testsql.Handler @@ -250,6 +251,7 @@ func New(t testutil.TestingT) *Server { fakeOidc: &FakeOidc{url: server.URL}, kills: kills, faults: faults, + hooks: newHookRules(), sqlHandler: testsql.New(), } router.Dispatch = s.serve @@ -307,9 +309,10 @@ Response.Body = '' }) router.NotFound = notFoundFunc - // Register test-only endpoints for setting up kill and fault rules from scripts. + // Register test-only endpoints for setting up kill, fault and hook rules from scripts. s.Handle("POST", "/__testserver/kill", killEndpointHandler(s.kills)) s.Handle("POST", "/__testserver/fault", faultEndpointHandler(s.faults)) + s.Handle("POST", "/__testserver/hook", hookEndpointHandler(s.hooks)) // Register a default handler for the SDK's host metadata discovery endpoint. // The SDK resolves this during config initialization (as of v0.126.0) to @@ -398,6 +401,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, handler HandlerFu } } + // The request is handled, or failed by a fault, and not answered yet: what a hook sends now + // lands between this request and the client's next one. + if hook := s.hooks.check(r.Method, r.URL.Path, token); hook != nil { + s.sendHookRequest(r.Context(), token, hook) + } + maps.Copy(w.Header(), resp.Headers) w.WriteHeader(resp.StatusCode) diff --git a/libs/testserver/vector_search_endpoints.go b/libs/testserver/vector_search_endpoints.go index 453d64b3924..de370ad818a 100644 --- a/libs/testserver/vector_search_endpoints.go +++ b/libs/testserver/vector_search_endpoints.go @@ -30,7 +30,7 @@ func (s *FakeWorkspace) VectorSearchEndpointCreate(req Request) Response { BudgetPolicyId: createReq.BudgetPolicyId, EffectiveBudgetPolicyId: createReq.BudgetPolicyId, Creator: s.CurrentUser().UserName, - CreationTimestamp: nowMilli(), + CreationTimestamp: req.nowMilli(), EndpointType: createReq.EndpointType, Id: nextUUID(), LastUpdatedUser: s.CurrentUser().UserName,