@topgunbuild/core 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -6,6 +6,12 @@ interface Timestamp {
6
6
  counter: number;
7
7
  nodeId: string;
8
8
  }
9
+ /**
10
+ * Clock source interface for time dependency injection.
11
+ */
12
+ interface ClockSource {
13
+ now(): number;
14
+ }
9
15
  /**
10
16
  * Configuration options for HLC behavior.
11
17
  */
@@ -21,6 +27,12 @@ interface HLCOptions {
21
27
  * Default: 60000 (1 minute)
22
28
  */
23
29
  maxDriftMs?: number;
30
+ /**
31
+ * Clock source for time generation.
32
+ * Defaults to Date.now() for production use.
33
+ * Can be replaced with VirtualClock for deterministic testing.
34
+ */
35
+ clockSource?: ClockSource;
24
36
  }
25
37
  declare class HLC {
26
38
  private lastMillis;
@@ -28,10 +40,16 @@ declare class HLC {
28
40
  private readonly nodeId;
29
41
  private readonly strictMode;
30
42
  private readonly maxDriftMs;
43
+ private readonly clockSource;
31
44
  constructor(nodeId: string, options?: HLCOptions);
32
45
  get getNodeId(): string;
33
46
  get getStrictMode(): boolean;
34
47
  get getMaxDriftMs(): number;
48
+ /**
49
+ * Returns the clock source used by this HLC instance.
50
+ * Useful for LWWMap/ORMap to access the same clock for TTL checks.
51
+ */
52
+ getClockSource(): ClockSource;
35
53
  /**
36
54
  * Generates a new unique timestamp for a local event.
37
55
  * Ensures monotonicity: always greater than any previously generated or received timestamp.
@@ -2726,6 +2744,247 @@ type ORMapSyncRespBucketsPayload = z.infer<typeof ORMapSyncRespBucketsSchema>['p
2726
2744
  type ORMapSyncRespLeafPayload = z.infer<typeof ORMapSyncRespLeafSchema>['payload'];
2727
2745
  type ORMapDiffResponsePayload = z.infer<typeof ORMapDiffResponseSchema>['payload'];
2728
2746
 
2747
+ /**
2748
+ * Schema for individual sync map entries, specifying which maps the client
2749
+ * wants deltas for and the last known sync HLC timestamp for each.
2750
+ */
2751
+ declare const SyncMapEntrySchema: z.ZodObject<{
2752
+ mapName: z.ZodString;
2753
+ lastSyncTimestamp: z.ZodObject<{
2754
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2755
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2756
+ nodeId: z.ZodString;
2757
+ }, z.core.$strip>;
2758
+ }, z.core.$strip>;
2759
+ /**
2760
+ * Schema for one-shot query requests over HTTP.
2761
+ */
2762
+ declare const HttpQueryRequestSchema: z.ZodObject<{
2763
+ queryId: z.ZodString;
2764
+ mapName: z.ZodString;
2765
+ filter: z.ZodAny;
2766
+ limit: z.ZodOptional<z.ZodNumber>;
2767
+ offset: z.ZodOptional<z.ZodNumber>;
2768
+ }, z.core.$strip>;
2769
+ /**
2770
+ * Schema for one-shot search requests over HTTP.
2771
+ */
2772
+ declare const HttpSearchRequestSchema: z.ZodObject<{
2773
+ searchId: z.ZodString;
2774
+ mapName: z.ZodString;
2775
+ query: z.ZodString;
2776
+ options: z.ZodOptional<z.ZodAny>;
2777
+ }, z.core.$strip>;
2778
+ /**
2779
+ * HTTP sync request body sent by the client as POST /sync.
2780
+ * Contains all context needed for a stateless request: client identity,
2781
+ * HLC state, operations to push, maps to pull deltas for, and queries/searches.
2782
+ */
2783
+ declare const HttpSyncRequestSchema: z.ZodObject<{
2784
+ clientId: z.ZodString;
2785
+ clientHlc: z.ZodObject<{
2786
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2787
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2788
+ nodeId: z.ZodString;
2789
+ }, z.core.$strip>;
2790
+ operations: z.ZodOptional<z.ZodArray<z.ZodObject<{
2791
+ id: z.ZodOptional<z.ZodString>;
2792
+ mapName: z.ZodString;
2793
+ key: z.ZodString;
2794
+ opType: z.ZodOptional<z.ZodString>;
2795
+ record: z.ZodOptional<z.ZodNullable<z.ZodObject<{
2796
+ value: z.ZodNullable<z.ZodAny>;
2797
+ timestamp: z.ZodObject<{
2798
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2799
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2800
+ nodeId: z.ZodString;
2801
+ }, z.core.$strip>;
2802
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2803
+ }, z.core.$strip>>>;
2804
+ orRecord: z.ZodOptional<z.ZodNullable<z.ZodObject<{
2805
+ value: z.ZodAny;
2806
+ timestamp: z.ZodObject<{
2807
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2808
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2809
+ nodeId: z.ZodString;
2810
+ }, z.core.$strip>;
2811
+ tag: z.ZodString;
2812
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2813
+ }, z.core.$strip>>>;
2814
+ orTag: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2815
+ writeConcern: z.ZodOptional<z.ZodEnum<{
2816
+ FIRE_AND_FORGET: "FIRE_AND_FORGET";
2817
+ MEMORY: "MEMORY";
2818
+ APPLIED: "APPLIED";
2819
+ REPLICATED: "REPLICATED";
2820
+ PERSISTED: "PERSISTED";
2821
+ }>>;
2822
+ timeout: z.ZodOptional<z.ZodNumber>;
2823
+ }, z.core.$strip>>>;
2824
+ syncMaps: z.ZodOptional<z.ZodArray<z.ZodObject<{
2825
+ mapName: z.ZodString;
2826
+ lastSyncTimestamp: z.ZodObject<{
2827
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2828
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2829
+ nodeId: z.ZodString;
2830
+ }, z.core.$strip>;
2831
+ }, z.core.$strip>>>;
2832
+ queries: z.ZodOptional<z.ZodArray<z.ZodObject<{
2833
+ queryId: z.ZodString;
2834
+ mapName: z.ZodString;
2835
+ filter: z.ZodAny;
2836
+ limit: z.ZodOptional<z.ZodNumber>;
2837
+ offset: z.ZodOptional<z.ZodNumber>;
2838
+ }, z.core.$strip>>>;
2839
+ searches: z.ZodOptional<z.ZodArray<z.ZodObject<{
2840
+ searchId: z.ZodString;
2841
+ mapName: z.ZodString;
2842
+ query: z.ZodString;
2843
+ options: z.ZodOptional<z.ZodAny>;
2844
+ }, z.core.$strip>>>;
2845
+ }, z.core.$strip>;
2846
+ type HttpSyncRequest = z.infer<typeof HttpSyncRequestSchema>;
2847
+ /**
2848
+ * Delta record for a single key within a map.
2849
+ */
2850
+ declare const DeltaRecordSchema: z.ZodObject<{
2851
+ key: z.ZodString;
2852
+ record: z.ZodObject<{
2853
+ value: z.ZodNullable<z.ZodAny>;
2854
+ timestamp: z.ZodObject<{
2855
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2856
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2857
+ nodeId: z.ZodString;
2858
+ }, z.core.$strip>;
2859
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2860
+ }, z.core.$strip>;
2861
+ eventType: z.ZodEnum<{
2862
+ PUT: "PUT";
2863
+ REMOVE: "REMOVE";
2864
+ }>;
2865
+ }, z.core.$strip>;
2866
+ /**
2867
+ * Delta records for a specific map, containing all new/changed records
2868
+ * since the client's lastSyncTimestamp.
2869
+ */
2870
+ declare const MapDeltaSchema: z.ZodObject<{
2871
+ mapName: z.ZodString;
2872
+ records: z.ZodArray<z.ZodObject<{
2873
+ key: z.ZodString;
2874
+ record: z.ZodObject<{
2875
+ value: z.ZodNullable<z.ZodAny>;
2876
+ timestamp: z.ZodObject<{
2877
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2878
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2879
+ nodeId: z.ZodString;
2880
+ }, z.core.$strip>;
2881
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2882
+ }, z.core.$strip>;
2883
+ eventType: z.ZodEnum<{
2884
+ PUT: "PUT";
2885
+ REMOVE: "REMOVE";
2886
+ }>;
2887
+ }, z.core.$strip>>;
2888
+ serverSyncTimestamp: z.ZodObject<{
2889
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2890
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2891
+ nodeId: z.ZodString;
2892
+ }, z.core.$strip>;
2893
+ }, z.core.$strip>;
2894
+ /**
2895
+ * Query result for a one-shot HTTP query.
2896
+ */
2897
+ declare const HttpQueryResultSchema: z.ZodObject<{
2898
+ queryId: z.ZodString;
2899
+ results: z.ZodArray<z.ZodAny>;
2900
+ hasMore: z.ZodOptional<z.ZodBoolean>;
2901
+ nextCursor: z.ZodOptional<z.ZodString>;
2902
+ }, z.core.$strip>;
2903
+ /**
2904
+ * Search result for a one-shot HTTP search.
2905
+ */
2906
+ declare const HttpSearchResultSchema: z.ZodObject<{
2907
+ searchId: z.ZodString;
2908
+ results: z.ZodArray<z.ZodAny>;
2909
+ totalCount: z.ZodOptional<z.ZodNumber>;
2910
+ }, z.core.$strip>;
2911
+ /**
2912
+ * Error entry for individual operation failures.
2913
+ */
2914
+ declare const HttpSyncErrorSchema: z.ZodObject<{
2915
+ code: z.ZodNumber;
2916
+ message: z.ZodString;
2917
+ context: z.ZodOptional<z.ZodString>;
2918
+ }, z.core.$strip>;
2919
+ /**
2920
+ * HTTP sync response returned by the server for POST /sync.
2921
+ * Contains operation acknowledgments, delta records, query/search results,
2922
+ * and the server's current HLC for the client to use in subsequent requests.
2923
+ */
2924
+ declare const HttpSyncResponseSchema: z.ZodObject<{
2925
+ serverHlc: z.ZodObject<{
2926
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2927
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2928
+ nodeId: z.ZodString;
2929
+ }, z.core.$strip>;
2930
+ ack: z.ZodOptional<z.ZodObject<{
2931
+ lastId: z.ZodString;
2932
+ results: z.ZodOptional<z.ZodArray<z.ZodObject<{
2933
+ opId: z.ZodString;
2934
+ success: z.ZodBoolean;
2935
+ achievedLevel: z.ZodEnum<{
2936
+ FIRE_AND_FORGET: "FIRE_AND_FORGET";
2937
+ MEMORY: "MEMORY";
2938
+ APPLIED: "APPLIED";
2939
+ REPLICATED: "REPLICATED";
2940
+ PERSISTED: "PERSISTED";
2941
+ }>;
2942
+ error: z.ZodOptional<z.ZodString>;
2943
+ }, z.core.$strip>>>;
2944
+ }, z.core.$strip>>;
2945
+ deltas: z.ZodOptional<z.ZodArray<z.ZodObject<{
2946
+ mapName: z.ZodString;
2947
+ records: z.ZodArray<z.ZodObject<{
2948
+ key: z.ZodString;
2949
+ record: z.ZodObject<{
2950
+ value: z.ZodNullable<z.ZodAny>;
2951
+ timestamp: z.ZodObject<{
2952
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2953
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2954
+ nodeId: z.ZodString;
2955
+ }, z.core.$strip>;
2956
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2957
+ }, z.core.$strip>;
2958
+ eventType: z.ZodEnum<{
2959
+ PUT: "PUT";
2960
+ REMOVE: "REMOVE";
2961
+ }>;
2962
+ }, z.core.$strip>>;
2963
+ serverSyncTimestamp: z.ZodObject<{
2964
+ millis: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2965
+ counter: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodBigInt]>, z.ZodTransform<number, number | bigint>>;
2966
+ nodeId: z.ZodString;
2967
+ }, z.core.$strip>;
2968
+ }, z.core.$strip>>>;
2969
+ queryResults: z.ZodOptional<z.ZodArray<z.ZodObject<{
2970
+ queryId: z.ZodString;
2971
+ results: z.ZodArray<z.ZodAny>;
2972
+ hasMore: z.ZodOptional<z.ZodBoolean>;
2973
+ nextCursor: z.ZodOptional<z.ZodString>;
2974
+ }, z.core.$strip>>>;
2975
+ searchResults: z.ZodOptional<z.ZodArray<z.ZodObject<{
2976
+ searchId: z.ZodString;
2977
+ results: z.ZodArray<z.ZodAny>;
2978
+ totalCount: z.ZodOptional<z.ZodNumber>;
2979
+ }, z.core.$strip>>>;
2980
+ errors: z.ZodOptional<z.ZodArray<z.ZodObject<{
2981
+ code: z.ZodNumber;
2982
+ message: z.ZodString;
2983
+ context: z.ZodOptional<z.ZodString>;
2984
+ }, z.core.$strip>>>;
2985
+ }, z.core.$strip>;
2986
+ type HttpSyncResponse = z.infer<typeof HttpSyncResponseSchema>;
2987
+
2729
2988
  declare const MessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2730
2989
  type: z.ZodLiteral<"AUTH">;
2731
2990
  token: z.ZodString;
@@ -3291,7 +3550,6 @@ declare const MessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3291
3550
  subscriptionId: z.ZodString;
3292
3551
  }, z.core.$strip>;
