Skip to content

Commit f7d116f

Browse files
committed
Pack canonical vector coordinates for exact ranking
Read exact coordinates as a span and preserve canonical row, revision, and source visibility at the same cut. Strict Debug build, 34 focused tests, 3 process-kill tests and compiled discovery passed. Matched 100k-vector A/B/B/A retained exact results and reduced CPU and allocation per query.
1 parent 2751fd8 commit f7d116f

21 files changed

Lines changed: 185 additions & 70 deletions

File tree

‎docs/Features/Search.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ The optional rerank hook is not part of the contract and no public candidate-win
131131

132132
## Authoritative vector profiles
133133

134+
Canonical vector rows store the full vector space and document revision with a
135+
length-prefixed little-endian IEEE 754 coordinate field in the generated Orleans
136+
record. Exact ranking uses those coordinates as a span inside the same authorized
137+
ZoneTree read cut. Derived vector effect validation and ANN seed ownership use
138+
the same row's values through the existing typed VectorRecord contract.
139+
134140
REQ-VECTOR-PROFILE-001: a collection may declare a bounded, server-persisted, immutable set of field vector profiles through the authenticated ConfigureResource command. Each typed `VectorFieldProfile` binds a canonical JSON-pointer Field to a full `VectorSpace(Id, Dimension, Metric, Model, Version)`. `ResourceDefinition` gains Id13 `VectorProfiles` (default empty), and `VectorFieldProfile` has stable alias and Id0 Field / Id1 Space. Empty profiles keep the unrestricted collection semantics; a configured field has an authoritative expected profile. AC-VECTOR-PROFILE-001: ConfigureResource persists the profile and same-ID replay is immutable; missing/duplicate/noncanonical fields, a null profile item, malformed identifiers, an invalid metric/dimension and more than 32 field profiles reject with exact Validation/ResourceExhausted and no resource effect. Profiles are collection-only and the policy-only ResourcePolicyUpdates fingerprint forbids profile mutation.
135141

136142
REQ-VECTOR-PROFILE-002: every canonical vector publication (direct PutVector and ApplyVectorProjection) compares the declared full profile with the configured field after fresh persisted operation/field/row authorization and the current target revision but before vector/lineage publication. Invalid coordinates/dimensions keep their Validation diagnostic; a well-shaped wrong profile yields Validation "The declared vector profile does not match the configured field." There is no embedding-model inference from numeric values, authorization keeps precedence and no profile metadata is disclosed. AC-VECTOR-PROFILE-002: a same-partition document+PutVector batch with the right dimension but wrong model returns exact Validation once, resets all document/vector/lineage/source effects, persists the failed receipt once and advances the position once; the repeated identical command returns the identical outcome bytes at a stable position while changed content under the same ID is Conflict; a fresh correct-model revision-2 batch commits atomically with literal document/sidecar/exact-search ranking and survives reopen; an unauthorized wrong-profile caller is denied without learning the profile.

‎docs/implementation/competitor-performance-review.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ KeyLoad's benchmark requests exact cosine results. Replacing this with approxima
5656

5757
Exact search now encodes the document and lineage key prefixes once per scan and appends each candidate ID using the canonical key encoder. In a local macOS Arm64 Debug A/B/B/A with 100,000 vectors, one client and 20 verified queries per arm, mean process CPU per query was 630 ms before and 471 ms after. Allocation remained about 160 MB per query. Both arms returned identical IDs, scores, revisions and JSON at the same read cut. The SDK and Orleans transport were outside this measurement. The local logs and DLL/PDB hashes are retained under the functional test binaries in `performance-investigation/orleans-request-20261103/document-point-ab-20261103/`.
5858

59+
Canonical vector records now store packed float coordinates in one generated byte field. Exact ranking reads the coordinate span while document revision, row visibility and source lineage checks use the captured read cut. A second local A/B/B/A with the same 100,000-vector oracle and one client reduced mean process CPU from 538 to 488 ms/query and allocation from 159.9 to 144.7 MB/query. The baseline and treatment produced identical IDs, scores, revisions and JSON and left the cut unchanged. These are embedded-engine measurements.
60+
5961
## pgvector: data layout and arithmetic are separate from request overhead
6062

