From 2777b1f06a4f6d828e6a4a35a45c8fd8484cd79c Mon Sep 17 00:00:00 2001 From: tr00d Date: Wed, 25 Nov 2026 08:18:42 +0100 Subject: [PATCH] feat(storage): delete vectors by key from a vector index --- ...uldSerializeToExpectedPayload.verified.txt | 1 + .../DeleteVectorsApprovalTests.cs | 22 +++ .../DeleteVectorsContractTests.cs | 124 ++++++++++++++++ .../DeleteVectors/DeleteVectorsTests.cs | 36 +++++ .../DeleteVectors/VectorDeletionTests.cs | 133 ++++++++++++++++++ .../DeleteVectors/DeleteVectorsBody.cs | 23 +++ .../Storage/Interfaces/IVectorIndex.cs | 25 ++++ .../Storage/Storage/PublicAPI.Unshipped.txt | 1 + packages/Storage/Storage/VectorBucket.cs | 2 +- packages/Storage/Storage/VectorIndex.cs | 24 ++++ 10 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 packages/Storage/Storage.Tests/DeleteVectors/Data/DeleteVectorsApprovalTests.DeleteVectorsRequest_ShouldSerializeToExpectedPayload.verified.txt create mode 100644 packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsApprovalTests.cs create mode 100644 packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsContractTests.cs create mode 100644 packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsTests.cs create mode 100644 packages/Storage/Storage.Tests/DeleteVectors/VectorDeletionTests.cs create mode 100644 packages/Storage/Storage/DeleteVectors/DeleteVectorsBody.cs diff --git a/packages/Storage/Storage.Tests/DeleteVectors/Data/DeleteVectorsApprovalTests.DeleteVectorsRequest_ShouldSerializeToExpectedPayload.verified.txt b/packages/Storage/Storage.Tests/DeleteVectors/Data/DeleteVectorsApprovalTests.DeleteVectorsRequest_ShouldSerializeToExpectedPayload.verified.txt new file mode 100644 index 00000000..6c16ce66 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectors/Data/DeleteVectorsApprovalTests.DeleteVectorsRequest_ShouldSerializeToExpectedPayload.verified.txt @@ -0,0 +1 @@ +{"vectorBucketName":"embeddings-prod","indexName":"docs-v1","keys":["doc-1","doc-2"]} \ No newline at end of file diff --git a/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsApprovalTests.cs b/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsApprovalTests.cs new file mode 100644 index 00000000..f4deeb72 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsApprovalTests.cs @@ -0,0 +1,22 @@ +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Storage.Tests.Support; + +namespace Storage.Tests.DeleteVectors; + +/// +/// Pins the exact bytes Vectors.From(...).Index(...).DeleteVectorsAsync puts on the wire; the approved body must +/// match the service's DeleteVectors schema (vectorBucketName, indexName and keys, camelCase). +/// +[TestClass] +[TestCategory("Contract")] +public class DeleteVectorsApprovalTests : RequestApprovalFixture +{ + [TestMethod] + public async Task DeleteVectorsRequest_ShouldSerializeToExpectedPayload() + { + this.RespondWith(""); + await this.Client.Vectors.From("embeddings-prod").Index("docs-v1").DeleteVectorsAsync(new[] { "doc-1", "doc-2" }); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } +} diff --git a/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsContractTests.cs b/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsContractTests.cs new file mode 100644 index 00000000..24915893 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsContractTests.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage; +using Supabase.Storage.Exceptions; +using Supabase.Storage.Interfaces; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Server; + +namespace Storage.Tests.DeleteVectors; + +/// +/// Contract tests for Vectors.From(bucket).Index(name).DeleteVectorsAsync: the request it sends to +/// POST /vector/DeleteVectors and how each service answer maps to the caller's result. +/// +[TestClass] +[TestCategory("Contract")] +public class DeleteVectorsContractTests +{ + private const string Path = "/storage/v1/vector/DeleteVectors"; + private static readonly string[] Keys = { "doc-1", "doc-2" }; + private WireMockServer server = null!; + private Client client = null!; + + [TestInitialize] + public void TestInitialize() + { + this.server = WireMockServer.Start(); + this.client = new Client($"{this.server.Url}/storage/v1", new Dictionary { { "Authorization", "Bearer service-role-key" } }); + } + + [TestCleanup] + public void TestCleanup() => this.server.Stop(); + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldPostTheBucketIndexAndKeysToTheVectorRoute() + { + this.Respond(200, string.Empty); + await this.Index().DeleteVectorsAsync(Keys); + var request = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!; + using (new AssertionScope()) + { + request.Method.Should().Be("POST"); + request.Path.Should().Be(Path); + request.Body.Should().Be("{\"vectorBucketName\":\"embeddings-prod\",\"indexName\":\"docs-v1\",\"keys\":[\"doc-1\",\"doc-2\"]}"); + request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-role-key"); + } + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldLeaveTheJudgmentToTheService_GivenAnEmptyCollection() + { + this.Respond(200, string.Empty); + await this.Index().DeleteVectorsAsync(Array.Empty()); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Body.Should().Contain("\"keys\":[]", + "validation belongs to the service: https://github.com/supabase/sdk/blob/main/docs/principles.md#validation-belongs-to-the-service"); + } + + [TestMethod] + [DataRow(400, "InvalidRequest", "the service rejects an empty batch, an empty key or too many keys")] + [DataRow(404, "NotFoundException", "the bucket or the index does not exist")] + [DataRow(500, "InternalError", "the service failed internally")] + public async Task DeleteVectorsAsync_ShouldThrowStorageException_GivenAServiceError(int status, string code, string because) + { + this.Respond(status, $"{{\"statusCode\":\"{status}\",\"code\":\"{code}\",\"message\":\"refused\"}}"); + var thrown = await FluentActions.Awaiting(() => this.Index().DeleteVectorsAsync(Keys)) + .Should().ThrowAsync(because); + using (new AssertionScope()) + { + thrown.Which.StatusCode.Should().Be(status); + thrown.Which.Code.Should().Be(code); + } + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldClassifyAsNotAuthorized_GivenANonServiceRoleCaller() + { + this.Respond(403, "{\"statusCode\":\"403\",\"error\":\"Unauthorized\",\"message\":\"Invalid compact JWS\"}"); + (await FluentActions.Awaiting(() => this.Index().DeleteVectorsAsync(Keys)) + .Should().ThrowAsync()) + .Which.Reason.Should().Be(FailureHint.Reason.NotAuthorized); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldThrowStorageException_GivenTheVectorServiceIsNotEnabled() + { + this.Respond(404, "{\"statusCode\":\"404\",\"error\":\"Not Found\",\"message\":\"Route POST:/vector/DeleteVectors not found\"}"); + (await FluentActions.Awaiting(() => this.Index().DeleteVectorsAsync(Keys)) + .Should().ThrowAsync()) + .Which.StatusCode.Should().Be(404); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldCancel_GivenACanceledToken() + { + this.Respond(200, string.Empty); + using var source = new CancellationTokenSource(); + source.Cancel(); + await FluentActions.Awaiting(() => this.Index().DeleteVectorsAsync(Keys, source.Token)) + .Should().ThrowAsync("the token must reach the HTTP call"); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldSendDynamicHeaders_GivenGetHeadersOnTheClient() + { + this.Respond(200, string.Empty); + this.client.GetHeaders = () => new Dictionary { { "X-Dynamic", "fresh" } }; + await this.Index().DeleteVectorsAsync(Keys); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Headers!["X-Dynamic"] + .Should().ContainSingle().Which.Should().Be("fresh"); + } + + private IVectorIndex Index() => this.client.Vectors.From("embeddings-prod").Index("docs-v1"); + + private void Respond(int statusCode, string body) => + this.server.Given(Request.Create().WithPath(Path).UsingPost()) + .RespondWith(Response.Create().WithStatusCode(statusCode) + .WithHeader("Content-Type", "application/json").WithBody(body)); +} diff --git a/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsTests.cs b/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsTests.cs new file mode 100644 index 00000000..1ef0c161 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsTests.cs @@ -0,0 +1,36 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; +using Supabase.Storage; + +namespace Storage.Tests.DeleteVectors; + +/// +/// Unit tests for the checks Vectors.From(bucket).Index(name).DeleteVectorsAsync makes before it touches the wire. +/// +[TestClass] +[TestCategory("Unit")] +public class DeleteVectorsTests +{ + [TestMethod] + public async Task DeleteVectorsAsync_ShouldThrowArgumentNullException_GivenNullKeys() + { + var sut = new Client("http://localhost:1/storage/v1"); + (await FluentActions.Awaiting(() => sut.Vectors.From("embeddings-prod").Index("docs-v1").DeleteVectorsAsync(null!)) + .Should().ThrowAsync("a null collection breaks the method's contract and cannot become a request")) + .Which.ParamName.Should().Be("keys"); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldNotSendARequest_GivenNullKeys() + { + var handler = Substitute.For(); + var sut = new Client("http://localhost:1/storage/v1", new ClientOptions { HttpRequestClient = new HttpClient(handler) }); + await FluentActions.Awaiting(() => sut.Vectors.From("embeddings-prod").Index("docs-v1").DeleteVectorsAsync(null!)) + .Should().ThrowAsync(); + handler.ReceivedCalls().Should().BeEmpty("the argument check happens before any I/O"); + } +} diff --git a/packages/Storage/Storage.Tests/DeleteVectors/VectorDeletionTests.cs b/packages/Storage/Storage.Tests/DeleteVectors/VectorDeletionTests.cs new file mode 100644 index 00000000..3b6f69a8 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectors/VectorDeletionTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage; +using Supabase.Storage.CreateVectorIndex; +using Supabase.Storage.Exceptions; +using Supabase.Storage.Interfaces; + +namespace Storage.Tests.DeleteVectors; + +/// +/// End-to-end tests for Vectors.From(bucket).Index(name).DeleteVectorsAsync against the local stack's +/// vector service. Each test gets its own bucket and index, seeded and checked over plain HTTP because creating +/// a bucket and reading or writing vectors are not in the SDK yet, and torn down whatever the outcome. +/// +[TestClass] +[TestCategory("E2E")] +public class VectorDeletionTests +{ + private const string IndexName = "docs-v1"; + private static readonly string[] SeededKeys = { "doc-1", "doc-2", "doc-3" }; + private readonly Client storage = Helpers.GetServiceClient(); + private readonly HttpClient http = new(); + private readonly string bucketName = $"e2e-{Guid.NewGuid():N}"; + + [TestInitialize] + public async Task SeedIndex() + { + await this.PostToVectorService("CreateVectorBucket", new { vectorBucketName = this.bucketName }); + await this.storage.Vectors.From(this.bucketName).CreateIndexAsync(new NewVectorIndex + { + IndexName = IndexName, + Dimension = 2, + DistanceMetric = VectorDistanceMetric.Cosine, + }); + await this.PostToVectorService("PutVectors", new + { + vectorBucketName = this.bucketName, + indexName = IndexName, + vectors = SeededKeys.Select(key => new { key, data = new { float32 = new[] { 0.5f, 0.25f } } }), + }); + } + + [TestCleanup] + public async Task RemoveIndex() + { + await IgnoreRefusal(() => this.storage.Vectors.From(this.bucketName).DeleteIndexAsync(IndexName)); + await IgnoreRefusal(() => this.storage.Vectors.DeleteVectorBucketAsync(this.bucketName)); + this.http.Dispose(); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldRemoveOnlyTheVectorsUnderTheGivenKeys() + { + await this.Index().DeleteVectorsAsync(new[] { "doc-1", "doc-2" }); + (await this.StoredKeys()).Should().Equal(new[] { "doc-3" }, "only the named vectors are deleted"); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldIgnoreAKeyThatMatchesNoVector() + { + await this.Index().DeleteVectorsAsync(new[] { "missing" }); + (await this.StoredKeys()).Should().BeEquivalentTo(SeededKeys, "deleting an unknown key is a no-op for the service"); + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldThrowNotFound_GivenAMissingIndex() + { + var thrown = await FluentActions.Awaiting(() => this.storage.Vectors.From(this.bucketName).Index("missing-index").DeleteVectorsAsync(SeededKeys)) + .Should().ThrowAsync("the index does not exist"); + using (new AssertionScope()) + { + thrown.Which.StatusCode.Should().Be(404); + thrown.Which.Code.Should().Be("NotFoundException"); + } + } + + [TestMethod] + public async Task DeleteVectorsAsync_ShouldSurfaceTheServiceRejection_GivenAnEmptyCollection() + { + var thrown = await FluentActions.Awaiting(() => this.Index().DeleteVectorsAsync(Array.Empty())) + .Should().ThrowAsync("the service owns the batch-size rule and requires at least one key"); + using (new AssertionScope()) + { + thrown.Which.StatusCode.Should().Be(400); + thrown.Which.Code.Should().Be("InvalidRequest"); + } + } + + private IVectorIndex Index() => this.storage.Vectors.From(this.bucketName).Index(IndexName); + + private async Task> StoredKeys() + { + var body = await this.PostToVectorService("GetVectors", new { vectorBucketName = this.bucketName, indexName = IndexName, keys = SeededKeys }); + using var document = JsonDocument.Parse(body); + return document.RootElement.GetProperty("vectors").EnumerateArray() + .Select(vector => vector.GetProperty("key").GetString()!) + .OrderBy(key => key, StringComparer.Ordinal) + .ToList(); + } + + private async Task PostToVectorService(string operation, object body) + { + using var request = new HttpRequestMessage(HttpMethod.Post, $"{Helpers.StorageUrl}/vector/{operation}") + { + Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"), + }; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Helpers.ServiceKey); + using var response = await this.http.SendAsync(request); + var content = await response.Content.ReadAsStringAsync(); + response.IsSuccessStatusCode.Should().BeTrue($"seeding through {operation} must succeed: {content}"); + return content; + } + + private static async Task IgnoreRefusal(Func teardown) + { + try + { + await teardown(); + } + catch (SupabaseStorageException) + { + } + } +} diff --git a/packages/Storage/Storage/DeleteVectors/DeleteVectorsBody.cs b/packages/Storage/Storage/DeleteVectors/DeleteVectorsBody.cs new file mode 100644 index 00000000..0bd0b330 --- /dev/null +++ b/packages/Storage/Storage/DeleteVectors/DeleteVectorsBody.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Supabase.Storage.DeleteVectors; + +internal sealed class DeleteVectorsBody +{ + internal DeleteVectorsBody(string vectorBucketName, string indexName, IReadOnlyCollection keys) + { + this.VectorBucketName = vectorBucketName; + this.IndexName = indexName; + this.Keys = keys; + } + + [JsonPropertyName("vectorBucketName")] + public string VectorBucketName { get; } + + [JsonPropertyName("indexName")] + public string IndexName { get; } + + [JsonPropertyName("keys")] + public IReadOnlyCollection Keys { get; } +} diff --git a/packages/Storage/Storage/Interfaces/IVectorIndex.cs b/packages/Storage/Storage/Interfaces/IVectorIndex.cs index 05c9e40e..7deb11f4 100644 --- a/packages/Storage/Storage/Interfaces/IVectorIndex.cs +++ b/packages/Storage/Storage/Interfaces/IVectorIndex.cs @@ -1,3 +1,8 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Supabase.Core.Attributes; + namespace Supabase.Storage.Interfaces; /// @@ -5,4 +10,24 @@ namespace Supabase.Storage.Interfaces; /// public interface IVectorIndex { + /// + /// Deletes the vectors stored under the given keys from this index. A key that matches no vector is + /// ignored. Requires a service-role key. + /// + /// The keys of the vectors to delete. The service judges the batch size and each key. + /// Token used to cancel the request. + /// is null. + /// + /// The service refused the call, for example because the bucket or the index does not exist + /// (Code NotFoundException) or the keys are invalid, such as an empty batch, an empty key + /// or more keys than the service accepts at once (Code InvalidRequest). + /// + /// + /// + /// await storage.Vectors.From("embeddings-prod").Index("docs-v1") + /// .DeleteVectorsAsync(new[] { "doc-1", "doc-2" }); + /// + /// + [ImplementedCapability("storage.vector_buckets.delete_vectors")] + Task DeleteVectorsAsync(IReadOnlyCollection keys, CancellationToken cancellationToken = default); } diff --git a/packages/Storage/Storage/PublicAPI.Unshipped.txt b/packages/Storage/Storage/PublicAPI.Unshipped.txt index c787115e..03c864d7 100644 --- a/packages/Storage/Storage/PublicAPI.Unshipped.txt +++ b/packages/Storage/Storage/PublicAPI.Unshipped.txt @@ -69,6 +69,7 @@ Supabase.Storage.ClientOptions.TimeProvider.get -> System.TimeProvider! Supabase.Storage.ClientOptions.TimeProvider.set -> void Supabase.Storage.Interfaces.IVectorBucket.Index(string! indexName) -> Supabase.Storage.Interfaces.IVectorIndex! Supabase.Storage.Interfaces.IVectorIndex +Supabase.Storage.Interfaces.IVectorIndex.DeleteVectorsAsync(System.Collections.Generic.IReadOnlyCollection! keys, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort.$() -> Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort! Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort.AnalyticsBucketSort(Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSortColumn Column, System.ComponentModel.ListSortDirection Direction = System.ComponentModel.ListSortDirection.Ascending) -> void diff --git a/packages/Storage/Storage/VectorBucket.cs b/packages/Storage/Storage/VectorBucket.cs index d5a7a091..86bee138 100644 --- a/packages/Storage/Storage/VectorBucket.cs +++ b/packages/Storage/Storage/VectorBucket.cs @@ -23,7 +23,7 @@ internal VectorBucket(string vectorBucketName, VectorService service) public IVectorIndex Index(string indexName) { VectorService.RequireName(indexName, nameof(indexName)); - return new VectorIndex(); + return new VectorIndex(this.vectorBucketName, indexName, this.service); } /// diff --git a/packages/Storage/Storage/VectorIndex.cs b/packages/Storage/Storage/VectorIndex.cs index 368d66f8..9d14c7b7 100644 --- a/packages/Storage/Storage/VectorIndex.cs +++ b/packages/Storage/Storage/VectorIndex.cs @@ -1,7 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Supabase.Storage.Common; +using Supabase.Storage.DeleteVectors; using Supabase.Storage.Interfaces; namespace Supabase.Storage; internal sealed class VectorIndex : IVectorIndex { + private readonly string vectorBucketName; + private readonly string indexName; + private readonly VectorService service; + + internal VectorIndex(string vectorBucketName, string indexName, VectorService service) + { + this.vectorBucketName = vectorBucketName; + this.indexName = indexName; + this.service = service; + } + + /// + public Task DeleteVectorsAsync(IReadOnlyCollection keys, CancellationToken cancellationToken = default) + { + if (keys is null) + throw new ArgumentNullException(nameof(keys)); + return this.service.Post("DeleteVectors", new DeleteVectorsBody(this.vectorBucketName, this.indexName, keys), cancellationToken); + } }