@feltdb/core 0.8.3 → 0.8.5

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.
Files changed (193) hide show
  1. package/dist/cli/commands.js +4 -1
  2. package/dist/cli/provisioning-neutrality.js +79 -0
  3. package/dist/collection.d.ts +43 -1
  4. package/dist/collection.d.ts.map +1 -1
  5. package/dist/collection.js +192 -22
  6. package/dist/create/create.js +25 -21
  7. package/dist/create/managed-account.js +11 -0
  8. package/dist/create/package-versions.js +1 -1
  9. package/dist/create/server-source/Cargo.lock +165 -0
  10. package/dist/create/server-source/Cargo.toml +9 -0
  11. package/dist/create/server-source/crates/feltdb/Cargo.toml +3 -0
  12. package/dist/create/server-source/crates/feltdb/benches/gate13_baseline.rs +44 -44
  13. package/dist/create/server-source/crates/feltdb/benches/gate13_phase_7_1_release_economics.rs +12 -24
  14. package/dist/create/server-source/crates/feltdb/benches/gate_13_redux.rs +7 -13
  15. package/dist/create/server-source/crates/feltdb/benches/gate_13_regression_runner.rs +13 -10
  16. package/dist/create/server-source/crates/feltdb/benches/gate_14a_concurrent_writer_scaling.rs +12 -9
  17. package/dist/create/server-source/crates/feltdb/benches/gate_14a_production_admission_revalidation.rs +78 -25
  18. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc2_admission_contract.rs +16 -13
  19. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc_root_cause.rs +13 -5
  20. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync1_queued_prototype.rs +41 -22
  21. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync_economics.rs +33 -15
  22. package/dist/create/server-source/crates/feltdb/benches/gate_14b_causal_backlog_scaling.rs +100 -33
  23. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_contract_test.rs +56 -20
  24. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_scaling.rs +116 -41
  25. package/dist/create/server-source/crates/feltdb/benches/gate_14d_combined_dimension_scaling.rs +186 -55
  26. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_2_optimization_benchmark.rs +64 -26
  27. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_3_crossover_analysis.rs +46 -15
  28. package/dist/create/server-source/crates/feltdb/src/admission.rs +8 -15
  29. package/dist/create/server-source/crates/feltdb/src/admission_contract_tests.rs +43 -13
  30. package/dist/create/server-source/crates/feltdb/src/adversarial_transport.rs +15 -42
  31. package/dist/create/server-source/crates/feltdb/src/analytics.rs +65 -19
  32. package/dist/create/server-source/crates/feltdb/src/application.rs +113 -30
  33. package/dist/create/server-source/crates/feltdb/src/authorization_security_tests.rs +475 -140
  34. package/dist/create/server-source/crates/feltdb/src/cardinality_diagnostics.rs +17 -15
  35. package/dist/create/server-source/crates/feltdb/src/cardinality_endpoint.rs +0 -1
  36. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +59 -15
  37. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +266 -114
  38. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier_phase_7_1.rs +25 -7
  39. package/dist/create/server-source/crates/feltdb/src/concurrency_fuzzing.rs +10 -15
  40. package/dist/create/server-source/crates/feltdb/src/consistency_contract.rs +3 -11
  41. package/dist/create/server-source/crates/feltdb/src/crash_atomic_boundary.rs +14 -5
  42. package/dist/create/server-source/crates/feltdb/src/crash_injection.rs +21 -25
  43. package/dist/create/server-source/crates/feltdb/src/crash_recovery_tests.rs +14 -11
  44. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +103 -22
  45. package/dist/create/server-source/crates/feltdb/src/distributed_indexing.rs +18 -15
  46. package/dist/create/server-source/crates/feltdb/src/durability_guarantees.rs +12 -8
  47. package/dist/create/server-source/crates/feltdb/src/durable_dedup_set.rs +1 -5
  48. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +87 -23
  49. package/dist/create/server-source/crates/feltdb/src/durable_operation_log.rs +3 -7
  50. package/dist/create/server-source/crates/feltdb/src/durable_sync.rs +10 -9
  51. package/dist/create/server-source/crates/feltdb/src/equality_index.rs +595 -0
  52. package/dist/create/server-source/crates/feltdb/src/in_process_transport.rs +1 -6
  53. package/dist/create/server-source/crates/feltdb/src/indexing.rs +35 -38
  54. package/dist/create/server-source/crates/feltdb/src/lib.rs +1050 -117
  55. package/dist/create/server-source/crates/feltdb/src/managed_cas_tests.rs +4 -1
  56. package/dist/create/server-source/crates/feltdb/src/metrics.rs +0 -1
  57. package/dist/create/server-source/crates/feltdb/src/multi_node_convergence.rs +1 -2
  58. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +107 -30
  59. package/dist/create/server-source/crates/feltdb/src/observability.rs +19 -6
  60. package/dist/create/server-source/crates/feltdb/src/operation_algebra.rs +12 -11
  61. package/dist/create/server-source/crates/feltdb/src/operation_log.rs +9 -4
  62. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +65 -18
  63. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +193 -57
  64. package/dist/create/server-source/crates/feltdb/src/partition_reconciliation.rs +37 -27
  65. package/dist/create/server-source/crates/feltdb/src/permutation_scheduler.rs +38 -10
  66. package/dist/create/server-source/crates/feltdb/src/persistence_reality.rs +20 -14
  67. package/dist/create/server-source/crates/feltdb/src/phase1b_acceptance.rs +394 -229
  68. package/dist/create/server-source/crates/feltdb/src/phase1c1_acceptance.rs +8 -6
  69. package/dist/create/server-source/crates/feltdb/src/phase1c2_acceptance.rs +11 -13
  70. package/dist/create/server-source/crates/feltdb/src/phase1c3_acceptance.rs +90 -72
  71. package/dist/create/server-source/crates/feltdb/src/phase1c_atomicity_proof.rs +3 -3
  72. package/dist/create/server-source/crates/feltdb/src/phase5_integration.rs +33 -11
  73. package/dist/create/server-source/crates/feltdb/src/phase5_scenarios.rs +6 -6
  74. package/dist/create/server-source/crates/feltdb/src/phase6_adversarial_scenarios.rs +14 -56
  75. package/dist/create/server-source/crates/feltdb/src/phase6_convergence_validator.rs +29 -27
  76. package/dist/create/server-source/crates/feltdb/src/phase6_persistence.rs +35 -17
  77. package/dist/create/server-source/crates/feltdb/src/phase_1c_real_tcp.rs +8 -2
  78. package/dist/create/server-source/crates/feltdb/src/phase_2a_failures.rs +59 -15
  79. package/dist/create/server-source/crates/feltdb/src/phase_2b_network.rs +70 -17
  80. package/dist/create/server-source/crates/feltdb/src/phase_2c_cascading.rs +23 -6
  81. package/dist/create/server-source/crates/feltdb/src/phase_3_durability.rs +12 -3
  82. package/dist/create/server-source/crates/feltdb/src/phase_4_baseline.rs +41 -11
  83. package/dist/create/server-source/crates/feltdb/src/phase_5_soak.rs +56 -25
  84. package/dist/create/server-source/crates/feltdb/src/policy_evaluation.rs +701 -245
  85. package/dist/create/server-source/crates/feltdb/src/production_api.rs +31 -13
  86. package/dist/create/server-source/crates/feltdb/src/query_execution_diagnostics.rs +126 -0
  87. package/dist/create/server-source/crates/feltdb/src/query_performance.rs +6 -8
  88. package/dist/create/server-source/crates/feltdb/src/replay_fuzzing.rs +5 -5
  89. package/dist/create/server-source/crates/feltdb/src/replica_acknowledgements.rs +48 -18
  90. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +30 -11
  91. package/dist/create/server-source/crates/feltdb/src/replication_manager.rs +6 -3
  92. package/dist/create/server-source/crates/feltdb/src/replication_protocol.rs +4 -3
  93. package/dist/create/server-source/crates/feltdb/src/sharding.rs +36 -10
  94. package/dist/create/server-source/crates/feltdb/src/state_conflict_contract.rs +516 -0
  95. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +305 -6
  96. package/dist/create/server-source/crates/feltdb/src/state_diff_contract.rs +222 -0
  97. package/dist/create/server-source/crates/feltdb/src/state_facade.rs +82 -54
  98. package/dist/create/server-source/crates/feltdb/src/state_hash.rs +2 -2
  99. package/dist/create/server-source/crates/feltdb/src/state_model.rs +1514 -537
  100. package/dist/create/server-source/crates/feltdb/src/state_transition_store.rs +6 -3
  101. package/dist/create/server-source/crates/feltdb/src/state_trigger.rs +672 -0
  102. package/dist/create/server-source/crates/feltdb/src/submission.rs +5 -11
  103. package/dist/create/server-source/crates/feltdb/src/sync.rs +12 -0
  104. package/dist/create/server-source/crates/feltdb/src/tcp_transport.rs +6 -8
  105. package/dist/create/server-source/crates/feltdb/src/transaction_api.rs +24 -35
  106. package/dist/create/server-source/crates/feltdb/src/transaction_invariants.rs +24 -8
  107. package/dist/create/server-source/crates/feltdb/src/transaction_preconditions.rs +248 -59
  108. package/dist/create/server-source/crates/feltdb/src/transactions.rs +17 -20
  109. package/dist/create/server-source/crates/feltdb/src/trigger_contract.rs +749 -0
  110. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +1 -0
  111. package/dist/create/server-source/crates/feltdb/src/workload.rs +512 -4
  112. package/dist/create/server-source/crates/feltdb/src/workload_diagnostics.rs +442 -0
  113. package/dist/create/server-source/crates/feltdb/tests/branching_evidence.rs +299 -0
  114. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +288 -0
  115. package/dist/create/server-source/crates/feltdb/tests/durable_format_compatibility.rs +392 -0
  116. package/dist/create/server-source/crates/feltdb/tests/feltdb_state_boundary_tests.rs +436 -220
  117. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_conflict_contract_corpus.json +1916 -0
  118. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_diff_contract_corpus.json +1878 -0
  119. package/dist/create/server-source/crates/feltdb/tests/fixtures/trigger_contract_corpus.json +1862 -0
  120. package/dist/create/server-source/crates/feltdb/tests/pr34_query_collection.rs +234 -0
  121. package/dist/create/server-source/crates/feltdb/tests/pr35_equality_index.rs +947 -0
  122. package/dist/create/server-source/crates/feltdb/tests/pr7_self_authorization_proof.rs +5 -8
  123. package/dist/create/server-source/crates/feltdb/tests/pr8_vocabulary_assessment.rs +52 -44
  124. package/dist/create/server-source/crates/feltdb/tests/pr9_phase2_boundary_tests.rs +33 -16
  125. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3a_path_a_tests.rs +22 -7
  126. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_authorized_mutations.rs +41 -22
  127. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_role_based_authorization.rs +25 -8
  128. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_simple_auth_delete.rs +9 -6
  129. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_team_delete_role_authorization.rs +120 -69
  130. package/dist/create/server-source/crates/feltdb/tests/pr9_teams_role_based_access.rs +21 -10
  131. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +1032 -0
  132. package/dist/create/server-source/crates/feltdb/tests/reconciliation_application.rs +868 -0
  133. package/dist/create/server-source/crates/feltdb/tests/reconciliation_wire_format_evidence.rs +221 -0
  134. package/dist/create/server-source/crates/feltdb/tests/resource_scoped_revisions.rs +338 -0
  135. package/dist/create/server-source/crates/feltdb/tests/revision_identity_contract.rs +1039 -0
  136. package/dist/create/server-source/crates/feltdb/tests/revision_model_decision.rs +739 -0
  137. package/dist/create/server-source/crates/feltdb/tests/revision_retention_boundary_evidence.rs +427 -0
  138. package/dist/create/server-source/crates/feltdb/tests/saas_authorization_integration.rs +3 -3
  139. package/dist/create/server-source/crates/feltdb/tests/saas_invitation_lifecycle.rs +25 -22
  140. package/dist/create/server-source/crates/feltdb/tests/state_conflict_contract_conformance.rs +1799 -0
  141. package/dist/create/server-source/crates/feltdb/tests/state_diff_contract_conformance.rs +1316 -0
  142. package/dist/create/server-source/crates/feltdb/tests/state_model_integration.rs +53 -61
  143. package/dist/create/server-source/crates/feltdb/tests/state_persistence_integration.rs +156 -61
  144. package/dist/create/server-source/crates/feltdb/tests/state_store_boundary_evidence.rs +299 -0
  145. package/dist/create/server-source/crates/feltdb/tests/sync_divergence_evidence.rs +255 -0
  146. package/dist/create/server-source/crates/feltdb/tests/three_way_input_boundary_evidence.rs +249 -0
  147. package/dist/create/server-source/crates/feltdb/tests/trigger_contract_conformance.rs +994 -0
  148. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +2 -1
  149. package/dist/create/server-source/crates/feltdb-server/src/audit.rs +1137 -29
  150. package/dist/create/server-source/crates/feltdb-server/src/auth.rs +164 -13
  151. package/dist/create/server-source/crates/feltdb-server/src/main.rs +800 -34
  152. package/dist/db.d.ts +33 -34
  153. package/dist/db.d.ts.map +1 -1
  154. package/dist/db.js +74 -20
  155. package/dist/deployment.d.ts +30 -0
  156. package/dist/deployment.d.ts.map +1 -0
  157. package/dist/deployment.js +130 -0
  158. package/dist/embedded-transaction.d.ts +22 -4
  159. package/dist/embedded-transaction.d.ts.map +1 -1
  160. package/dist/embedded-transaction.js +51 -5
  161. package/dist/feltdb.d.ts +14 -2
  162. package/dist/feltdb.d.ts.map +1 -1
  163. package/dist/file-db.js +1 -1
  164. package/dist/http-client.d.ts +14 -0
  165. package/dist/http-client.d.ts.map +1 -1
  166. package/dist/http-client.js +23 -5
  167. package/dist/http-db.d.ts +119 -1
  168. package/dist/http-db.d.ts.map +1 -1
  169. package/dist/http-db.js +346 -31
  170. package/dist/index-core.d.ts +2 -0
  171. package/dist/index-core.d.ts.map +1 -1
  172. package/dist/index-core.js +2 -0
  173. package/dist/index.d.ts.map +1 -1
  174. package/dist/index.js +9 -0
  175. package/dist/indexeddb-db.d.ts.map +1 -1
  176. package/dist/indexeddb-db.js +35 -21
  177. package/dist/managed-recovery.d.ts +192 -0
  178. package/dist/managed-recovery.d.ts.map +1 -0
  179. package/dist/managed-recovery.js +242 -0
  180. package/dist/memory-db.js +1 -1
  181. package/dist/studio-app/assets/{feltdb_wasm-DB8cX151.js → feltdb_wasm-DaNwCLRX.js} +1 -1
  182. package/dist/studio-app/assets/feltdb_wasm_bg-DnsHNv6g.wasm +0 -0
  183. package/dist/studio-app/assets/index-j8IlhNqJ.js +29 -0
  184. package/dist/studio-app/index.html +1 -1
  185. package/dist/transaction.d.ts +30 -0
  186. package/dist/transaction.d.ts.map +1 -1
  187. package/dist/transaction.js +41 -0
  188. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  189. package/dist/workload.d.ts +2 -1
  190. package/dist/workload.d.ts.map +1 -1
  191. package/package.json +1 -1
  192. package/dist/studio-app/assets/feltdb_wasm_bg-ClhDHp0S.wasm +0 -0
  193. package/dist/studio-app/assets/index-B0k4UAlI.js +0 -29
