Skip to content

Commit 7cda797

Browse files
committed
Use bounded document index ranges and avoid discarded JSON encoding
Plan conjunctive single-field scalar inequalities through existing storage bounds while retaining authorization, residual predicates, cursor cuts and budgets. Validate retained document content without canonical output encoding. Verified: Debug solution build with warnings as errors; solution formatting verification; 111 focused document, query and storage tests; repository governance. Local one-million-call validation allocation fell from 5427.766 to 624.003 bytes per call; this is not a database throughput comparison. Cluster, recovery, coverage and endurance qualification were not run.
1 parent 0077329 commit 7cda797

12 files changed

Lines changed: 367 additions & 27 deletions

File tree

‎docs/Features/QueryExecution.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ The two counters must not be compared as though they share one unit.
4040

4141
Complete range traversal stops its internal visitor at the provider's record ceiling before a lookahead can exceed that physical page's work budget. It resumes after the last delivered storage key inside the same owning gate. An internal page boundary does not become the caller's terminal stop; an explicit caller stop remains terminal even at that boundary. A contiguous range of deleted documents can therefore span storage pages while the query continues collecting its requested live rows. Physical examined-record, byte, read-cut and cancellation checks remain enforced by their existing owners.
4242

43+
Single-field scalar indexes also serve conjunctive `<`, `<=`, `>` and `>=` predicates, including reversed operands and bound parameters. The planner selects the tightest encoded lower and upper bounds and seeks through the existing storage range API. Strict bounds exclude every document sharing the boundary value; inclusive bounds retain them. The full predicate, persisted row/field authorization, original read cut and cursor fences still apply to every selected document. Disjunctions do not select just one branch. Composite inequality planning remains unsupported. `IndexRangeAccessPathTests` checks SQL/AST parity, exact endpoints, duplicate values, residuals, physical examined-entry bounds, protected fields, cancellation and cursor invalidation.
44+
4345
Q1 provides typed adapter validation, authorization, deterministic scalar order, a bounded current-cut query and cursor, and a capability manifest. A global serializable snapshot, arbitrary joins and user delegates, and cross-shard execution are not declared implemented. [Search](Search.md) and [ChangeFeeds](ChangeFeeds.md) have their own behavior contracts; a live scalar query uses the same safe query boundary.
4446

4547
Decisions: [ADR-147 id continuation](../ADR/ADR-147-id-ordered-query-continuation.md), [ADR-149 no operation limits](../ADR/ADR-149-no-operation-limits.md), [ADR-004](../ADR/ADR-004-committed-read-views.md), [ADR-010](../ADR/ADR-010-query-budgets-security.md), [ADR-013 AST](../ADR/ADR-013-authorized-query-ast.md), [ADR-020 contexts](../ADR/ADR-020-independent-query-contexts.md), [ADR-022 policy epoch](../ADR/ADR-022-policy-epoch-revocation.md). One integration owner holds the shared AST, codec, security and cursor contracts. Qualification comes only from the TUnit, recovery and Aspire cluster SDK/MCP runs.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
namespace KeyLoad.Storage;
2+
3+
/// <summary>Computes byte-order bounds shared by storage traversal and index planning.</summary>
4+
internal static class StorageKeyBounds
5+
{
6+
internal static (bool HasValue, byte[]? Value) PrefixSuccessor(ReadOnlySpan<byte> prefix)
7+
{
8+
if (prefix.IsEmpty)
9+
{
10+
return (false, default(byte[]?));
11+
}
12+
var successor = prefix.ToArray();
13+
for (var index = successor.Length - 1; index >= 0; index--)
14+
{
15+
if (successor[index] == byte.MaxValue)
16+
{
17+
continue;
18+
}
19+
successor[index]++;
20+
return (true, successor[..(index + 1)]);
21+
}
22+
return (false, default(byte[]?));
23+
}
24+
}

