Skip to content

Commit 190ff88

Browse files
KSemenenkoclaude
andcommitted
Run each request on its own grain and remove byte accounting and request byte limits
Every request now runs on its own stateless request grain behind the connection grain. The request path no longer counts, measures or caps bytes. ReadExecutionBudget carries only caller cancellation, the operation lifetime and resource-lifetime bindings. - Delete read grants, the read byte and record counters, result byte measurement and the per-chunk stream byte counter. Delete the reply byte cap, the stream frame cap, the execution lifetime option and the Orleans MaxMessageBodySize override. - Remove MaxBytes from the change-feed, projection, live-query, stream, subscription and queue receive requests. Remove it from the query capability manifest, and delete QueryExecutionOptions.MaximumResultBytes. - Partition query and distributed search plans and leaves no longer carry byte or record allowances, deadline mapping or retention accounting. - Delete the ANN and text maintenance page caps; replay pages until the projection reports no more entries. - Event feed PubSub rows are serialized once, with no retained-byte ledger. - The SDK queue worker no longer counts UTF-8 payload bytes or caps in-flight bytes. - Closing a connection stops admission and joins admitted operations without cancelling them on their request grains. - Allow awaited asynchronous ZoneTree APIs (KLD0039). - Cache cosine squared norms in packed ANN vectors. - Process-recovery command files use Orleans binary serialization, so typed command input round-trips. - Tests that only proved a removed cap are deleted. Cancellation tests that used charged bytes as a progress signal now observe store read diagnostics. - The coverage inventory, coverage contract, product contributors and CI lanes are synchronized. - Docs and ADRs describe the current contracts. Verification (local, Debug, macOS arm64): - dotnet build KeyLoad.slnx -warnaserror: 0 warnings, 0 errors. - dotnet format --verify-no-changes and the governance script pass. - A full FunctionalTests run before the final fixes passed 3345 of 3468. - After the fixes, the reruns pass: - Messaging: 392 of 392. - The previously failing analytics, graph, ANN, budgeted-read, ordered retry, connection close, multi-lane, TUnit selection, production manifest and process-recovery classes all pass. - OrleansExecution passes 187 of 195. The 8 failures are text maintenance cases that fail with "The execution text projection is corrupt." ZoneTree rewrites its own index1/0.json metadata after publication, and TextInventory compares SHA256 hashes of engine-owned files. This also fails at HEAD in CI. - Still open: - The full-text inventory failures, together with the related text and process-recovery cases. - Cluster tests were not run locally. - No Linux CI qualification. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent eb7f085 commit 190ff88

674 files changed

Lines changed: 2466 additions & 10859 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,13 @@ ad-hoc concatenation. Do not change user entity casing implicitly.
8888
- Use ZoneTree.FullTextSearch for full-text indexing and ZoneTree.Analytics for
8989
approved analytics integration. Derived indexes, caches and analytics never
9090
become a second authority for database records or permissions.
91-
- Access ZoneTree, ZoneTree.FullTextSearch and ZoneTree.Analytics through their
92-
public synchronous APIs. Their asynchronous API calls and dispatching
93-
engine work through `Task.Run`, `Task.Factory.StartNew` or a thread-pool callback
94-
are compiler errors (`KLD0039`). Do not wrap synchronous engine operations to
95-
bypass this rule. Orleans, HTTP and other actual asynchronous transports remain
96-
asynchronous; the rule makes no claim about a dependency's internal scheduling.
91+
- Use ZoneTree, ZoneTree.FullTextSearch and ZoneTree.Analytics through their
92+
public APIs. Await their asynchronous APIs, such as `CommitDurableAsync` and
93+
`SyncWALAsync`, so engine waits never block a grain or thread-pool thread.
94+
Blocking on their tasks (`.Result`, `.Wait()`, `.GetAwaiter().GetResult()`) and
95+
dispatching engine work through `Task.Run`, `Task.Factory.StartNew` or a
96+
thread-pool callback are compiler errors (`KLD0039`). The rule makes no claim
97+
about a dependency's internal scheduling.
9798
- Use generated Orleans binary serialization with explicit stable
9899
`[GenerateSerializer]`, `[Id]` and `[Alias]` contracts internally. Preserve raw
99100
ZoneTree bytes, sortable keys, public JSON and exact user content. Introduce no

‎analyzers/KeyLoad.Analyzers/Analysis/RuntimeContracts/ZoneTreeDispatchAnalysis.cs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,33 @@ internal static bool ContainsAccess(IOperation operation, OperationAnalysisConte
3737
return false;
3838
}
3939