3293
3552
  }, z.core.$strip>], "type">;
3294
- type Message = z.infer<typeof MessageSchema>;
3295
3553
 
3296
3554
  /**
3297
3555
  * Write Concern - Configurable Acknowledgment Levels
@@ -4401,12 +4659,34 @@ interface QueryOptions {
4401
4659
  limit?: number;
4402
4660
  /** Cursor for pagination (replaces offset) */
4403
4661
  cursor?: string;
4662
+ /** Force use of an index on this attribute name. Throws if no index exists for the attribute. */
4663
+ useIndex?: string;
4664
+ /** Require that the query plan uses at least one index. Throws if plan would be a full scan. */
4665
+ forceIndexScan?: boolean;
4666
+ /** Skip all optimization; produce a full-scan plan. Useful for debugging. */
4667
+ disableOptimization?: boolean;
4668
+ }
4669
+ /**
4670
+ * Point lookup step - O(1) direct key access.
4671
+ */
4672
+ interface PointLookupStep {
4673
+ type: 'point-lookup';
4674
+ key: unknown;
4675
+ cost: number;
4676
+ }
4677
+ /**
4678
+ * Multi-point lookup step - O(k) direct key access for k keys.
4679
+ */
4680
+ interface MultiPointLookupStep {
4681
+ type: 'multi-point-lookup';
4682
+ keys: unknown[];
4683
+ cost: number;
4404
4684
  }
4405
4685
  /**
4406
4686
  * Execution plan step.
4407
4687
  * Represents a single operation in the query execution plan.
4408
4688
  */
4409
- type PlanStep = IndexScanStep | FullScanStep | IntersectionStep | UnionStep | FilterStep | NotStep | FTSScanStep | FusionStep;
4689
+ type PlanStep = PointLookupStep | MultiPointLookupStep | IndexScanStep | FullScanStep | IntersectionStep | UnionStep | FilterStep | NotStep | FTSScanStep | FusionStep;
4410
4690
  /**
4411
4691
  * Index scan step - retrieves from an index.
4412
4692
  */