‎src/KeyLoad.Core/JsonData.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,17 @@ private static string ValidateCore(string json, bool requireObject, bool preserv
4646
{
4747
throw Errors.Fail(ErrorCode.Validation, ObjectRequiredDetail);
4848
}
49-
var bytes = preserveContent ? null : new ArrayBufferWriter<byte>();
50-
using (var writer = bytes is null ? new Utf8JsonWriter(Stream.Null) : new Utf8JsonWriter(bytes))
49+
if (preserveContent)
50+
{
51+
CanonicalJsonWriter.Validate(document.RootElement);
52+
return json;
53+
}
54+
var bytes = new ArrayBufferWriter<byte>();
55+
using (var writer = new Utf8JsonWriter(bytes))
5156
{
5257
CanonicalJsonWriter.Write(writer, document.RootElement);
5358
}
54-
return bytes is null ? json
55-
: Encoding.UTF8.GetString(bytes.WrittenSpan);
59+
return Encoding.UTF8.GetString(bytes.WrittenSpan);
5660
}
5761
catch (JsonException)
5862
{

‎src/KeyLoad.Core/ResourceExecution/Serialization/CanonicalJsonWriter.cs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,38 @@ internal static class CanonicalJsonWriter
1414
private const string DecimalRequired = "JSON numbers must fit the decimal numeric policy.";
1515
private const string DecimalFormat = "G29";
1616

17+
/// <summary>Checks content policy without sorting properties or encoding output that the caller discards.</summary>
18+
/// <param name="element">Parsed JSON within its document lifetime.</param>
19+
internal static void Validate(JsonElement element)
20+
{
21+
switch (element.ValueKind)
22+
{
23+
case JsonValueKind.Object:
24+
var names = new HashSet<string>(StringComparer.Ordinal);
25+
foreach (var property in element.EnumerateObject())
26+
{
27+
if (!names.Add(property.Name))
28+
{
29+
throw Errors.Fail(ErrorCode.Validation, DuplicateProperty);
30+
}
31+
Validate(property.Value);
32+
}
33+
break;
34+
case JsonValueKind.Array:
35+
foreach (var item in element.EnumerateArray())
36+
{
37+
Validate(item);
38+
}
39+
break;
40+
case JsonValueKind.Number:
41+
if (!element.TryGetDecimal(out _))
42+
{
43+
throw Errors.Fail(ErrorCode.Validation, DecimalRequired);
44+
}
45+
break;
46+
}
47+
}
48+
1749
/// <summary>Writes a complete canonical JSON value without retaining its complete output.</summary>
1850
/// <param name="writer">Caller-owned UTF-8 writer and destination.</param>
1951
/// <param name="element">Parsed JSON value within its document lifetime.</param>
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
namespace KeyLoad.Query.QueryExecution;
2+
3+
/// <summary>One declared index and its encoded exclusive storage bounds.</summary>
4+
internal sealed record QueryIndexRange(byte[] Prefix, byte[]? AfterKey, byte[]? UntilKey);

‎src/KeyLoad.Query/QueryExecution/Queries/QueryCandidateReader.cs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ internal string Visit()
3232
{
3333
return indexed;
3434
}
35+
if (RangePath().Value is { } range)
36+
{
37+
return range;
38+
}
3539
if (!request.AllowFullScan)
3640
{
3741
throw Errors.Fail(ErrorCode.UnsupportedCapability, FullScanDenied);
@@ -83,6 +87,28 @@ internal string Visit()
8387
return (false, default(string?));
8488
}
8589

90+
private (bool HasValue, string? Value) RangePath()
91+
{
92+
foreach (var index in resource.Indexes)
93+
{
94+
if (QueryIndexRangePlanner.Create(index, request).Value is not { } range)
95+
{
96+
continue;
97+
}
98+
var result = budget.VisitAll(view, range.Prefix, (_, value) =>
99+
{
100+
Read(OrleansSerialization.Deserialize<string>(value));
101+
return true;
102+
}, range.AfterKey, range.UntilKey);
103+
if (result.HasMore)
104+
{
105+
throw Errors.Fail(ErrorCode.BudgetExceeded, CandidateLimitExceeded);
106+
}
107+
return (true, IndexPathPrefix + index.Name);
108+
}
109+
return (false, default(string?));
110+
}
111+
86112
private void Candidate(ReadOnlySpan<byte> payload)
87113
{
88114
var record = OrleansSerialization.Deserialize<DocumentRecord>(payload);
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
using System.Text.Json;
2+
using KeyLoad.Core;
3+
using KeyLoad.Storage;
4+
5+
namespace KeyLoad.Query.QueryExecution;
6+
7+
/// <summary>Seeks scalar inequalities through the same ordered index used by equality queries.</summary>
8+
internal static class QueryIndexRangePlanner
9+
{
10+
private const string IndexSpace = "index";
11+
12+
internal static (bool HasValue, QueryIndexRange? Value) Create(IndexDefinition index, AstQueryRequest request)
13+
{
14+
if (index.Fields.Length != 1 || index.Fields[0] is SqlSyntax.MetadataIdPath or SqlSyntax.MetadataRevisionPath)
15+
{
16+
return (false, default(QueryIndexRange?));
17+
}
18+
var prefix = KeySpace.Partition(IndexSpace, request.Partition, request.Query.Collection, index.Name);
19+
byte[]? lower = null;
20+
byte[]? upper = null;
21+
Type? scalarType = null;
22+
var found = false;
23+
foreach (var comparison in Comparisons(request.Query.Filter))
24+
{
25+
var field = comparison.Left as FieldOperand ?? comparison.Right as FieldOperand;
26+
if (field?.Path != index.Fields[0])
27+
{
28+
continue;
29+
}
30+
var operation = comparison.Left is FieldOperand ? comparison.Operator : Reverse(comparison.Operator);
31+
if (operation is not (SqlSyntax.Greater or SqlSyntax.GreaterOrEqual or SqlSyntax.Less or SqlSyntax.LessOrEqual))
32+
{
33+
continue;
34+
}
35+
var operand = comparison.Left is FieldOperand ? comparison.Right : comparison.Left;
36+
var value = Value(operand, request.Parameters).Value;
37+
if (value is null or MissingValue)
38+
{
39+
continue;
40+
}
41+
if (scalarType is not null && scalarType != value.GetType())
42+
{
43+
return (false, default(QueryIndexRange?));
44+
}
45+
scalarType = value.GetType();
46+
var key = KeySpace.Partition(IndexSpace, request.Partition, request.Query.Collection, index.Name, value);
47+
if (operation is SqlSyntax.Greater or SqlSyntax.GreaterOrEqual)
48+
{
49+
var bound = operation == SqlSyntax.Greater ? StorageKeyBounds.PrefixSuccessor(key).Value : key;
50+
lower = lower is null || bound is not null && lower.AsSpan().SequenceCompareTo(bound) < 0 ? bound : lower;
51+
found = true;
52+
}
53+
if (operation is SqlSyntax.Less or SqlSyntax.LessOrEqual)
54+
{
55+
var bound = operation == SqlSyntax.LessOrEqual ? StorageKeyBounds.PrefixSuccessor(key).Value : key;
56+
upper = upper is null || bound is not null && upper.AsSpan().SequenceCompareTo(bound) > 0 ? bound : upper;
57+
found = true;
58+
}
59+
}
60+
return found ? (true, new(prefix, lower, upper)) : (false, default(QueryIndexRange?));
61+
}
62+
63+
private static (bool HasValue, object? Value) Value(Operand operand, Dictionary<string, JsonElement>? parameters)
64+
=> operand switch
65+
{
66+
ValueOperand value => (true, JsonData.Scalar(value.Value, string.Empty)),
67+
ParameterOperand parameter when parameters?.TryGetValue(parameter.Name, out var value) == true
68+
=> (true, JsonData.Scalar(value, string.Empty)),
69+
_ => (false, default(object?))
70+
};
71+
72+
private static string Reverse(string operation) => operation switch
73+
{
74+
SqlSyntax.Greater => SqlSyntax.Less,
75+
SqlSyntax.GreaterOrEqual => SqlSyntax.LessOrEqual,
76+
SqlSyntax.Less => SqlSyntax.Greater,
77+
SqlSyntax.LessOrEqual => SqlSyntax.GreaterOrEqual,
78+
_ => operation
79+
};
80+
81+
private static IEnumerable<Comparison> Comparisons(Predicate? predicate)
82+
{
83+
if (predicate is Logical { Operator: SqlSyntax.And } conjunction)
84+
{
85+
foreach (var comparison in Comparisons(conjunction.Left).Concat(Comparisons(conjunction.Right)))
86+
{
87+
yield return comparison;
88+
}
89+
}
90+
else if (predicate is Comparison comparison)
91+
{
92+
yield return comparison;
93+
}
94+
}
95+
}

‎src/KeyLoad.Storage.ZoneTree/StorageEngine/Queries/ZoneTreeRangeBounds.cs‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,6 @@ namespace KeyLoad.Storage.ZoneTree;
22

33
internal static class ZoneTreeRangeBounds
44
{
5-
internal static (bool HasValue, byte[]? Value) PrefixSuccessor(ReadOnlySpan<byte> prefix)
6-
{
7-
if (prefix.IsEmpty)
8-
{
9-
return (false, default(byte[]?));
10-
}
11-
12-
var successor = prefix.ToArray();
13-
for (var index = successor.Length - 1; index >= 0; index--)
14-
{
15-
if (successor[index] == byte.MaxValue)
16-
{
17-
continue;
18-
}
19-
20-
successor[index]++;
21-
return (true, ((byte[]?)(successor[..(index + 1)])));
22-
}
23-
24-
return (false, default(byte[]?));
25-
}
26-
275
internal static byte[]? Minimum(byte[]? first, byte[]? second)
286
{
297
if (first is null)

‎src/KeyLoad.Storage.ZoneTree/StorageEngine/Queries/ZoneTreeRangeReader.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ internal static StorageScanResult Visit(ZoneTreeStoreRuntime runtime, byte[] pre
1313
runtime.ReadCounters.RangeAttempt();
1414
Validate(prefix, maxRecords, visitor, runtime.Options.MaximumRangeRecords, cancellationToken);
1515
var lower = afterKey is not null && BinaryKeyComparer.Instance.Compare(afterKey, prefix) > 0 ? afterKey : prefix;
16-
var prefixSuccessor = reverse ? (ZoneTreeRangeBounds.PrefixSuccessor(prefix)).Value : null;
16+
var prefixSuccessor = reverse ? (StorageKeyBounds.PrefixSuccessor(prefix)).Value : null;
1717
if ((untilKey is not null && BinaryKeyComparer.Instance.Compare(lower, untilKey) >= 0)
1818
|| (reverse && prefixSuccessor is not null
1919
&& BinaryKeyComparer.Instance.Compare(lower, prefixSuccessor) >= 0))

‎tests/KeyLoad.FunctionalTests/DocumentStorage/Cases/Document/Writes/DocumentExactContentTests.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ public async Task AcDstore008ReplacementRetainsItsNewLiteralText()
5353
[Test]
5454
[Arguments("{\"a\":1,\"a\":2}")]
5555
[Arguments("{\"a\":1e1000}")]
56+
[Arguments("{\"a\":[{\"x\":1,\"\\u0078\":2}]}")]
57+
[Arguments("{\"a\":[{\"x\":1e1000}]}")]
58+
[Arguments("{\"a\":[] , \"b\":{\"nested\":true,\"nested\":false}}")]
59+
[Arguments("{\"a\":[1e1000]}")]
5660
public async Task AcDstore008DuplicateMembersAndDecimalOverflowStillFailWithoutDocumentEffects(string json)
5761
{
5862
using var database = new TestDatabase();

0 commit comments

Comments
 (0)