40+
/// <summary>Finds whether a blocked awaitable comes from a ZoneTree asynchronous member.</summary>
41+
internal static bool FromEngine(IOperation? operation)
42+
{
43+
while (operation is not null)
44+
{
45+
switch (operation)
46+
{
47+
case IConversionOperation conversion:
48+
operation = conversion.Operand;
49+
continue;
50+
case IInvocationOperation invocation when invocation.TargetMethod.Name is "GetAwaiter" or "ConfigureAwait"
51+
or "AsTask":
52+
operation = invocation.Instance;
53+
continue;
54+
case IInvocationOperation invocation:
55+
return ZoneTreeAccessPolicy.Execution(invocation.TargetMethod)
56+
&& ZoneTreeAccessPolicy.Asynchronous(invocation.TargetMethod);
57+
case IPropertyReferenceOperation property:
58+
return ZoneTreeAccessPolicy.Execution(property.Property)
59+
&& ZoneTreeAccessPolicy.Awaitable(property.Property.Type);
60+
default:
61+
return false;
62+
}
63+
}
64+
return false;
65+
}
66+
4067
internal static bool RuntimeResource(IOperation operation)
4168
{
4269
if (ZoneTreeAccessPolicy.Execution(operation.Type))

‎analyzers/KeyLoad.Analyzers/Analyzers/RuntimeContracts/SynchronousZoneTreeAccessAnalyzer.cs‎

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace KeyLoad.Analyzers.CodeQuality;
88

9-
/// <summary>Requires synchronous execution engine access while preserving asynchronous Orleans and transport calls.</summary>
9+
/// <summary>Requires awaited ZoneTree work: no blocking on its tasks and no thread-pool dispatch of engine access.</summary>
1010
[DiagnosticAnalyzer(LanguageNames.CSharp)]
1111
public sealed class SynchronousZoneTreeAccessAnalyzer : DiagnosticAnalyzer
1212
{
@@ -30,15 +30,13 @@ public override void Initialize(AnalysisContext context)
3030
context.EnableConcurrentExecution();
3131
context.RegisterOperationAction(AnalyzeInvocation, Microsoft.CodeAnalysis.OperationKind.Invocation);
3232
context.RegisterOperationAction(AnalyzeProperty, Microsoft.CodeAnalysis.OperationKind.PropertyReference);
33-
context.RegisterOperationAction(AnalyzeUsing, Microsoft.CodeAnalysis.OperationKind.Using, Microsoft.CodeAnalysis.OperationKind.UsingDeclaration);
3433
}
3534

3635
private static void AnalyzeInvocation(OperationAnalysisContext context)
3736
{
3837
var invocation = (IInvocationOperation)context.Operation;
3938
var method = invocation.TargetMethod;
40-
if ((ZoneTreeAccessPolicy.Execution(method) || invocation.Instance is not null &&
41-
ZoneTreeDispatchAnalysis.RuntimeResource(invocation.Instance)) && ZoneTreeAccessPolicy.Asynchronous(method) ||
39+
if (ZoneTreeAccessPolicy.Blocking(method) && ZoneTreeDispatchAnalysis.FromEngine(invocation.Instance) ||
4240
ZoneTreeAccessPolicy.Dispatch(method) && ZoneTreeDispatchAnalysis.ContainsAccess(invocation, context,
4341
new HashSet<IMethodSymbol>(SymbolEqualityComparer.Default)))
4442
{
@@ -49,23 +47,10 @@ private static void AnalyzeInvocation(OperationAnalysisContext context)
4947
private static void AnalyzeProperty(OperationAnalysisContext context)
5048
{
5149
var reference = (IPropertyReferenceOperation)context.Operation;
52-
if (ZoneTreeAccessPolicy.Execution(reference.Property) && ZoneTreeAccessPolicy.Awaitable(reference.Property.Type))
50+
if (reference.Property.Name == "Result" && ZoneTreeAccessPolicy.Awaitable(reference.Property.ContainingType)
51+
&& ZoneTreeDispatchAnalysis.FromEngine(reference.Instance))
5352
{
5453
context.ReportDiagnostic(Diagnostic.Create(Rule, reference.Syntax.GetLocation(), reference.Property.ToDisplayString()));
5554
}
5655
}
57-
58-
private static void AnalyzeUsing(OperationAnalysisContext context)
59-
{
60-
var resource = context.Operation switch
61-
{
62-
IUsingOperation { IsAsynchronous: true } operation => operation.Resources,
63-
IUsingDeclarationOperation { IsAsynchronous: true } declaration => declaration.DeclarationGroup,
64-
_ => null
65-
};
66-
if (resource is not null && ZoneTreeDispatchAnalysis.RuntimeResource(resource))
67-
{
68-
context.ReportDiagnostic(Diagnostic.Create(Rule, resource.Syntax.GetLocation(), "DisposeAsync"));
69-
}
70-
}
7156
}

‎analyzers/KeyLoad.Analyzers/Contracts/ZoneTreeAccessPolicy.cs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ namespace KeyLoad.Analyzers.CodeQuality;
66
internal static class ZoneTreeAccessPolicy
77
{
88
internal const string DiagnosticId = "KLD0039";
9-
internal const string Title = "Use synchronous execution ZoneTree APIs";
10-
internal const string Message = "'{0}' must use the synchronous execution ZoneTree API without thread-pool dispatch";
11-
internal const string Description = "ZoneTree, ZoneTree.FullTextSearch and ZoneTree.Analytics access uses their public synchronous APIs. Orleans and transport calls remain asynchronous; wrapping execution engine work in a thread-pool dispatch does not satisfy this rule.";
9+
internal const string Title = "Await ZoneTree work without blocking or thread-pool dispatch";
10+
internal const string Message = "'{0}' must await ZoneTree work instead of blocking on it or dispatching it to the thread pool";
11+
internal const string Description = "ZoneTree, ZoneTree.FullTextSearch and ZoneTree.Analytics asynchronous APIs, such as durable commits and write-ahead log syncs, are awaited so they never block a grain or thread-pool thread. Blocking on their tasks or wrapping engine work in a thread-pool dispatch is rejected.";
1212
private const string TasksNamespace = "System.Threading.Tasks";
1313
private const string CollectionsNamespace = "System.Collections.Generic";
1414

@@ -22,6 +22,11 @@ internal static bool Awaitable(ITypeSymbol type) =>
2222
type.ContainingNamespace?.ToDisplayString() == TasksNamespace && type.Name is "Task" or "ValueTask" ||
2323
type.ContainingNamespace?.ToDisplayString() == CollectionsNamespace && type.Name == "IAsyncEnumerable";
2424

25+
internal static bool Blocking(IMethodSymbol method) =>
26+
method.Name == "GetResult" && method.ContainingType.Name is "TaskAwaiter" or "ValueTaskAwaiter" or "ConfiguredTaskAwaiter"
27+
or "ConfiguredValueTaskAwaiter" ||
28+
method.Name == "Wait" && method.ContainingType.Name is "Task" && method.ContainingNamespace.ToDisplayString() == TasksNamespace;
29+
2530
internal static bool Dispatch(IMethodSymbol method) =>
2631
method.ContainingNamespace.ToDisplayString() == TasksNamespace &&
2732
(method.ContainingType.Name == "Task" && method.Name == "Run" ||
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using BenchmarkDotNet.Attributes;
2+
using KeyLoad.Query.Search;
3+
4+
namespace KeyLoad.BenchmarkScenarios.BenchmarkComparisons;
5+
6+
/// <summary>Measures the production SIMD cosine kernels with computed and retained candidate norms.</summary>
7+
[MemoryDiagnoser]
8+
[InProcess]
9+
[WarmupCount(3)]
10+
[IterationCount(6)]
11+
[IterationTime(200)]
12+
public class CosineMetricBenchmarks
13+
{
14+
private const int CorpusPhaseOffset = 7;
15+
private const string UnequalScores = "The production cosine kernels disagree.";
16+
private float[] query = [];
17+
private float[] candidate = [];
18+
private double queryNorm;
19+
private double candidateNorm;
20+
21+
/// <summary>Gets or sets the short, wide-tail or maximum supported vector dimension.</summary>
22+
[Params(16, 769, 4_096)]
23+
public int Dimension { get; set; }
24+
25+
/// <summary>Prepares owned finite vectors and verifies identical production scores before timing.</summary>
26+
[GlobalSetup]
27+
public void Setup()
28+
{
29+
SimdRuntime.RequireHardwareSupport();
30+
query = Enumerable.Range(0, Dimension).Select(index => (float)Math.Sin(index)).ToArray();
31+
candidate = Enumerable.Range(0, Dimension).Select(index => (float)Math.Sin(index + CorpusPhaseOffset)).ToArray();
32+
queryNorm = SimilarityMetricMath.Norm(query);
33+
candidateNorm = SimilarityMetricMath.Norm(candidate);
34+
if (RecomputeCandidateNorm() != RetainedCandidateNorm())
35+
{
36+
throw new InvalidOperationException(UnequalScores);
37+
}
38+
}
39+
40+
/// <summary>Computes the candidate norm in the exact metric's existing combined SIMD pass.</summary>
41+
/// <returns>The cosine score.</returns>
42+
[Benchmark(Baseline = true)]
43+
public double RecomputeCandidateNorm()
44+
=> SimilarityMetricMath.Score(query, candidate, DistanceMetric.Cosine, queryNorm);
45+
46+
/// <summary>Uses the norm retained by the immutable packed ANN vector arena.</summary>
47+
/// <returns>The cosine score with unchanged double-precision reduction grouping.</returns>
48+
[Benchmark]
49+
public double RetainedCandidateNorm()
50+
=> SimilarityMetricMath.CosineWithNorms(query, candidate, queryNorm, candidateNorm);
51+
}

‎benchmarks/KeyLoad.BenchmarkScenarios/Benchmarks/Serialization/SampleChunkBenchmarkState.cs‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,19 +55,13 @@ internal SampleRecord[] RuntimeDecode()
5555
var decoded = new SampleRecord[records.Length];
5656
for (var index = IndexInitialValue; index < records.Length; index++)
5757
{
58-
budget.ChargeBytes(runtimeValues[index].Length);
5958
decoded[index] = OrleansSerialization.Deserialize<SampleRecord>(runtimeValues[index]);
6059
budget.Check();
6160
}
6261
return decoded;
6362
}
6463

65-
internal SampleRecord[] ChunkDecode()
66-
{
67-
var budget = Budget();
68-
budget.ChargeBytes(chunk.Length);
69-
return SampleChunkCodec.Decode(chunk, budget, executionOptions);
70-
}
64+
internal SampleRecord[] ChunkDecode() => SampleChunkCodec.Decode(chunk, Budget(), executionOptions);
7165

7266
private static ReadExecutionBudget Budget() => new();
7367

‎docs/ADR/ADR-004-committed-read-views.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ EventStreams `REQ-EVENT-001..003`/`AC-MP-005`, QueryExecution `REQ-QUERY-001..00
1717
## Implementation contract
1818

1919
1. Freeze the read cut and generation semantics for each canonical, feed, and derived-projection read.
20-
2. Add tests for concurrent append/page, exact boundary/lookahead, stale generation/retention, cancellation, and complete metadata byte limits.
20+
2. Add tests for concurrent append/page, exact boundary/lookahead, stale generation/retention, cancellation, and complete page metadata.
2121
3. Keep the common storage view contract in `src/KeyLoad.Abstractions/Storage/Contracts/StorageContracts.cs` and implement its lifetime/committed cut under `src/KeyLoad.Storage.ZoneTree/StorageEngine/`; per-feature readers live under their canonical Core `Features/<SliceName>/` roots and do not leak borrowed spans beyond the gate. Do not add a ReadViews slice.
2222
4. Validate current cursor versions and invalidate stale bindings explicitly. Reject unsupported cursors with a stable error rather than translating them or guessing their cut.
2323
5. GitHub CI runs real-store TUnit, process recovery, and replicated-cluster client reads across failover.

‎docs/ADR/ADR-010-query-budgets-security.md‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,34 @@
22

33
Status: Accepted; end-to-end qualification pending. Related current baseline: [QueryExecution](../Features/QueryExecution.md), [ResourceExecution](../Features/ResourceExecution.md), and product source [sections 13–15, 23–26, and 29–30](../design/product-specification.md).
44

5-
Superseded in part by [ADR-149](ADR-149-no-operation-limits.md): the `DatabaseLimits` operation limits it references are removed.
5+
[ADR-149](ADR-149-no-operation-limits.md) governs operation bounds: there are no configured work, read-byte or result-byte budgets.
66

77
## Context and decision
88

9-
Queries combine parsing/planning, index/scan work, point dereferences, graph expansion, search branches, projection, and serialized response metadata. Unbounded stages can consume memory/CPU or leak data through filtering/ranking. A request carries one bounded cancellation/deadline/work/read/result budget through relevant operators. Authorization and row/field policy must be applied before data can affect an observable result; security barriers cannot be moved below a filter or ranking stage that reveals protected values.
9+
Queries combine parsing/planning, index/scan work, point dereferences, graph expansion, search branches, projection, and serialized response metadata. Unbounded stages can consume memory/CPU or leak data through filtering/ranking. A request carries one operation (`ReadExecutionBudget`: caller cancellation, explicit expiry and resource-lifetime bindings) through relevant operators; it counts no work, read bytes or result bytes. Authorization and row/field policy must be applied before data can affect an observable result; security barriers cannot be moved below a filter or ranking stage that reveals protected values.
1010

1111
## Rationale and consequences
1212

13-
One budget prevents each operator from independently spending the full limit. Explicit failure preserves honesty when completeness cannot be proven; partial results require a separately explicit contract. Typed authorized ASTs and field lineage prevent SQL/JSON/C# surface differences from bypassing policy. Budgets may reject large valid workloads and must be surfaced as stable errors.
13+
One operation lets every operator observe the same cancellation and expiry. Explicit failure preserves honesty when completeness cannot be proven; partial results require a separately explicit contract. Typed authorized ASTs and field lineage prevent SQL/JSON/C# surface differences from bypassing policy. An elapsed expiry surfaces as a stable `BudgetExceeded` error; large valid workloads run as far as the caller's limits, cancellation and expiry allow.
1414

1515
## Related requirements
1616

17-
QueryExecution `REQ-QUERY-001..003`/`AC-MP-003`, GraphTraversal `REQ-GRAPH-002..004`, DocumentStorage `REQ-DSTORE-003`, EventStreams `REQ-EVENT-001..003`, and Search `REQ-SR-001..005`. Live change-feed behavior (`REQ/AC-FEED-002/003/005`, owned by [ChangeFeeds](../Features/ChangeFeeds.md)) follows this decision: a continuation cursor carries no frozen local cut, every call opens a fresh committed view with its own cut, and the complete page including cursor metadata must fit the same result budget; cancellation returns no partial page.
17+
QueryExecution `REQ-QUERY-001..003`/`AC-MP-003`, GraphTraversal `REQ-GRAPH-002..004`, DocumentStorage `REQ-DSTORE-003`, EventStreams `REQ-EVENT-001..003`, and Search `REQ-SR-001..005`. Live change-feed behavior (`REQ/AC-FEED-002/003/005`, owned by [ChangeFeeds](../Features/ChangeFeeds.md)) follows this decision: a continuation cursor carries no frozen local cut, every call opens a fresh committed view with its own cut, and a page is bounded by its record `Limit`; cancellation returns no partial page.
1818

1919
## Implementation contract
2020

21-
1. Freeze per-request budget dimensions, operator charge points, error behavior, and authorization-before-observation rules.
22-
2. Add real tests for scan/index/point accounting, metadata/result bytes, cancel/deadline, hidden rows/fields, aliases, explain, and following-operation health.
23-
3. Implement shared budgets under `src/KeyLoad.Abstractions/ResourceExecution/` and `src/KeyLoad.Core/ResourceExecution/`; each canonical slice owns its operators under `Features/<Slice>/`.
24-
4. Any budget or policy change is versioned/configured explicitly; rollback restores the prior bound without allowing an unbounded fallback. Capability manifests list only operators with an enforced budget.
21+
1. Freeze the operation's cancellation and expiry checkpoints, error behavior, and authorization-before-observation rules.
22+
2. Add real tests for cancel/deadline, hidden rows/fields, aliases, explain, and following-operation health.
23+
3. Implement the shared operation under `src/KeyLoad.Abstractions/ResourceExecution/` and `src/KeyLoad.Core/ResourceExecution/`; each canonical slice owns its operators under `Features/<Slice>/`.
24+
4. Any policy change is versioned/configured explicitly. Capability manifests list only operators whose cancellation, expiry and caller limits are enforced.
2525
5. GitHub CI executes TUnit and real replicated-cluster API scenarios with the same caller-visible errors; retained diagnostics contain no sensitive payloads.
2626

2727
Dependencies: [ADR-004](ADR-004-committed-read-views.md), [ADR-006](ADR-006-strict-derived-indexes.md), [ADR-009](ADR-009-search-provider-boundaries.md), [ADR-013](ADR-013-authorized-query-ast.md), [ADR-014](ADR-014-principals-rbac-row-policy.md), [ADR-015](ADR-015-sensitive-data-lineage.md), [ADR-018](ADR-018-global-rank-fusion.md), [ADR-019](ADR-019-managed-ann.md), and [ADR-022](ADR-022-policy-epoch-revocation.md). Stop if an operator cannot prove complete bounded output or policy order; do not silently truncate.
2828

2929
```mermaid
3030
flowchart LR
3131
Request[Authenticated request] --> Parse[Validate and bind authorized AST]
32-
Parse --> Budget[One work time cancellation and result budget]
32+
Parse --> Budget[One operation with cancellation and explicit expiry]
3333
Budget --> Operators[Bounded index scan graph or search operators]
3434
Operators --> Barrier[Row and field security projection]
3535
Barrier --> Result[Complete response or explicit rejection]

0 commit comments

Comments
 (0)