@@ -0,0 +1,442 @@
1
+ //! Phase-level execution attribution for the sustained workload.
2
+ //!
3
+ //! PR33 named query execution as the sustained-workload bottleneck. PR34
4
+ //! removed whole-collection materialization and PR35 removed the full predicate
5
+ //! scan, taking the workload from 274.1 to 1,665.9 ops/sec on one runner. PR36
6
+ //! asks what is left, and that question cannot be answered from throughput:
7
+ //! an aggregate rate says how fast the system is, never where the time went.
8
+ //!
9
+ //! So this module records **where the time went**, as elapsed nanoseconds and a
10
+ //! call count per execution phase. Three properties keep it honest:
11
+ //!
12
+ //! 1. **The boundaries are real.** Every phase brackets an actual span of
13
+ //! execution — the wait for the state lock, the index lookup, the record
14
+ //! fetch, the predicate, the sort, the log append. Nothing here is a
15
+ //! proportion inferred from wall-clock time, and a phase that cannot be
16
+ //! bracketed cleanly is simply absent rather than estimated.
17
+ //! 2. **Phases nest, and the report says so.** `STATE_LOCK_HOLD` contains
18
+ //! `RECORD_MUTATION`, `INDEX_MAINTENANCE` and `PERSISTENCE`; `INDEXED_QUERY`
19
+ //! contains `INDEX_LOOKUP`, `CANDIDATE_RETRIEVAL` and `PREDICATE_EVALUATION`.
20
+ //! Summing every phase would double-count, which is why [`Phase::parent`]
21
+ //! exists and why the analysis distinguishes exclusive time from nested time.
22
+ //! 3. **It is off unless asked for.** Disabled, each instrumented site costs one
23
+ //! relaxed atomic load and a predictable branch; no clock is read and no
24
+ //! counter is touched. It is enabled by `FELTDB_WORKLOAD_DIAGNOSTICS=1`, is
25
+ //! test instrumentation rather than a product surface, and reports counts and
26
+ //! durations only — never a record, a field, a value or an id.
27
+ //!
28
+ //! Instrumentation that changes what it measures is not a measurement, so the
29
+ //! overhead of *enabled* diagnostics is itself measured, and the headline
30
+ //! production figures are taken with diagnostics off.
31
+
32
+ use std::sync::atomic::{AtomicU64, Ordering};
33
+ use std::time::Instant;
34
+
35
+ /// One bracketed span of execution.
36
+ ///
37
+ /// Ordered so that a report reads top-down: request, then query phases, then
38
+ /// mutation phases. The discriminant is the counter index, so adding a phase
39
+ /// means adding it here and to [`Phase::ALL`] and nothing else.
40
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41
+ #[repr(usize)]
42
+ pub enum Phase {
43
+ /// Waiting to acquire the single state lock. Pure contention: no work is
44
+ /// done here, which is what makes it the one phase whose time is always
45
+ /// wasted rather than merely spent.
46
+ StateLockWait = 0,
47
+ /// Holding the state lock. Contains every phase below that touches state,
48
+ /// and bounds how long other operations can be made to wait.
49
+ StateLockHold,
50
+ /// A bounded query answered from the equality index, end to end.
51
+ IndexedQuery,
52
+ /// Turning `(field, value)` into candidate record ids inside the index.
53
+ IndexLookup,
54
+ /// Fetching authoritative records for candidate ids.
55
+ CandidateRetrieval,
56
+ /// Evaluating the query's conjunction against a record, on either execution.
57
+ PredicateEvaluation,
58
+ /// A bounded query answered by scanning the collection, end to end.
59
+ ScanQuery,
60
+ /// Sorting the matching set into the query's requested order.
61
+ Ordering,
62
+ /// Cloning matches and injecting `recordId` to build the visible result.
63
+ ResultMaterialization,
64
+ /// Writing or removing a record in the authoritative map.
65
+ RecordMutation,
66
+ /// Maintaining the derived equality index alongside that record change.
67
+ IndexMaintenance,
68
+ /// Appending to the durable log, including any fsync it performs.
69
+ Persistence,
70
+ /// Transaction bookkeeping around a commit: preconditions, operation
71
+ /// construction, revision and dedup accounting. Excludes the log append.
72
+ TransactionCommit,
73
+ /// A whole HTTP handler, measured inside the server between extraction and
74
+ /// response. The gap between this and the client's own timing is transport,
75
+ /// decode and encode.
76
+ HttpHandler,
77
+ /// Authenticating and authorizing a request: key lookup, signature and
78
+ /// capability checks. Nested inside `HttpHandler`, and separated from it
79
+ /// because "the request costs something outside state" is not an answer —
80
+ /// which part of the request is.
81
+ Authorization,
82
+ /// The request's whole dealing with the security audit subsystem: building
83
+ /// the event, submitting it to the audit writer, and waiting for the
84
+ /// writer to accept it. Nested inside `HttpHandler` and deliberately not
85
+ /// folded into `Persistence`, which is the *state* log — these are two
86
+ /// different durable writes with two different reasons to exist, and
87
+ /// attributing them together would hide which one costs what.
88
+ ///
89
+ /// Since PR38 this span no longer contains a durability barrier. The
90
+ /// barrier happens on the audit writer's own threads, in
91
+ /// `AuditGroupSync`, after the request has already been released.
92
+ AuditWrite,
93
+ /// Handing the event to the audit writer's bounded queue. Fails fast when
94
+ /// the queue is at capacity rather than blocking the request.
95
+ AuditSubmit,
96
+ /// Waiting for the audit writer to append the submitted event to the
97
+ /// stream — the acceptance boundary, and the only part of the audit
98
+ /// pipeline a request waits for.
99
+ ///
100
+ /// This is the audit path's analogue of `StateLockWait`, and it is where
101
+ /// the single-writer discipline shows up as time: a request waits behind
102
+ /// the appends in front of it, and behind whatever the writer is doing
103
+ /// when it arrives.
104
+ AuditAcceptWait,
105
+ /// Opening the audit file, on the writer thread. Since PR38 the writer
106
+ /// keeps the handle, so this happens once per stream rather than once per
107
+ /// event; it is still measured, because "once" is a claim.
108
+ AuditOpen,
109
+ /// Serializing one event into the writer's reusable buffer and issuing the
110
+ /// single `write(2)` that appends it. On the writer thread.
111
+ AuditAppend,
112
+ /// `File::flush` on the audit handle, inside a durability group. A
113
+ /// `std::fs::File` holds no userspace buffer, so this is measured rather
114
+ /// than assumed to be free.
115
+ AuditFlush,
116
+ /// `File::sync_data` on the audit handle: the durability barrier itself,
117
+ /// and the one phase that asks the storage stack for a guarantee rather
118
+ /// than for a write. On the syncer thread, off the request path.
119
+ AuditFsync,
120
+ /// One whole durability group: the flush and the barrier that make a
121
+ /// bounded set of already-accepted events durable. On the syncer thread.
122
+ AuditGroupSync,
123
+ /// Closing the audit file handle at shutdown. Measured because it is a
124
+ /// syscall, and because the point of the writer owning the handle is that
125
+ /// this no longer happens per event.
126
+ AuditClose,
127
+ /// The body of a request handler, from the first line of the handler
128
+ /// function to its return.
129
+ ///
130
+ /// It exists to bracket what a middleware cannot. `HttpHandler` wraps the
131
+ /// whole route, so it includes axum's extraction — where the request JSON is
132
+ /// decoded — and the response conversion, where the response JSON is
133
+ /// encoded. Neither can be timed from inside a handler or from a middleware
134
+ /// alone. The difference `HttpHandler - HandlerBody - Authorization -
135
+ /// AuditWrite` is therefore routing plus decode plus encode, measured as a
136
+ /// difference of two spans rather than asserted.
137
+ HandlerBody,
138
+ }
139
+
140
+ impl Phase {
141
+ pub const ALL: [Phase; 25] = [
142
+ Phase::StateLockWait,
143
+ Phase::StateLockHold,
144
+ Phase::IndexedQuery,
145
+ Phase::IndexLookup,
146
+ Phase::CandidateRetrieval,
147
+ Phase::PredicateEvaluation,
148
+ Phase::ScanQuery,
149
+ Phase::Ordering,
150
+ Phase::ResultMaterialization,
151
+ Phase::RecordMutation,
152
+ Phase::IndexMaintenance,
153
+ Phase::Persistence,
154
+ Phase::TransactionCommit,
155
+ Phase::HttpHandler,
156
+ Phase::Authorization,
157
+ Phase::AuditWrite,
158
+ Phase::AuditSubmit,
159
+ Phase::AuditAcceptWait,
160
+ Phase::AuditOpen,
161
+ Phase::AuditAppend,
162
+ Phase::AuditFlush,
163
+ Phase::AuditFsync,
164
+ Phase::AuditGroupSync,
165
+ Phase::AuditClose,
166
+ Phase::HandlerBody,
167
+ ];
168
+
169
+ /// The stable name this phase is reported under.
170
+ pub fn name(self) -> &'static str {
171
+ match self {
172
+ Phase::StateLockWait => "state_lock_wait",
173
+ Phase::StateLockHold => "state_lock_hold",
174
+ Phase::IndexedQuery => "indexed_query",
175
+ Phase::IndexLookup => "index_lookup",
176
+ Phase::CandidateRetrieval => "candidate_retrieval",
177
+ Phase::PredicateEvaluation => "predicate_evaluation",
178
+ Phase::ScanQuery => "scan_query",
179
+ Phase::Ordering => "ordering",
180
+ Phase::ResultMaterialization => "result_materialization",
181
+ Phase::RecordMutation => "record_mutation",
182
+ Phase::IndexMaintenance => "index_maintenance",
183
+ Phase::Persistence => "persistence",
184
+ Phase::TransactionCommit => "transaction_commit",
185
+ Phase::HttpHandler => "http_handler",
186
+ Phase::Authorization => "authorization",
187
+ Phase::AuditWrite => "audit_write",
188
+ Phase::AuditSubmit => "audit_submit",
189
+ Phase::AuditAcceptWait => "audit_accept_wait",
190
+ Phase::AuditOpen => "audit_open",
191
+ Phase::AuditAppend => "audit_append",
192
+ Phase::AuditFlush => "audit_flush",
193
+ Phase::AuditFsync => "audit_fsync",
194
+ Phase::AuditGroupSync => "audit_group_sync",
195
+ Phase::AuditClose => "audit_close",
196
+ Phase::HandlerBody => "handler_body",
197
+ }
198
+ }
199
+
200
+ /// The phase whose span contains this one, when there is one.
201
+ ///
202
+ /// This is what stops a reader from adding the columns up. A phase's time is
203
+ /// already counted inside its parent, so only sibling phases at one level
204
+ /// can be compared, and only exclusive time can be summed.
205
+ pub fn parent(self) -> Option<Phase> {
206
+ match self {
207
+ Phase::StateLockWait | Phase::StateLockHold | Phase::HttpHandler => None,
208
+ Phase::IndexedQuery | Phase::ScanQuery => Some(Phase::StateLockHold),
209
+ Phase::IndexLookup | Phase::CandidateRetrieval => Some(Phase::IndexedQuery),
210
+ // The predicate runs on both executions, so its parent is the lock
211
+ // rather than either query phase.
212
+ Phase::PredicateEvaluation => Some(Phase::StateLockHold),
213
+ Phase::Authorization | Phase::AuditWrite | Phase::HandlerBody => {
214
+ Some(Phase::HttpHandler)
215
+ }
216
+ Phase::Ordering | Phase::ResultMaterialization => Some(Phase::HandlerBody),
217
+ Phase::RecordMutation | Phase::IndexMaintenance | Phase::Persistence => {
218
+ Some(Phase::StateLockHold)
219
+ }
220
+ Phase::TransactionCommit => Some(Phase::StateLockHold),
221
+ // What the request pays decomposes into the submit and the wait for
222
+ // acceptance, and nothing else: since PR38 no other audit phase
223
+ // happens on the request's thread.
224
+ Phase::AuditSubmit | Phase::AuditAcceptWait => Some(Phase::AuditWrite),
225
+ // The flush and the barrier are the two halves of one durability
226
+ // group.
227
+ Phase::AuditFlush | Phase::AuditFsync => Some(Phase::AuditGroupSync),
228
+ // Deliberately parentless. `AuditOpen`, `AuditAppend`,
229
+ // `AuditGroupSync` and `AuditClose` run on the audit writer's own
230
+ // threads, concurrently with the requests that produced them.
231
+ // Nesting them under `AuditWrite` or `HttpHandler` would let a
232
+ // reader compute a share of a span they do not run inside, and
233
+ // that share could exceed one hundred per cent.
234
+ Phase::AuditOpen | Phase::AuditAppend | Phase::AuditGroupSync | Phase::AuditClose => {
235
+ None
236
+ }
237
+ }
238
+ }
239
+ }
240
+
241
+ const PHASES: usize = Phase::ALL.len();
242
+
243
+ #[allow(clippy::declare_interior_mutable_const)]
244
+ const ZERO: AtomicU64 = AtomicU64::new(0);
245
+ static CALLS: [AtomicU64; PHASES] = [ZERO; PHASES];
246
+ static NANOS: [AtomicU64; PHASES] = [ZERO; PHASES];
247
+ static ENABLED: AtomicU64 = AtomicU64::new(UNRESOLVED);
248
+
249
+ const UNRESOLVED: u64 = 0;
250
+ const OFF: u64 = 1;
251
+ const ON: u64 = 2;
252
+
253
+ /// Is phase attribution recording?
254
+ ///
255
+ /// Resolved once from `FELTDB_WORKLOAD_DIAGNOSTICS`, then a relaxed load. The
256
+ /// environment is read at most once per process, so a hot path never touches the
257
+ /// environment and never allocates.
258
+ #[inline]
259
+ pub fn enabled() -> bool {
260
+ match ENABLED.load(Ordering::Relaxed) {
261
+ ON => true,
262
+ OFF => false,
263
+ _ => {
264
+ let resolved = if std::env::var("FELTDB_WORKLOAD_DIAGNOSTICS").as_deref() == Ok("1") {
265
+ ON
266
+ } else {
267
+ OFF
268
+ };
269
+ ENABLED.store(resolved, Ordering::Relaxed);
270
+ resolved == ON
271
+ }
272
+ }
273
+ }
274
+
275
+ /// Turn recording on or off for the current process, for tests that need to
276
+ /// measure the instrumentation itself rather than through it.
277
+ pub fn set_enabled(on: bool) {
278
+ ENABLED.store(if on { ON } else { OFF }, Ordering::Relaxed);
279
+ }
280
+
281
+ /// An open span. Dropping it records the elapsed time against its phase.
282
+ ///
283
+ /// Constructed only when recording is on, so the disabled path allocates
284
+ /// nothing and never reads the clock.
285
+ #[derive(Debug)]
286
+ pub struct Span {
287
+ phase: Phase,
288
+ began: Instant,
289
+ }
290
+
291
+ impl Drop for Span {
292
+ fn drop(&mut self) {
293
+ let elapsed = self.began.elapsed().as_nanos().min(u64::MAX as u128) as u64;
294
+ let index = self.phase as usize;
295
+ CALLS[index].fetch_add(1, Ordering::Relaxed);
296
+ NANOS[index].fetch_add(elapsed, Ordering::Relaxed);
297
+ }
298
+ }
299
+
300
+ /// Open a span, or `None` when recording is off.
301
+ ///
302
+ /// The `Option` is the whole disabled-path cost: no clock read, no atomic
303
+ /// write, and a branch the predictor gets right every time.
304
+ #[inline]
305
+ pub fn span(phase: Phase) -> Option<Span> {
306
+ enabled().then(|| Span {
307
+ phase,
308
+ began: Instant::now(),
309
+ })
310
+ }
311
+
312
+ /// Record a duration measured elsewhere, such as a lock wait that has to be
313
+ /// timed across an acquisition rather than around a closure.
314
+ #[inline]
315
+ pub fn record(phase: Phase, nanos: u64) {
316
+ if !enabled() {
317
+ return;
318
+ }
319
+ let index = phase as usize;
320
+ CALLS[index].fetch_add(1, Ordering::Relaxed);
321
+ NANOS[index].fetch_add(nanos, Ordering::Relaxed);
322
+ }
323
+
324
+ /// Time one closure into a phase and return its value.
325
+ #[inline]
326
+ pub fn timed<T>(phase: Phase, body: impl FnOnce() -> T) -> T {
327
+ let _span = span(phase);
328
+ body()
329
+ }
330
+
331
+ /// What one phase accumulated: how often, and for how long.
332
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
333
+ pub struct PhaseCounter {
334
+ pub phase: Phase,
335
+ pub calls: u64,
336
+ pub nanos: u64,
337
+ }
338
+
339
+ impl PhaseCounter {
340
+ pub fn mean_nanos(&self) -> u64 {
341
+ self.nanos.checked_div(self.calls).unwrap_or(0)
342
+ }
343
+ }
344
+
345
+ /// Read every phase counter. Monotonic since process start or the last
346
+ /// [`reset`], so a caller compares deltas across a measured window.
347
+ pub fn counters() -> Vec<PhaseCounter> {
348
+ Phase::ALL
349
+ .iter()
350
+ .map(|&phase| PhaseCounter {
351
+ phase,
352
+ calls: CALLS[phase as usize].load(Ordering::Relaxed),
353
+ nanos: NANOS[phase as usize].load(Ordering::Relaxed),
354
+ })
355
+ .collect()
356
+ }
357
+
358
+ /// Zero every counter, so a phase of a measurement starts from a clean base.
359
+ pub fn reset() {
360
+ for index in 0..PHASES {
361
+ CALLS[index].store(0, Ordering::Relaxed);
362
+ NANOS[index].store(0, Ordering::Relaxed);
363
+ }
364
+ }
365
+
366
+ #[cfg(test)]
367
+ mod tests {
368
+ use super::*;
369
+ use std::sync::{Mutex, MutexGuard, OnceLock};
370
+
371
+ /// Counters are process-global; a counter assertion is only meaningful
372
+ /// while no other test in this module is recording.
373
+ fn exclusive() -> MutexGuard<'static, ()> {
374
+ static SERIAL: OnceLock<Mutex<()>> = OnceLock::new();
375
+ SERIAL
376
+ .get_or_init(|| Mutex::new(()))
377
+ .lock()
378
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
379
+ }
380
+
381
+ fn counter(phase: Phase) -> PhaseCounter {
382
+ counters()
383
+ .into_iter()
384
+ .find(|counter| counter.phase == phase)
385
+ .expect("every phase is reported")
386
+ }
387
+
388
+ #[test]
389
+ fn a_disabled_span_records_nothing() {
390
+ let _serial = exclusive();
391
+ set_enabled(false);
392
+ reset();
393
+
394
+ for _ in 0..1_000 {
395
+ let _span = span(Phase::Ordering);
396
+ }
397
+
398
+ assert_eq!(counter(Phase::Ordering).calls, 0);
399
+ assert!(
400
+ span(Phase::Ordering).is_none(),
401
+ "a disabled span is not constructed, so it reads no clock",
402
+ );
403
+ }
404
+
405
+ #[test]
406
+ fn an_enabled_span_records_calls_and_elapsed_time() {
407
+ let _serial = exclusive();
408
+ set_enabled(true);
409
+ reset();
410
+
411
+ for _ in 0..8 {
412
+ timed(Phase::IndexLookup, || std::hint::black_box(0u64));
413
+ }
414
+ let observed = counter(Phase::IndexLookup);
415
+ assert_eq!(observed.calls, 8);
416
+ assert!(observed.nanos > 0, "a span of real work takes real time");
417
+
418
+ set_enabled(false);
419
+ }
420
+
421
+ #[test]
422
+ fn every_phase_is_reported_and_nesting_is_declared() {
423
+ let _serial = exclusive();
424
+ let reported: Vec<&str> = counters()
425
+ .into_iter()
426
+ .map(|counter| counter.phase.name())
427
+ .collect();
428
+ assert_eq!(reported.len(), Phase::ALL.len());
429
+ // A phase must not be its own ancestor, or a report could not
430
+ // distinguish exclusive time from nested time.
431
+ for phase in Phase::ALL {
432
+ let mut ancestor = phase.parent();
433
+ let mut depth = 0;
434
+ while let Some(current) = ancestor {
435
+ assert_ne!(current, phase, "{} is its own ancestor", phase.name());
436
+ depth += 1;
437
+ assert!(depth < PHASES, "phase nesting must terminate");
438
+ ancestor = current.parent();
439
+ }
440
+ }
441
+ }
442
+ }