@@ -4508,7 +4788,56 @@ interface QueryPlan {
4508
4788
  limit?: number;
4509
4789
  /** Cursor for pagination (replaces offset) */
4510
4790
  cursor?: string;
4511
- }
4791
+ /** Index hint that was applied (attribute name from useIndex option) */
4792
+ hint?: string;
4793
+ }
4794
+ /**
4795
+ * Query execution context for distributed cost estimation.
4796
+ */
4797
+ interface QueryContext {
4798
+ /** Whether query executes in distributed mode */
4799
+ isDistributed: boolean;
4800
+ /** Number of nodes in cluster */
4801
+ nodeCount: number;
4802
+ /** Whether query uses PostgreSQL storage */
4803
+ usesStorage: boolean;
4804
+ /** Local node ID for partition ownership checks */
4805
+ localNodeId?: string;
4806
+ /** Partition ownership map: partitionId -> ownerNodeId */
4807
+ partitionOwners?: Map<number, string>;
4808
+ }
4809
+ /**
4810
+ * Distributed query cost model.
4811
+ * Inspired by Hazelcast CostUtils.java
4812
+ */
4813
+ interface DistributedCost {
4814
+ /** Estimated number of rows */
4815
+ rows: number;
4816
+ /** CPU cost (computation) */
4817
+ cpu: number;
4818
+ /** Network cost (data transfer between nodes) */
4819
+ network: number;
4820
+ /** I/O cost (disk reads for PostgreSQL) */
4821
+ io: number;
4822
+ }
4823
+ /**
4824
+ * Cost multipliers for distributed query optimization.
4825
+ * Network is weighted 10x higher than CPU because network latency
4826
+ * typically dominates query execution time in distributed systems.
4827
+ */
4828
+ declare const COST_WEIGHTS: {
4829
+ readonly CPU: 1;
4830
+ readonly NETWORK: 10;
4831
+ readonly IO: 5;
4832
+ readonly ROWS: 0.001;
4833
+ };
4834
+ /**
4835
+ * Calculate total cost from distributed cost components.
4836
+ *
4837
+ * @param cost - Distributed cost breakdown
4838
+ * @returns Weighted total cost
4839
+ */
4840
+ declare function calculateTotalCost(cost: DistributedCost): number;
4512
4841
  /**
4513
4842
  * Check if a query is a simple query node.
4514
4843
  */
