Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"vectorBucketName":"embeddings-prod","indexName":"docs-v1","keys":["doc-1","doc-2"]}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Storage.Tests.Support;

namespace Storage.Tests.DeleteVectors;

/// <summary>
/// Pins the exact bytes <c>Vectors.From(...).Index(...).DeleteVectorsAsync</c> puts on the wire; the approved body must
/// match the service's <c>DeleteVectors</c> schema (<c>vectorBucketName</c>, <c>indexName</c> and <c>keys</c>, camelCase).
/// </summary>
[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");
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Contract tests for <c>Vectors.From(bucket).Index(name).DeleteVectorsAsync</c>: the request it sends to
/// <c>POST /vector/DeleteVectors</c> and how each service answer maps to the caller's result.
/// </summary>
[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<string, string> { { "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<string>());
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<SupabaseStorageException>(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<SupabaseStorageException>())
.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<SupabaseStorageException>())
.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<OperationCanceledException>("the token must reach the HTTP call");
}

[TestMethod]
public async Task DeleteVectorsAsync_ShouldSendDynamicHeaders_GivenGetHeadersOnTheClient()
{
this.Respond(200, string.Empty);
this.client.GetHeaders = () => new Dictionary<string, string> { { "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));
}
36 changes: 36 additions & 0 deletions packages/Storage/Storage.Tests/DeleteVectors/DeleteVectorsTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Unit tests for the checks <c>Vectors.From(bucket).Index(name).DeleteVectorsAsync</c> makes before it touches the wire.
/// </summary>
[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<ArgumentNullException>("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<HttpMessageHandler>();
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<ArgumentNullException>();
handler.ReceivedCalls().Should().BeEmpty("the argument check happens before any I/O");
}
}
133 changes: 133 additions & 0 deletions packages/Storage/Storage.Tests/DeleteVectors/VectorDeletionTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// End-to-end tests for <c>Vectors.From(bucket).Index(name).DeleteVectorsAsync</c> 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.
/// </summary>
[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<SupabaseStorageException>("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<string>()))
.Should().ThrowAsync<SupabaseStorageException>("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<IReadOnlyList<string>> 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<string> 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<Task> teardown)
{
try
{
await teardown();
}
catch (SupabaseStorageException)
{
}
}
}
23 changes: 23 additions & 0 deletions packages/Storage/Storage/DeleteVectors/DeleteVectorsBody.cs
Original file line number Diff line number Diff line change
@@ -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<string> 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<string> Keys { get; }
}
25 changes: 25 additions & 0 deletions packages/Storage/Storage/Interfaces/IVectorIndex.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Attributes;

namespace Supabase.Storage.Interfaces;

/// <summary>
/// Operations scoped to one vector index of one vector bucket, obtained from <see cref="IVectorBucket.Index"/>.
/// </summary>
public interface IVectorIndex
{
/// <summary>
/// Deletes the vectors stored under the given keys from this index. A key that matches no vector is
/// ignored. Requires a service-role key.
/// </summary>
/// <param name="keys">The keys of the vectors to delete. The service judges the batch size and each key.</param>
/// <param name="cancellationToken">Token used to cancel the request.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="keys"/> is null.</exception>
/// <exception cref="Exceptions.SupabaseStorageException">
/// The service refused the call, for example because the bucket or the index does not exist
/// (<c>Code</c> <c>NotFoundException</c>) or the keys are invalid, such as an empty batch, an empty key
/// or more keys than the service accepts at once (<c>Code</c> <c>InvalidRequest</c>).
/// </exception>
/// <example>
/// <code>
/// await storage.Vectors.From("embeddings-prod").Index("docs-v1")
/// .DeleteVectorsAsync(new[] { "doc-1", "doc-2" });
/// </code>
/// </example>
[ImplementedCapability("storage.vector_buckets.delete_vectors")]
Task DeleteVectorsAsync(IReadOnlyCollection<string> keys, CancellationToken cancellationToken = default);
}
1 change: 1 addition & 0 deletions packages/Storage/Storage/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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<string!>! keys, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort
Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort.<Clone>$() -> Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort!
Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSort.AnalyticsBucketSort(Supabase.Storage.ListAnalyticsBuckets.AnalyticsBucketSortColumn Column, System.ComponentModel.ListSortDirection Direction = System.ComponentModel.ListSortDirection.Ascending) -> void
Expand Down
2 changes: 1 addition & 1 deletion packages/Storage/Storage/VectorBucket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/// <inheritdoc />
Expand Down
Loading