6163
[vector.c](https://github.com/pgvector/pgvector/blob/v0.8.6/src/vector.c) computes exact distances over contiguous float arrays, using compiler-vectorized loops and target-specific compilation where supported. KeyLoad already has SIMD-backed `PreparedSimilarity`; the presence of SIMD alone is not the missing proof. The next vector profile must separate storage reads, record decoding, candidate selection, full sorting and metric arithmetic before changing kernels.

‎scripts/Features/CodeQuality/functional-coverage.unit-test-inventory.json‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40696,7 +40696,7 @@
4069640696
"methodName": "CutMatchesOnePersistedStoreReadAndUnchangedCaptureFingerprintIsStable",
4069740697
"instanceName": "CutMatchesOnePersistedStoreReadAndUnchangedCaptureFingerprintIsStable",
4069840698
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedCutTests.cs",
40699-
"sourceSha256": "8fdae2930b9d38d58af663d2305a133352e126c9a68ffb3f142850a10dad2bcd",
40699+
"sourceSha256": "18cee8c9f7d590176c3d30da255786e7f9147cb6874b19e95560fa25d1af4c32",
4070040700
"lineNumber": 12,
4070140701
"endLineNumber": 36,
4070240702
"classification": "functional",
@@ -40716,7 +40716,7 @@
4071640716
"methodName": "ReturnedRecordsUseOrdinalIdentityOrderIndependentOfStorageKeyOrder",
4071740717
"instanceName": "ReturnedRecordsUseOrdinalIdentityOrderIndependentOfStorageKeyOrder",
4071840718
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedCutTests.cs",
40719-
"sourceSha256": "8fdae2930b9d38d58af663d2305a133352e126c9a68ffb3f142850a10dad2bcd",
40719+
"sourceSha256": "18cee8c9f7d590176c3d30da255786e7f9147cb6874b19e95560fa25d1af4c32",
4072040720
"lineNumber": 60,
4072140721
"endLineNumber": 86,
4072240722
"classification": "functional",
@@ -40736,7 +40736,7 @@
4073640736
"methodName": "SameRevisionVectorBitChangeAdvancesCutAndChangesExactCorpusDigest",
4073740737
"instanceName": "SameRevisionVectorBitChangeAdvancesCutAndChangesExactCorpusDigest",
4073840738
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedCutTests.cs",
40739-
"sourceSha256": "8fdae2930b9d38d58af663d2305a133352e126c9a68ffb3f142850a10dad2bcd",
40739+
"sourceSha256": "18cee8c9f7d590176c3d30da255786e7f9147cb6874b19e95560fa25d1af4c32",
4074040740
"lineNumber": 38,
4074140741
"endLineNumber": 58,
4074240742
"classification": "functional",
@@ -41132,7 +41132,7 @@
4113241132
"methodName": "DuplicateRetainedDocumentIdentityFailsAsCorruption",
4113341133
"instanceName": "DuplicateRetainedDocumentIdentityFailsAsCorruption",
4113441134
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedMalformedStateTests.cs",
41135-
"sourceSha256": "e3c6c8d99eda1889c5bab1191005250f96c3c9bf1fc8920125d889477502b6ad",
41135+
"sourceSha256": "4de67ee94125b5414f1657d77f85d8ec19c53b6267fe7b30085be43672b64636",
4113641136
"lineNumber": 77,
4113741137
"endLineNumber": 96,
4113841138
"classification": "functional",
@@ -41158,7 +41158,7 @@
4115841158
"methodName": "InvalidAppliedScalarCutFailsAsCorruption",
4115941159
"instanceName": "InvalidAppliedScalarCutFailsAsCorruption",
4116041160
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedMalformedStateTests.cs",
41161-
"sourceSha256": "e3c6c8d99eda1889c5bab1191005250f96c3c9bf1fc8920125d889477502b6ad",
41161+
"sourceSha256": "4de67ee94125b5414f1657d77f85d8ec19c53b6267fe7b30085be43672b64636",
4116241162
"lineNumber": 98,
4116341163
"endLineNumber": 113,
4116441164
"classification": "functional",
@@ -41184,7 +41184,7 @@
4118441184
"methodName": "MalformedMatchingVectorFailsAsCorruptionWithoutFurtherWrites",
4118541185
"instanceName": "MalformedMatchingVectorFailsAsCorruptionWithoutFurtherWrites",
4118641186
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedMalformedStateTests.cs",
41187-
"sourceSha256": "e3c6c8d99eda1889c5bab1191005250f96c3c9bf1fc8920125d889477502b6ad",
41187+
"sourceSha256": "4de67ee94125b5414f1657d77f85d8ec19c53b6267fe7b30085be43672b64636",
4118841188
"lineNumber": 10,
4118941189
"endLineNumber": 26,
4119041190
"classification": "functional",
@@ -41210,7 +41210,7 @@
4121041210
"methodName": "MalformedPersistedPartitionIdentityFailsAsCorruption",
4121141211
"instanceName": "MalformedPersistedPartitionIdentityFailsAsCorruption",
4121241212
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedMalformedStateTests.cs",
41213-
"sourceSha256": "e3c6c8d99eda1889c5bab1191005250f96c3c9bf1fc8920125d889477502b6ad",
41213+
"sourceSha256": "4de67ee94125b5414f1657d77f85d8ec19c53b6267fe7b30085be43672b64636",
4121441214
"lineNumber": 28,
4121541215
"endLineNumber": 50,
4121641216
"classification": "functional",
@@ -41236,7 +41236,7 @@
4123641236
"methodName": "StructurallyValidPersistedPartitionMismatchFailsAsCorruption",
4123741237
"instanceName": "StructurallyValidPersistedPartitionMismatchFailsAsCorruption",
4123841238
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedMalformedStateTests.cs",
41239-
"sourceSha256": "e3c6c8d99eda1889c5bab1191005250f96c3c9bf1fc8920125d889477502b6ad",
41239+
"sourceSha256": "4de67ee94125b5414f1657d77f85d8ec19c53b6267fe7b30085be43672b64636",
4124041240
"lineNumber": 52,
4124141241
"endLineNumber": 75,
4124241242
"classification": "functional",
@@ -41262,7 +41262,7 @@
4126241262
"methodName": "WorkLimitExhaustionDuringMatchingRecordValidationRemainsBudgetExceeded",
4126341263
"instanceName": "WorkLimitExhaustionDuringMatchingRecordValidationRemainsBudgetExceeded",
4126441264
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/Ann/AnnSeed/AnnSeedMalformedStateTests.cs",
41265-
"sourceSha256": "e3c6c8d99eda1889c5bab1191005250f96c3c9bf1fc8920125d889477502b6ad",
41265+
"sourceSha256": "4de67ee94125b5414f1657d77f85d8ec19c53b6267fe7b30085be43672b64636",
4126641266
"lineNumber": 115,
4126741267
"endLineNumber": 141,
4126841268
"classification": "functional",
@@ -41972,9 +41972,9 @@
4197241972
"methodName": "ExactTopKMatchesLiteralMetricOrderAndCanceledReadPreservesEveryDocument",
4197341973
"instanceName": "ExactTopKMatchesLiteralMetricOrderAndCanceledReadPreservesEveryDocument(Cosine)",
4197441974
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/CanonicalVector/CanonicalVectorPublicMetricTests.cs",
41975-
"sourceSha256": "6e98eed2352f39de3dec832e64fe17b3c9ecdf6f83e3b207dda6f8e0acda1747",
41975+
"sourceSha256": "e871184d98b79e2f71feb817f081fe97c5a0cfcd36e8f2c490e9f2c22a630af8",
4197641976
"lineNumber": 14,
41977-
"endLineNumber": 74,
41977+
"endLineNumber": 75,
4197841978
"classification": "functional",
4197941979
"exclusionReason": null,
4198041980
"requirements": [
@@ -41993,9 +41993,9 @@
4199341993
"methodName": "ExactTopKMatchesLiteralMetricOrderAndCanceledReadPreservesEveryDocument",
4199441994
"instanceName": "ExactTopKMatchesLiteralMetricOrderAndCanceledReadPreservesEveryDocument(DotProduct)",
4199541995
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/CanonicalVector/CanonicalVectorPublicMetricTests.cs",
41996-
"sourceSha256": "6e98eed2352f39de3dec832e64fe17b3c9ecdf6f83e3b207dda6f8e0acda1747",
41996+
"sourceSha256": "e871184d98b79e2f71feb817f081fe97c5a0cfcd36e8f2c490e9f2c22a630af8",
4199741997
"lineNumber": 14,
41998-
"endLineNumber": 74,
41998+
"endLineNumber": 75,
4199941999
"classification": "functional",
4200042000
"exclusionReason": null,
4200142001
"requirements": [
@@ -42014,9 +42014,9 @@
4201442014
"methodName": "ExactTopKMatchesLiteralMetricOrderAndCanceledReadPreservesEveryDocument",
4201542015
"instanceName": "ExactTopKMatchesLiteralMetricOrderAndCanceledReadPreservesEveryDocument(Euclidean)",
4201642016
"sourcePath": "tests/KeyLoad.FunctionalTests/Search/Cases/CanonicalVector/CanonicalVectorPublicMetricTests.cs",
42017-
"sourceSha256": "6e98eed2352f39de3dec832e64fe17b3c9ecdf6f83e3b207dda6f8e0acda1747",
42017+
"sourceSha256": "e871184d98b79e2f71feb817f081fe97c5a0cfcd36e8f2c490e9f2c22a630af8",
4201842018
"lineNumber": 14,
42019-
"endLineNumber": 74,
42019+
"endLineNumber": 75,
4202042020
"classification": "functional",
4202142021
"exclusionReason": null,
4202242022
"requirements": [
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using System.Runtime.InteropServices;
2+
3+
namespace KeyLoad;
4+
5+
/// <summary>The canonical vector row, with length-prefixed little-endian IEEE 754 coordinates.</summary>
6+
[Orleans.GenerateSerializer]
7+
[Orleans.Alias(VectorStorageRecord.StorageAlias)]
8+
internal sealed record VectorStorageRecord(
9+
[property: Orleans.Id(0)] string DocumentId,
10+
[property: Orleans.Id(1)] string Field,
11+
[property: Orleans.Id(2)] VectorSpace Space,
12+
[property: Orleans.Id(3)] byte[] PackedCoordinates,
13+
[property: Orleans.Id(4)] long DocumentRevision)
14+
{
15+
private const string StorageAlias = "keyload.search.vector-storage-record";
16+
private const string InvalidCoordinates = "The stored vector coordinates are corrupt.";
17+
private const string LittleEndianRequired = "Packed vector storage requires a little-endian runtime.";
18+
19+
internal static byte[] Pack(ReadOnlySpan<float> values)
20+
{
21+
RequireLittleEndian();
22+
return MemoryMarshal.AsBytes(values).ToArray();
23+
}
24+
25+
internal ReadOnlySpan<float> Coordinates()
26+
{
27+
RequireLittleEndian();
28+
if (PackedCoordinates is null || PackedCoordinates.Length % sizeof(float) != 0)
29+
{
30+
throw Errors.Fail(ErrorCode.Corruption, InvalidCoordinates);
31+
}
32+
return MemoryMarshal.Cast<byte, float>((ReadOnlySpan<byte>)PackedCoordinates);
33+
}
34+
35+
internal VectorRecord Materialize() => new(DocumentId, Field, Space,
36+
ImmutableCollectionsMarshal.AsImmutableArray(Coordinates().ToArray()), DocumentRevision);
37+
38+
private static void RequireLittleEndian()
39+
{
40+
if (!BitConverter.IsLittleEndian)
41+
{
42+
throw new PlatformNotSupportedException(LittleEndianRequired);
43+
}
44+
}
45+
}

‎src/KeyLoad.Core/Search/Commands/VectorProjectionApply.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ internal static MutationReceipt ReuseProjectionEffect(IAtomicTransaction transac
9898

9999
internal static void PutCanonicalVector(IAtomicTransaction transaction, PartitionRef partition, PutVector vector, DocumentRecord document)
100100
{
101-
var record = new VectorRecord(vector.Id, vector.Field, vector.Space, vector.Values, document.Revision);
101+
var record = new VectorStorageRecord(vector.Id, vector.Field, vector.Space,
102+
VectorStorageRecord.Pack(vector.Values.AsSpan()), document.Revision);
102103
var lineageKey = VectorProjectionKeys.Lineage(partition, vector.Collection, vector.Field, vector.Id);
103104
if (transaction.GetRecord<VectorProjectionLineage>(lineageKey) is { } previousLineage)
104105
{

‎src/KeyLoad.Core/Search/Commands/VectorProjectionValidation.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,8 @@ internal static DocumentRecord ValidateProjectionTarget(this DatabaseEngine engi
128128

129129
internal static void RequireCanonicalProjectionEffect(IKeyValueView view, PartitionRef partition, PutVector target, VectorProjectionEffect effect)
130130
{
131-
var vector = view.GetRecord<VectorRecord>(KeySpace.Partition(VisibleVectorReads.VectorKeySpace, partition, target.Collection, target.Field, target.Id));
132-
if (vector is null || vector.DocumentId != target.Id || vector.Field != target.Field || vector.Space != target.Space || vector.DocumentRevision != target.ExpectedDocumentRevision || effect.Receipt.Revision != vector.DocumentRevision || !VectorProjectionPolicy.MatchesCanonicalVector(effect.Fingerprint, target.Collection, vector))
131+
var vector = view.GetRecord<VectorStorageRecord>(KeySpace.Partition(VisibleVectorReads.VectorKeySpace, partition, target.Collection, target.Field, target.Id));
132+
if (vector is null || vector.DocumentId != target.Id || vector.Field != target.Field || vector.Space != target.Space || vector.DocumentRevision != target.ExpectedDocumentRevision || effect.Receipt.Revision != vector.DocumentRevision || !VectorProjectionPolicy.MatchesCanonicalVector(effect.Fingerprint, target.Collection, vector.Materialize()))
133133
{
134134
throw Errors.Fail(ErrorCode.Corruption, VectorProjectionApply.ProjectionEffectCorruptMessage);
135135
}

‎src/KeyLoad.Core/Search/Queries/SearchLookupClosure.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,14 @@ internal static void Capture(DatabaseEngine database, IScopedReadCapture source,
2929
source.VisitCapturedPrefix(prefix, (_, bytes) =>
3030
{
3131
budget.Check();
32-
var vector = OrleansSerialization.Deserialize<VectorRecord>(bytes);
32+
var vector = OrleansSerialization.Deserialize<VectorStorageRecord>(bytes);
3333
CaptureVector(database, source, principal, partition, collection, vector, budget);
3434
return true;
3535
});
3636
}
3737

3838
private static void CaptureVector(DatabaseEngine database, IScopedReadCapture source, PrincipalRecord principal,
39-
PartitionRef partition, string collection, VectorRecord vector, ReadExecutionBudget budget)
39+
PartitionRef partition, string collection, VectorStorageRecord vector, ReadExecutionBudget budget)
4040
{
4141
budget.Check();
4242
var document = Read<DocumentRecord>(source, DocumentStorageKeys.RecordKey(partition, collection, vector.DocumentId));
@@ -51,7 +51,7 @@ private static void CaptureVector(DatabaseEngine database, IScopedReadCapture so
5151
{
5252
return;
5353
}
54-
VectorProjectionEligibility.ValidateLineage(lineage, partition, document, vector);
54+
VectorProjectionEligibility.ValidateLineage(lineage, partition, document, vector.Materialize());
5555
source.CaptureExact(VectorProjectionKeys.Effect(partition, lineage));
5656
source.CaptureExact(KeySpace.Resource(partition.TenantId, partition.DatabaseId, lineage.SourceDocument.Collection));
5757
source.CaptureExact(DocumentStorageKeys.RecordKey(lineage.SourceDocument));

‎src/KeyLoad.Core/Search/Queries/VectorProjectionEligibility.cs‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,9 @@ internal static class VectorProjectionEligibility
1111

1212
private const string LineageCorrupt = "The stored vector projection lineage is corrupt.";
1313

14-
internal static bool IsEligible(DatabaseEngine database, IKeyValueView view, PrincipalRecord principal,
15-
PartitionRef partition, string collection, DocumentRecord targetDocument, VectorRecord vector,
16-
ReadExecutionBudget budget, ReadExecutionRecordReader<VectorProjectionLineage> lineages,
17-
(string Field, byte[] Prefix) lineageScope, AnnLifetimeResourceResolver? lifetime = null, bool sourcePolicies = false)
14+
internal static VectorProjectionLineage? ReadLineage(PartitionRef partition, string collection,
15+
VectorStorageRecord vector, ReadExecutionRecordReader<VectorProjectionLineage> lineages,
16+
(string Field, byte[] Prefix) lineageScope)
1817
{
1918
if (vector.DocumentId is null || vector.Field is null || vector.Space is null)
2019
{
@@ -23,12 +22,15 @@ internal static bool IsEligible(DatabaseEngine database, IKeyValueView view, Pri
2322
var lineageKey = string.Equals(vector.Field, lineageScope.Field, StringComparison.Ordinal)
2423
? VectorProjectionKeys.Lineage(lineageScope.Prefix, vector.DocumentId)
2524
: VectorProjectionKeys.Lineage(partition, collection, vector.Field, vector.DocumentId);
26-
var lineage = lineages.Read(lineageKey);
27-
if (lineage is null)
28-
{
29-
return true;
30-
}
25+
return lineages.Read(lineageKey);
26+
}
3127

28+
internal static bool IsEligible(DatabaseEngine database, IKeyValueView view, PrincipalRecord principal,
29+
PartitionRef partition, string collection, DocumentRecord targetDocument, VectorRecord vector,
30+
VectorProjectionLineage lineage, ReadExecutionBudget budget, AnnLifetimeResourceResolver? lifetime,
31+
bool sourcePolicies = false)
32+
{
33+
budget.Check();
3234
ValidateLineage(lineage, partition, targetDocument, vector);
3335
VectorProjectionPolicy.ValidateEffect(budget.ReadRecord<VectorProjectionEffect>(view,
3436
VectorProjectionKeys.Effect(partition, lineage)), lineage, vector);

0 commit comments

Comments
 (0)