@@ -7063,21 +7392,54 @@ declare class QueryOptimizer<K, V> {
7063
7392
  * Optimize a query and return an execution plan.
7064
7393
  *
7065
7394
  * Optimization order (by cost):
7066
- * 1. StandingQueryIndex (cost: 10) - pre-computed results
7067
- * 2. Other indexes via optimizeNode
7395
+ * 1. Point lookup (cost: 1) - direct primary key access
7396
+ * 2. StandingQueryIndex (cost: 10) - pre-computed results
7397
+ * 3. Other indexes via optimizeNode
7068
7398
  *
7069
7399
  * @param query - Query to optimize
7070
7400
  * @returns Query execution plan
7071
7401
  */
7072
7402
  optimize(query: Query): QueryPlan;
7073
7403
  /**
7074
- * Optimize a query with sort/limit/offset options.
7404
+ * Optimize a query with sort/limit/offset options and index hints.
7405
+ *
7406
+ * Hint precedence: disableOptimization > useIndex > forceIndexScan.
7075
7407
  *
7076
7408
  * @param query - Query to optimize
7077
- * @param options - Query options (sort, limit, offset)
7409
+ * @param options - Query options (sort, limit, cursor, hints)
7078
7410
  * @returns Query execution plan with options
7079
7411
  */
7080
7412
  optimizeWithOptions(query: Query, options: QueryOptions): QueryPlan;
7413
+ /**
7414
+ * Apply sort/limit/cursor options to a query plan.
7415
+ *
7416
+ * @param plan - Base query plan
7417
+ * @param options - Query options with sort/limit/cursor
7418
+ * @returns Plan with options applied
7419
+ */
7420
+ private applyPlanOptions;
7421
+ /**
7422
+ * Extract the relevant index query for a hinted attribute from the query tree.
7423
+ * If the query directly references the attribute, build an index query from it.
7424
+ * For compound (logical) queries, extract the matching child predicate.
7425
+ * Falls back to { type: 'has' } when no matching predicate is found,
7426
+ * retrieving all entries from the index for post-filtering.
7427
+ * FTS query nodes also fall back to { type: 'has' } since full-text search
7428
+ * queries are not compatible with regular index lookups.
7429
+ *
7430
+ * @param query - Original query tree
7431
+ * @param attributeName - Hinted attribute name
7432
+ * @returns Index query for the hinted attribute
7433
+ */
7434
+ private buildHintedIndexQuery;
7435
+ /**
7436
+ * Try to optimize query as a point lookup.
7437
+ * Returns a point lookup step if query is an equality or IN query on primary key.
7438
+ *
7439
+ * @param query - Query to check
7440
+ * @returns Point lookup step or null
7441
+ */
7442
+ private tryPointLookup;
7081
7443
  /**
7082
7444
  * Optimize a single query node.
7083
7445
  */
@@ -7178,6 +7540,29 @@ declare class QueryOptimizer<K, V> {
7178
7540
  * Estimate the execution cost of a plan step.
7179
7541
  */
7180
7542
  private estimateCost;
7543
+ /**
7544
+ * Estimate distributed cost including network overhead.
7545
+ *
7546
+ * Network cost is assigned based on step type:
7547
+ * - full-scan: broadcast to all nodes (highest cost)
7548
+ * - index-scan: 0 if local partition, 5 if remote
7549
+ * - point-lookup: 0 if local key, 5 if remote
7550
+ * - intersection/union: aggregating results from multiple sources
7551
+ *
7552
+ * @param step - Plan step to estimate
7553
+ * @param context - Distributed query context (optional)
7554
+ * @returns Distributed cost breakdown
7555
+ */
7556
+ estimateDistributedCost(step: PlanStep, context?: QueryContext): DistributedCost;
7557
+ /**
7558
+ * Get total distributed cost for a plan step.
7559
+ * Convenience method combining estimateDistributedCost and calculateTotalCost.
7560
+ *
7561
+ * @param step - Plan step to estimate
7562
+ * @param context - Distributed query context (optional)
7563
+ * @returns Weighted total cost
7564
+ */
7565
+ getTotalDistributedCost(step: PlanStep, context?: QueryContext): number;
7181
7566
  /**
7182
7567
  * Check if a plan step uses any indexes.
7183
7568
  */
@@ -9312,4 +9697,366 @@ declare class SearchDebugger {
9312
9697
  declare function getSearchDebugger(): SearchDebugger;
9313
9698
  declare function resetSearchDebugger(): void;
9314
9699
 
9315
- export { type Attribute, type AuthFailMessage, AuthFailMessageSchema, AuthMessageSchema, type BM25DebugInfo, type BM25Options, BM25Scorer, type BatchMessage, BatchMessageSchema, BuiltInProcessors, BuiltInResolvers, CRDTDebugger, type CRDTSnapshot, type CircuitBreakerConfig, type ClientOp, ClientOpMessageSchema, ClientOpSchema, type ClusterClientConfig, type ClusterEvents, type ReadOptions as ClusterReadOptions, type ClusterSearchReqMessage, ClusterSearchReqMessageSchema, type ClusterSearchReqPayload, ClusterSearchReqPayloadSchema, type ClusterSearchRespMessage, ClusterSearchRespMessageSchema, type ClusterSearchRespPayload, ClusterSearchRespPayloadSchema, type ClusterSearchSubscribeMessage, ClusterSearchSubscribeMessageSchema, type ClusterSearchSubscribePayload, ClusterSearchSubscribePayloadSchema, type ClusterSearchUnsubscribeMessage, ClusterSearchUnsubscribeMessageSchema, type ClusterSearchUnsubscribePayload, ClusterSearchUnsubscribePayloadSchema, type ClusterSearchUpdateMessage, ClusterSearchUpdateMessageSchema, type ClusterSearchUpdatePayload, ClusterSearchUpdatePayloadSchema, type ClusterSubAckMessage, ClusterSubAckMessageSchema, type ClusterSubAckPayload, ClusterSubAckPayloadSchema, type ClusterSubRegisterMessage, ClusterSubRegisterMessageSchema, type ClusterSubRegisterPayload, ClusterSubRegisterPayloadSchema, type ClusterSubUnregisterMessage, ClusterSubUnregisterMessageSchema, type ClusterSubUnregisterPayload, ClusterSubUnregisterPayloadSchema, type ClusterSubUpdateMessage, ClusterSubUpdateMessageSchema, type ClusterSubUpdatePayload, ClusterSubUpdatePayloadSchema, type WriteOptions as ClusterWriteOptions, type CompareFn, type ConflictInfo, type ConflictResolver, type ConflictResolverDef, ConflictResolverDefSchema, type ConflictResolverFn, ConflictResolverSchema, type ConnectionPoolConfig, type ConnectionState, ConsistencyLevel, CounterRequestSchema, CounterResponseSchema, CounterSyncSchema, CounterUpdateSchema, type CursorStatus$1 as CursorStatus, CursorStatusSchema, type CursorableQueryResult, type CursorableResult, DEFAULT_BACKUP_COUNT, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONNECTION_POOL_CONFIG, DEFAULT_CURSOR_MAX_AGE_MS, DEFAULT_EVENT_JOURNAL_CONFIG, DEFAULT_MIGRATION_CONFIG, DEFAULT_PARTITION_ROUTER_CONFIG, DEFAULT_PROCESSOR_RATE_LIMITS, DEFAULT_QUERY_CURSOR_MAX_AGE_MS, DEFAULT_REPLICATION_CONFIG, DEFAULT_RESOLVER_RATE_LIMITS, DEFAULT_STOP_WORDS, DEFAULT_WRITE_CONCERN_TIMEOUT, type DebugStatistics, ENGLISH_STOPWORDS, type EntryProcessBatchRequest, EntryProcessBatchRequestSchema, type EntryProcessBatchResponse, EntryProcessBatchResponseSchema, type EntryProcessKeyResult, EntryProcessKeyResultSchema, type EntryProcessRequest, EntryProcessRequestSchema, type EntryProcessResponse, EntryProcessResponseSchema, type EntryProcessorDef, EntryProcessorDefSchema, type EntryProcessorFn, type EntryProcessorResult, EntryProcessorSchema, type EventJournal, type EventJournalConfig, EventJournalImpl, type ExactMatchDebugInfo, FORBIDDEN_PATTERNS, BM25InvertedIndex as FTSInvertedIndex, type SearchOptions as FTSSearchOptions, type SearchResult as FTSSearchResult, BM25Tokenizer as FTSTokenizer, type TokenizerOptions as FTSTokenizerOptions, FallbackIndex, type FilterStep, FilteringResultSet, type FullScanStep, FullTextIndex, type FullTextIndexConfig, type GcPruneMessage, GcPruneMessageSchema, type GcPrunePayload, GcPrunePayloadSchema, HLC, HashIndex, type HybridQueryDeltaPayload, HybridQueryDeltaPayloadSchema, type HybridQueryRespPayload, HybridQueryRespPayloadSchema, type Index, type IndexQuery, IndexRegistry, type IndexRegistryStats, type IndexScanStep, type IndexStats, IndexedLWWMap, IndexedORMap, IntersectionResultSet, type IntersectionStep, InvertedIndex, type InvertedIndexStats, type IteratorFactory, type JournalEvent, type JournalEventData, JournalEventDataSchema, type JournalEventInput, type JournalEventListener, type JournalEventMessage, JournalEventMessageSchema, type JournalEventType, JournalEventTypeSchema, type JournalReadRequest, JournalReadRequestSchema, type JournalReadResponse, JournalReadResponseSchema, type JournalSubscribeRequest, JournalSubscribeRequestSchema, type JournalUnsubscribeRequest, JournalUnsubscribeRequestSchema, LWWMap, type LWWRecord, LWWRecordSchema, LazyResultSet, LimitResultSet, type ListResolversRequest, ListResolversRequestSchema, type ListResolversResponse, ListResolversResponseSchema, type LiveQueryCallback, type LiveQueryDeltaEvent, type LiveQueryEvent, type LiveQueryInitialEvent, LiveQueryManager, type LiveQueryManagerOptions, type LiveQueryManagerStats, type LockGrantedPayload, LockGrantedPayloadSchema, LockReleaseSchema, type LockReleasedPayload, LockReleasedPayloadSchema, LockRequestSchema, type Logger, type LogicalQueryNode, LowercaseFilter, type MatchOptions, MaxLengthFilter, type MergeContext, type MergeKeyResult, type MergeRejectedMessage, MergeRejectedMessageSchema, type MergeRejection, type MergeResult, type MergedResult, MerkleReqBucketMessageSchema, MerkleTree, type Message, MessageSchema, type MigrationChunkAckMessage, type MigrationChunkMessage, type MigrationCompleteMessage, type MigrationConfig, type MigrationMessage, type MigrationMetrics, type MigrationStartMessage, type MigrationStatus, type MigrationVerifyMessage, MinLengthFilter, MultiValueAttribute, NGramTokenizer, NavigableIndex, type NodeHealth, type NodeInfo, type NodeStatus, type NotOwnerError, type NotStep, ORMap, ORMapDiffRequestSchema, type ORMapDiffResponsePayload, ORMapDiffResponseSchema, type ORMapMerkleNode, ORMapMerkleReqBucketSchema, ORMapMerkleTree, ORMapPushDiffSchema, type ORMapQueryResult, type ORMapRecord, ORMapRecordSchema, type ORMapSearchResult, type ORMapSnapshot, ORMapSyncInitSchema, type ORMapSyncRespBucketsPayload, ORMapSyncRespBucketsSchema, type ORMapSyncRespLeafPayload, ORMapSyncRespLeafSchema, type ORMapSyncRespRootPayload, ORMapSyncRespRootSchema, type OpAckMessage, OpAckMessageSchema, OpBatchMessageSchema, type OpRejectedMessage, OpRejectedMessageSchema, type OpResult, OpResultSchema, type OperationQueryOptions, PARTITION_COUNT, type PNCounter, type PNCounterConfig, PNCounterImpl, type PNCounterState, type PNCounterStateObject, PNCounterStateObjectSchema, type PartitionChange, type PartitionInfo, type PartitionMap, type PartitionMapDeltaMessage, type PartitionMapMessage, type PartitionMapRequestMessage, PartitionMapRequestSchema, type PartitionMigration, type PartitionRouterConfig, PartitionState, type PendingWrite, type PermissionPolicy, type PermissionType, type PingMessage, PingMessageSchema, type PlanStep, type PongMessage, PongMessageSchema, type Posting, type PredicateFn, type PredicateNode, PredicateNodeSchema, type PredicateOp, PredicateOpSchema, Predicates, type Principal, type ProcessorRateLimitConfig, type Query$1 as Query, QueryCursor, type QueryCursorData, type QueryCursorOptions, type Query as QueryExpression, type QueryNode, QueryOptimizer, type QueryOptimizerOptions, type QueryOptions, type QueryPlan, type QueryRespMessage, QueryRespMessageSchema, type QueryRespPayload, QueryRespPayloadSchema, type QueryResultWithCursor, QuerySchema, QuerySubMessageSchema, QueryUnsubMessageSchema, type QueryUpdateMessage, QueryUpdateMessageSchema, type QueryUpdatePayload, QueryUpdatePayloadSchema, RESOLVER_FORBIDDEN_PATTERNS, type RRFConfig, type RRFDebugInfo, type RankedResult, ReciprocalRankFusion, type RegisterResolverRequest, RegisterResolverRequestSchema, type RegisterResolverResponse, RegisterResolverResponseSchema, type ReplicationAckMessage, type ReplicationBatchAckMessage, type ReplicationBatchMessage, type ReplicationConfig, type ReplicationHealth, type ReplicationLag, type ReplicationMessage, type ReplicationProtocolMessage, type ReplicationResult, type ReplicationTask, type ResolverRateLimitConfig, type ResultSet, Ringbuffer, type RoutingError, type ScoredDocument, SearchCursor, type SearchCursorData, type SearchDebugInfo, SearchDebugger, type SearchIndexStats, type SearchMessage, SearchMessageSchema, type SearchOptions$1 as SearchOptions, SearchOptionsSchema, type SearchPayload, SearchPayloadSchema, type SearchRespMessage, SearchRespMessageSchema, type SearchRespPayload, SearchRespPayloadSchema, type SearchResultDebug, type SearchSubMessage, SearchSubMessageSchema, type SearchSubPayload, SearchSubPayloadSchema, type SearchTiming, type SearchUnsubMessage, SearchUnsubMessageSchema, type SearchUnsubPayload, SearchUnsubPayloadSchema, type SearchUpdateMessage, SearchUpdateMessageSchema, type SearchUpdatePayload, SearchUpdatePayloadSchema, type SearchUpdateType, SearchUpdateTypeSchema, type SerializedIndex, type ServerBatchEventMessage, ServerBatchEventMessageSchema, type ServerEventMessage, ServerEventMessageSchema, type ServerEventPayload, ServerEventPayloadSchema, SetResultSet, SimpleAttribute, type SimpleQueryNode, SortedMap, SortedResultSet, type StaleMapError, type StandingQueryChange, StandingQueryIndex, type StandingQueryIndexOptions, StandingQueryRegistry, type StandingQueryRegistryOptions, type StandingQueryRegistryStats, StopWordFilter, SyncInitMessageSchema, type SyncResetRequiredPayload, SyncResetRequiredPayloadSchema, SyncRespBucketsMessageSchema, type SyncRespBucketsPayload, SyncRespLeafMessageSchema, type SyncRespLeafPayload, SyncRespRootMessageSchema, type SyncRespRootPayload, type TermInfo, type Timestamp, TimestampSchema, type TokenFilter, TokenizationPipeline, type TokenizationPipelineOptions, type Tokenizer, TopicMessageEventSchema, TopicPubSchema, TopicSubSchema, TopicUnsubSchema, TrimFilter, UnionResultSet, type UnionStep, UniqueFilter, type UnregisterResolverRequest, UnregisterResolverRequestSchema, type UnregisterResolverResponse, UnregisterResolverResponseSchema, type VectorDebugInfo, WRITE_CONCERN_ORDER, WhitespaceTokenizer, WordBoundaryTokenizer, WriteConcern, WriteConcernSchema, type WriteConcernValue, type WriteOptions$1 as WriteOptions, type WriteResult, combineHashes, compareHLCTimestamps, compareTimestamps, compareValues, createFieldComparator, createPredicateMatcher, decodeBase64Url, deepMerge, deserialize, disableNativeHash, encodeBase64Url, evaluatePredicate, getCRDTDebugger, getHighestWriteConcernLevel, getSearchDebugger, hashORMapEntry, hashORMapRecord, hashObject, hashString, isLogicalQuery, isSimpleQuery, isUsingNativeHash, isWriteConcernAchieved, logger, multiAttribute, porterStem, resetCRDTDebugger, resetNativeHash, resetSearchDebugger, serialize, simpleAttribute, timestampToString, validateProcessorCode, validateResolverCode };
9700
+ /**
9701
+ * Real clock source using system time.
9702
+ */
9703
+ declare const RealClock: ClockSource;
9704
+ /**
9705
+ * Virtual clock for deterministic testing.
9706
+ * Time only advances when explicitly requested via advance() or set().
9707
+ *
9708
+ * Usage:
9709
+ * ```typescript
9710
+ * const clock = new VirtualClock(1000000);
9711
+ * clock.now(); // 1000000
9712
+ * clock.advance(500);
9713
+ * clock.now(); // 1000500
9714
+ * ```
9715
+ */
9716
+ declare class VirtualClock implements ClockSource {
9717
+ private currentTime;
9718
+ /**
9719
+ * @param initialTime Starting timestamp in milliseconds (default: 0)
9720
+ */
9721
+ constructor(initialTime?: number);
9722
+ /**
9723
+ * Returns the current virtual time.
9724
+ * Time remains frozen until advance() or set() is called.
9725
+ */
9726
+ now(): number;
9727
+ /**
9728
+ * Advances time forward by the specified milliseconds.
9729
+ * @param ms Milliseconds to advance (must be non-negative)
9730
+ */
9731
+ advance(ms: number): void;
9732
+ /**
9733
+ * Sets the clock to a specific time.
9734
+ * Allows moving time forward or backward (useful for testing).
9735
+ * @param time Absolute timestamp in milliseconds
9736
+ */
9737
+ set(time: number): void;
9738
+ /**
9739
+ * Resets the clock to zero.
9740
+ */
9741
+ reset(): void;
9742
+ }
9743
+
9744
+ /**
9745
+ * Seeded pseudo-random number generator for deterministic testing.
9746
+ * Uses the mulberry32 algorithm for fast, high-quality randomness.
9747
+ *
9748
+ * Usage:
9749
+ * ```typescript
9750
+ * const rng = new SeededRNG(12345);
9751
+ * rng.random(); // 0.6011..., always same for seed 12345
9752
+ * rng.randomInt(1, 10); // Deterministic integer in range
9753
+ * ```
9754
+ */
9755
+ declare class SeededRNG {
9756
+ private state;
9757
+ private readonly originalSeed;
9758
+ /**
9759
+ * @param seed Integer seed value. Same seed = same sequence.
9760
+ */
9761
+ constructor(seed: number);
9762
+ /**
9763
+ * Returns the original seed used to construct this RNG.
9764
+ */
9765
+ getSeed(): number;
9766
+ /**
9767
+ * Generates the next random number in [0, 1).
9768
+ * Uses mulberry32 algorithm for deterministic, high-quality randomness.
9769
+ */
9770
+ random(): number;
9771
+ /**
9772
+ * Generates a random integer in [min, max] (inclusive).
9773
+ * @param min Minimum value (inclusive)
9774
+ * @param max Maximum value (inclusive)
9775
+ */
9776
+ randomInt(min: number, max: number): number;
9777
+ /**
9778
+ * Generates a random boolean value.
9779
+ * @param probability Probability of returning true (default: 0.5)
9780
+ */
9781
+ randomBool(probability?: number): boolean;
9782
+ /**
9783
+ * Shuffles an array in place using Fisher-Yates algorithm.
9784
+ * Returns the shuffled array.
9785
+ * @param array Array to shuffle
9786
+ */
9787
+ shuffle<T>(array: T[]): T[];
9788
+ /**
9789
+ * Picks a random element from an array.
9790
+ * @param array Array to pick from
9791
+ * @returns Random element, or undefined if array is empty
9792
+ */
9793
+ pick<T>(array: T[]): T | undefined;
9794
+ /**
9795
+ * Resets the RNG to its original seed.
9796
+ * Useful for reproducing a sequence from the start.
9797
+ */
9798
+ reset(): void;
9799
+ }
9800
+
9801
+ /**
9802
+ * Network configuration for chaos injection.
9803
+ */
9804
+ interface NetworkConfig {
9805
+ /** Latency range in milliseconds */
9806
+ latencyMs: {
9807
+ min: number;
9808
+ max: number;
9809
+ };
9810
+ /** Packet loss rate (0.0 to 1.0) */
9811
+ packetLossRate: number;
9812
+ /** Groups that cannot communicate with each other */
9813
+ partitions: string[][];
9814
+ }
9815
+ /**
9816
+ * A message in flight through the virtual network.
9817
+ */
9818
+ interface Message {
9819
+ from: string;
9820
+ to: string;
9821
+ payload: unknown;
9822
+ scheduledTime: number;
9823
+ }
9824
+ /**
9825
+ * Virtual network for deterministic chaos testing.
9826
+ * Simulates packet loss, latency, and network partitions.
9827
+ *
9828
+ * Usage:
9829
+ * ```typescript
9830
+ * const rng = new SeededRNG(123);
9831
+ * const clock = new VirtualClock(1000);
9832
+ * const network = new VirtualNetwork(rng, clock);
9833
+ *
9834
+ * network.configure({ packetLossRate: 0.1, latencyMs: { min: 10, max: 50 } });
9835
+ * network.send('node-a', 'node-b', { type: 'sync' });
9836
+ *
9837
+ * clock.advance(30);
9838
+ * const delivered = network.tick(); // Messages delivered at current time
9839
+ * ```
9840
+ */
9841
+ declare class VirtualNetwork {
9842
+ private readonly rng;
9843
+ private readonly clock;
9844
+ private config;
9845
+ private pendingMessages;
9846
+ constructor(rng: SeededRNG, clock: VirtualClock);
9847
+ /**
9848
+ * Updates network configuration.
9849
+ * Partially updates existing config with provided values.
9850
+ */
9851
+ configure(config: Partial<NetworkConfig>): void;
9852
+ /**
9853
+ * Sends a message through the network.
9854
+ * Subject to packet loss, latency, and partition rules.
9855
+ */
9856
+ send(from: string, to: string, payload: unknown): void;
9857
+ /**
9858
+ * Creates a network partition between two groups.
9859
+ * Nodes in groupA cannot communicate with nodes in groupB.
9860
+ */
9861
+ partition(groupA: string[], groupB: string[]): void;
9862
+ /**
9863
+ * Removes all network partitions.
9864
+ */
9865
+ heal(): void;
9866
+ /**
9867
+ * Delivers all messages scheduled at or before the current time.
9868
+ * @returns Array of delivered messages
9869
+ */
9870
+ tick(): Message[];
9871
+ /**
9872
+ * Returns the number of messages currently in flight.
9873
+ */
9874
+ getPendingCount(): number;
9875
+ /**
9876
+ * Clears all pending messages.
9877
+ */
9878
+ clear(): void;
9879
+ /**
9880
+ * Checks if two nodes are partitioned from each other.
9881
+ */
9882
+ private isPartitioned;
9883
+ /**
9884
+ * Returns all pending messages (useful for debugging).
9885
+ */
9886
+ getPendingMessages(): Message[];
9887
+ }
9888
+
9889
+ /**
9890
+ * Invariant function signature.
9891
+ * Returns true if the invariant holds, false otherwise.
9892
+ */
9893
+ type Invariant<T> = (state: T) => boolean;
9894
+ /**
9895
+ * Result of invariant verification.
9896
+ */
9897
+ interface InvariantResult {
9898
+ passed: boolean;
9899
+ failures: string[];
9900
+ }
9901
+ /**
9902
+ * Checker for property-based invariants.
9903
+ * Used to verify CRDT consistency during simulation.
9904
+ *
9905
+ * Usage:
9906
+ * ```typescript
9907
+ * const checker = new InvariantChecker<MyState>();
9908
+ * checker.addInvariant('no-nulls', (state) => state.value !== null);
9909
+ * const result = checker.verify(state);
9910
+ * if (!result.passed) {
9911
+ * console.log('Failures:', result.failures);
9912
+ * }
9913
+ * ```
9914
+ */
9915
+ declare class InvariantChecker<T> {
9916
+ private invariants;
9917
+ /**
9918
+ * Adds an invariant to be checked.
9919
+ * @param name Unique name for this invariant
9920
+ * @param check Function that returns true if invariant holds
9921
+ */
9922
+ addInvariant(name: string, check: Invariant<T>): void;
9923
+ /**
9924
+ * Removes an invariant by name.
9925
+ */
9926
+ removeInvariant(name: string): boolean;
9927
+ /**
9928
+ * Verifies all invariants against the provided state.
9929
+ * @returns Result with pass/fail status and list of failed invariants
9930
+ */
9931
+ verify(state: T): InvariantResult;
9932
+ /**
9933
+ * Returns the number of registered invariants.
9934
+ */
9935
+ get count(): number;
9936
+ /**
9937
+ * Clears all invariants.
9938
+ */
9939
+ clear(): void;
9940
+ }
9941
+ /**
9942
+ * Predefined CRDT invariants for common testing scenarios.
9943
+ */
9944
+ declare const CRDTInvariants: {
9945
+ /**
9946
+ * Verifies LWW-Map convergence: all maps contain the same values for same keys.
9947
+ */
9948
+ lwwConvergence: <K, V>(maps: LWWMap<K, V>[]) => boolean;
9949
+ /**
9950
+ * Verifies OR-Map convergence: all maps contain the same values for same keys.
9951
+ */
9952
+ orMapConvergence: <K, V>(maps: ORMap<K, V>[]) => boolean;
9953
+ /**
9954
+ * Verifies HLC monotonicity: timestamps are strictly increasing.
9955
+ */
9956
+ hlcMonotonicity: (timestamps: Timestamp[]) => boolean;
9957
+ /**
9958
+ * Verifies Merkle tree consistency: trees with same data have same root hash.
9959
+ */
9960
+ merkleConsistency: (trees: MerkleTree[]) => boolean;
9961
+ };
9962
+
9963
+ /**
9964
+ * Configuration for a simulation scenario.
9965
+ */
9966
+ interface ScenarioConfig {
9967
+ /** Random seed for reproducibility (auto-generated if not provided) */
9968
+ seed?: number;
9969
+ /** List of node identifiers participating in the scenario */
9970
+ nodes: string[];
9971
+ /** Total duration in virtual milliseconds */
9972
+ duration: number;
9973
+ /** Virtual ms to advance per tick (default: 1) */
9974
+ tickInterval?: number;
9975
+ }
9976
+ /**
9977
+ * Result of a scenario execution.
9978
+ */
9979
+ interface ScenarioResult {
9980
+ /** Seed used for this run (for reproduction) */
9981
+ seed: number;
9982
+ /** Whether all invariants passed */
9983
+ passed: boolean;
9984
+ /** Number of ticks executed */
9985
+ ticks: number;
9986
+ /** List of invariant failures */
9987
+ invariantFailures: string[];
9988
+ /** Final state captured at end of scenario */
9989
+ finalStates: Map<string, unknown>;
9990
+ }
9991
+ /**
9992
+ * Orchestrates deterministic simulation scenarios.
9993
+ * Combines virtual clock, seeded RNG, and virtual network for reproducible testing.
9994
+ *
9995
+ * Usage:
9996
+ * ```typescript
9997
+ * const runner = new ScenarioRunner({
9998
+ * seed: 12345,
9999
+ * nodes: ['node-a', 'node-b'],
10000
+ * duration: 1000
10001
+ * });
10002
+ *
10003
+ * const result = runner.run(
10004
+ * (r) => {
10005
+ * // Setup: create CRDTs, configure network
10006
+ * r.getNetwork().configure({ packetLossRate: 0.1 });
10007
+ * },
10008
+ * (r, tick) => {
10009
+ * // Step: simulate operations, deliver messages
10010
+ * if (tick === 500) r.getNetwork().heal();
10011
+ * },
10012
+ * invariants
10013
+ * );
10014
+ *
10015
+ * if (!result.passed) {
10016
+ * console.log(`Failed with seed ${result.seed}`);
10017
+ * }
10018
+ * ```
10019
+ */
10020
+ declare class ScenarioRunner {
10021
+ private readonly config;
10022
+ private readonly clock;
10023
+ private readonly rng;
10024
+ private readonly network;
10025
+ private readonly seed;
10026
+ constructor(config: ScenarioConfig);
10027
+ /**
10028
+ * Returns the seed used for this scenario.
10029
+ */
10030
+ getSeed(): number;
10031
+ /**
10032
+ * Returns the virtual clock instance.
10033
+ */
10034
+ getClock(): VirtualClock;
10035
+ /**
10036
+ * Returns the seeded RNG instance.
10037
+ */
10038
+ getRNG(): SeededRNG;
10039
+ /**
10040
+ * Returns the virtual network instance.
10041
+ */
10042
+ getNetwork(): VirtualNetwork;
10043
+ /**
10044
+ * Returns the list of nodes in this scenario.
10045
+ */
10046
+ getNodes(): string[];
10047
+ /**
10048
+ * Executes the simulation scenario.
10049
+ *
10050
+ * @param setup Called once before simulation starts. Initialize state here.
10051
+ * @param step Called on each tick. Perform operations and message delivery.
10052
+ * @param invariants Checker for verifying correctness throughout execution.
10053
+ * @returns Result with pass/fail status and captured state
10054
+ */
10055
+ run(setup: (runner: ScenarioRunner) => void, step: (runner: ScenarioRunner, tick: number) => void, invariants: InvariantChecker<unknown>): ScenarioResult;
10056
+ /**
10057
+ * Stores state for a node (useful for capturing final state).
10058
+ */
10059
+ setState(nodeId: string, state: unknown): void;
10060
+ }
10061
+
10062
+ export { type Attribute, type AuthFailMessage, AuthFailMessageSchema, AuthMessageSchema, type BM25DebugInfo, type BM25Options, BM25Scorer, type BatchMessage, BatchMessageSchema, BuiltInProcessors, BuiltInResolvers, COST_WEIGHTS, CRDTDebugger, CRDTInvariants, type CRDTSnapshot, type CircuitBreakerConfig, type ClientOp, ClientOpMessageSchema, ClientOpSchema, type ClockSource, type ClusterClientConfig, type ClusterEvents, type ReadOptions as ClusterReadOptions, type ClusterSearchReqMessage, ClusterSearchReqMessageSchema, type ClusterSearchReqPayload, ClusterSearchReqPayloadSchema, type ClusterSearchRespMessage, ClusterSearchRespMessageSchema, type ClusterSearchRespPayload, ClusterSearchRespPayloadSchema, type ClusterSearchSubscribeMessage, ClusterSearchSubscribeMessageSchema, type ClusterSearchSubscribePayload, ClusterSearchSubscribePayloadSchema, type ClusterSearchUnsubscribeMessage, ClusterSearchUnsubscribeMessageSchema, type ClusterSearchUnsubscribePayload, ClusterSearchUnsubscribePayloadSchema, type ClusterSearchUpdateMessage, ClusterSearchUpdateMessageSchema, type ClusterSearchUpdatePayload, ClusterSearchUpdatePayloadSchema, type ClusterSubAckMessage, ClusterSubAckMessageSchema, type ClusterSubAckPayload, ClusterSubAckPayloadSchema, type ClusterSubRegisterMessage, ClusterSubRegisterMessageSchema, type ClusterSubRegisterPayload, ClusterSubRegisterPayloadSchema, type ClusterSubUnregisterMessage, ClusterSubUnregisterMessageSchema, type ClusterSubUnregisterPayload, ClusterSubUnregisterPayloadSchema, type ClusterSubUpdateMessage, ClusterSubUpdateMessageSchema, type ClusterSubUpdatePayload, ClusterSubUpdatePayloadSchema, type WriteOptions as ClusterWriteOptions, type CompareFn, type ConflictInfo, type ConflictResolver, type ConflictResolverDef, ConflictResolverDefSchema, type ConflictResolverFn, ConflictResolverSchema, type ConnectionPoolConfig, type ConnectionState, ConsistencyLevel, CounterRequestSchema, CounterResponseSchema, CounterSyncSchema, CounterUpdateSchema, type CursorStatus$1 as CursorStatus, CursorStatusSchema, type CursorableQueryResult, type CursorableResult, DEFAULT_BACKUP_COUNT, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONNECTION_POOL_CONFIG, DEFAULT_CURSOR_MAX_AGE_MS, DEFAULT_EVENT_JOURNAL_CONFIG, DEFAULT_MIGRATION_CONFIG, DEFAULT_PARTITION_ROUTER_CONFIG, DEFAULT_PROCESSOR_RATE_LIMITS, DEFAULT_QUERY_CURSOR_MAX_AGE_MS, DEFAULT_REPLICATION_CONFIG, DEFAULT_RESOLVER_RATE_LIMITS, DEFAULT_STOP_WORDS, DEFAULT_WRITE_CONCERN_TIMEOUT, type DebugStatistics, DeltaRecordSchema, type DistributedCost, ENGLISH_STOPWORDS, type EntryProcessBatchRequest, EntryProcessBatchRequestSchema, type EntryProcessBatchResponse, EntryProcessBatchResponseSchema, type EntryProcessKeyResult, EntryProcessKeyResultSchema, type EntryProcessRequest, EntryProcessRequestSchema, type EntryProcessResponse, EntryProcessResponseSchema, type EntryProcessorDef, EntryProcessorDefSchema, type EntryProcessorFn, type EntryProcessorResult, EntryProcessorSchema, type EventJournal, type EventJournalConfig, EventJournalImpl, type ExactMatchDebugInfo, FORBIDDEN_PATTERNS, BM25InvertedIndex as FTSInvertedIndex, type SearchOptions as FTSSearchOptions, type SearchResult as FTSSearchResult, BM25Tokenizer as FTSTokenizer, type TokenizerOptions as FTSTokenizerOptions, FallbackIndex, type FilterStep, FilteringResultSet, type FullScanStep, FullTextIndex, type FullTextIndexConfig, type GcPruneMessage, GcPruneMessageSchema, type GcPrunePayload, GcPrunePayloadSchema, HLC, HashIndex, HttpQueryRequestSchema, HttpQueryResultSchema, HttpSearchRequestSchema, HttpSearchResultSchema, HttpSyncErrorSchema, type HttpSyncRequest, HttpSyncRequestSchema, type HttpSyncResponse, HttpSyncResponseSchema, type HybridQueryDeltaPayload, HybridQueryDeltaPayloadSchema, type HybridQueryRespPayload, HybridQueryRespPayloadSchema, type Index, type IndexQuery, IndexRegistry, type IndexRegistryStats, type IndexScanStep, type IndexStats, IndexedLWWMap, IndexedORMap, IntersectionResultSet, type IntersectionStep, type Invariant, InvariantChecker, type InvariantResult, InvertedIndex, type InvertedIndexStats, type IteratorFactory, type JournalEvent, type JournalEventData, JournalEventDataSchema, type JournalEventInput, type JournalEventListener, type JournalEventMessage, JournalEventMessageSchema, type JournalEventType, JournalEventTypeSchema, type JournalReadRequest, JournalReadRequestSchema, type JournalReadResponse, JournalReadResponseSchema, type JournalSubscribeRequest, JournalSubscribeRequestSchema, type JournalUnsubscribeRequest, JournalUnsubscribeRequestSchema, LWWMap, type LWWRecord, LWWRecordSchema, LazyResultSet, LimitResultSet, type ListResolversRequest, ListResolversRequestSchema, type ListResolversResponse, ListResolversResponseSchema, type LiveQueryCallback, type LiveQueryDeltaEvent, type LiveQueryEvent, type LiveQueryInitialEvent, LiveQueryManager, type LiveQueryManagerOptions, type LiveQueryManagerStats, type LockGrantedPayload, LockGrantedPayloadSchema, LockReleaseSchema, type LockReleasedPayload, LockReleasedPayloadSchema, LockRequestSchema, type Logger, type LogicalQueryNode, LowercaseFilter, MapDeltaSchema, type MatchOptions, MaxLengthFilter, type MergeContext, type MergeKeyResult, type MergeRejectedMessage, MergeRejectedMessageSchema, type MergeRejection, type MergeResult, type MergedResult, MerkleReqBucketMessageSchema, MerkleTree, type Message, MessageSchema, type MigrationChunkAckMessage, type MigrationChunkMessage, type MigrationCompleteMessage, type MigrationConfig, type MigrationMessage, type MigrationMetrics, type MigrationStartMessage, type MigrationStatus, type MigrationVerifyMessage, MinLengthFilter, MultiValueAttribute, NGramTokenizer, NavigableIndex, type NetworkConfig, type NodeHealth, type NodeInfo, type NodeStatus, type NotOwnerError, type NotStep, ORMap, ORMapDiffRequestSchema, type ORMapDiffResponsePayload, ORMapDiffResponseSchema, type ORMapMerkleNode, ORMapMerkleReqBucketSchema, ORMapMerkleTree, ORMapPushDiffSchema, type ORMapQueryResult, type ORMapRecord, ORMapRecordSchema, type ORMapSearchResult, type ORMapSnapshot, ORMapSyncInitSchema, type ORMapSyncRespBucketsPayload, ORMapSyncRespBucketsSchema, type ORMapSyncRespLeafPayload, ORMapSyncRespLeafSchema, type ORMapSyncRespRootPayload, ORMapSyncRespRootSchema, type OpAckMessage, OpAckMessageSchema, OpBatchMessageSchema, type OpRejectedMessage, OpRejectedMessageSchema, type OpResult, OpResultSchema, type OperationQueryOptions, PARTITION_COUNT, type PNCounter, type PNCounterConfig, PNCounterImpl, type PNCounterState, type PNCounterStateObject, PNCounterStateObjectSchema, type PartitionChange, type PartitionInfo, type PartitionMap, type PartitionMapDeltaMessage, type PartitionMapMessage, type PartitionMapRequestMessage, PartitionMapRequestSchema, type PartitionMigration, type PartitionRouterConfig, PartitionState, type PendingWrite, type PermissionPolicy, type PermissionType, type PingMessage, PingMessageSchema, type PlanStep, type PongMessage, PongMessageSchema, type Posting, type PredicateFn, type PredicateNode, PredicateNodeSchema, type PredicateOp, PredicateOpSchema, Predicates, type Principal, type ProcessorRateLimitConfig, type Query$1 as Query, type QueryContext, QueryCursor, type QueryCursorData, type QueryCursorOptions, type Query as QueryExpression, type QueryNode, QueryOptimizer, type QueryOptimizerOptions, type QueryOptions, type QueryPlan, type QueryRespMessage, QueryRespMessageSchema, type QueryRespPayload, QueryRespPayloadSchema, type QueryResultWithCursor, QuerySchema, QuerySubMessageSchema, QueryUnsubMessageSchema, type QueryUpdateMessage, QueryUpdateMessageSchema, type QueryUpdatePayload, QueryUpdatePayloadSchema, RESOLVER_FORBIDDEN_PATTERNS, type RRFConfig, type RRFDebugInfo, type RankedResult, RealClock, ReciprocalRankFusion, type RegisterResolverRequest, RegisterResolverRequestSchema, type RegisterResolverResponse, RegisterResolverResponseSchema, type ReplicationAckMessage, type ReplicationBatchAckMessage, type ReplicationBatchMessage, type ReplicationConfig, type ReplicationHealth, type ReplicationLag, type ReplicationMessage, type ReplicationProtocolMessage, type ReplicationResult, type ReplicationTask, type ResolverRateLimitConfig, type ResultSet, Ringbuffer, type RoutingError, type ScenarioConfig, type ScenarioResult, ScenarioRunner, type ScoredDocument, SearchCursor, type SearchCursorData, type SearchDebugInfo, SearchDebugger, type SearchIndexStats, type SearchMessage, SearchMessageSchema, type SearchOptions$1 as SearchOptions, SearchOptionsSchema, type SearchPayload, SearchPayloadSchema, type SearchRespMessage, SearchRespMessageSchema, type SearchRespPayload, SearchRespPayloadSchema, type SearchResultDebug, type SearchSubMessage, SearchSubMessageSchema, type SearchSubPayload, SearchSubPayloadSchema, type SearchTiming, type SearchUnsubMessage, SearchUnsubMessageSchema, type SearchUnsubPayload, SearchUnsubPayloadSchema, type SearchUpdateMessage, SearchUpdateMessageSchema, type SearchUpdatePayload, SearchUpdatePayloadSchema, type SearchUpdateType, SearchUpdateTypeSchema, SeededRNG, type SerializedIndex, type ServerBatchEventMessage, ServerBatchEventMessageSchema, type ServerEventMessage, ServerEventMessageSchema, type ServerEventPayload, ServerEventPayloadSchema, SetResultSet, SimpleAttribute, type SimpleQueryNode, SortedMap, SortedResultSet, type StaleMapError, type StandingQueryChange, StandingQueryIndex, type StandingQueryIndexOptions, StandingQueryRegistry, type StandingQueryRegistryOptions, type StandingQueryRegistryStats, StopWordFilter, SyncInitMessageSchema, SyncMapEntrySchema, type SyncResetRequiredPayload, SyncResetRequiredPayloadSchema, SyncRespBucketsMessageSchema, type SyncRespBucketsPayload, SyncRespLeafMessageSchema, type SyncRespLeafPayload, SyncRespRootMessageSchema, type SyncRespRootPayload, type TermInfo, type Timestamp, TimestampSchema, type TokenFilter, TokenizationPipeline, type TokenizationPipelineOptions, type Tokenizer, TopicMessageEventSchema, TopicPubSchema, TopicSubSchema, TopicUnsubSchema, TrimFilter, UnionResultSet, type UnionStep, UniqueFilter, type UnregisterResolverRequest, UnregisterResolverRequestSchema, type UnregisterResolverResponse, UnregisterResolverResponseSchema, type VectorDebugInfo, VirtualClock, VirtualNetwork, WRITE_CONCERN_ORDER, WhitespaceTokenizer, WordBoundaryTokenizer, WriteConcern, WriteConcernSchema, type WriteConcernValue, type WriteOptions$1 as WriteOptions, type WriteResult, calculateTotalCost, combineHashes, compareHLCTimestamps, compareTimestamps, compareValues, createFieldComparator, createPredicateMatcher, decodeBase64Url, deepMerge, deserialize, disableNativeHash, encodeBase64Url, evaluatePredicate, getCRDTDebugger, getHighestWriteConcernLevel, getSearchDebugger, hashORMapEntry, hashORMapRecord, hashObject, hashString, isLogicalQuery, isSimpleQuery, isUsingNativeHash, isWriteConcernAchieved, logger, multiAttribute, porterStem, resetCRDTDebugger, resetNativeHash, resetSearchDebugger, serialize, simpleAttribute, timestampToString, validateProcessorCode, validateResolverCode };