1use std::{borrow::Cow, cmp::Ordering};
5
6use reifydb_codec::key::{encode_bytes, encode_u128_varint, encoded::EncodedKey, serializer::KeySerializer};
7use reifydb_value::value::Value;
8use smallvec::SmallVec;
9
10use crate::{
11 interface::{
12 catalog::{id::IndexId, metrics::MetricsId, object::ObjectId},
13 store::Tier,
14 },
15 key::{
16 catalog::{
17 BindingKey, ColumnPropertyKey, DictionaryEntryIndexKey, DictionaryEntryKey, DictionaryKey,
18 HandlerKey, IndexEntryKey, IndexKey, PrimaryKeyKey, RelationshipKey, SinkKey, SourceKey,
19 SumTypeKey, TableKey, VariantHandlerKey, ViewKey,
20 },
21 cdc::CdcConsumerKey,
22 column::{
23 ColumnBlockKey, ColumnKey, ColumnSequenceKey, ColumnsKey, SeriesColumnBlockKey,
24 TableColumnBlockKey,
25 },
26 config::ConfigStorageKey,
27 flow::{FlowEdgeByFlowKey, FlowEdgeKey, FlowKey, FlowVersionKey},
28 identity::{
29 AuthenticationKey, GrantedRoleKey, IdentityAttributeKey, IdentityAttributeValueKey,
30 IdentityKey, PolicyKey, PolicyOpKey, RoleKey, TokenKey,
31 },
32 metric::{MetricCdcKey, MetricStorageKey},
33 namespace::{
34 NamespaceBindingKey, NamespaceDictionaryKey, NamespaceFlowKey, NamespaceHandlerKey,
35 NamespaceKey, NamespaceProcedureKey, NamespaceQueueKey, NamespaceRingBufferKey,
36 NamespaceSeriesKey, NamespaceSinkKey, NamespaceSourceKey, NamespaceSumTypeKey,
37 NamespaceTableKey, NamespaceViewKey,
38 },
39 operator::{
40 key::{OperatorByFlowKey, OperatorKey},
41 state::OperatorStateKey,
42 },
43 operator_retention::OperatorRetentionKey,
44 output_frontier::OutputFrontierKey,
45 partition::PartitionKey,
46 procedure::{ProcedureKey, ProcedureParamKey},
47 queue::{
48 QueueAttemptKey, QueueDeduplicationKey, QueueDueKey, QueueItemStateKey, QueueKey,
49 QueueKeyActiveKey, QueuePartitionKey,
50 },
51 ringbuffer::{RingBufferKey, RingBufferMetadataKey},
52 row::{
53 PartitionedRowKey, PartitionedSortedViewRowKey, RowKey, RowSequenceKey, RowSettingsKey,
54 RowShapeFieldKey, RowShapeKey, SortedViewRowKey, encode_sort_run,
55 },
56 series::{PartitionedSeriesRowKey, SeriesKey, SeriesPartitionMetadataKey, SeriesRowKey},
57 system::{MigrationEventKey, MigrationKey, SystemSequenceKey, SystemVersionKey, VersionEpochKey},
58 tag::KeyTag,
59 },
60};
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum MetricKey {
64 Cdc(MetricCdcKey),
65 Storage(MetricStorageKey),
66}
67
68#[derive(Debug, Clone, PartialEq, Hash)]
69pub enum TaggedKey {
70 Namespace(NamespaceKey),
71 Table(TableKey),
72 Row(RowKey),
73 NamespaceTable(NamespaceTableKey),
74 SystemSequence(SystemSequenceKey),
75 Columns(ColumnsKey),
76 Column(ColumnKey),
77 RowSequence(RowSequenceKey),
78 ColumnProperty(ColumnPropertyKey),
79 SystemVersion(SystemVersionKey),
80 Index(IndexKey),
81 IndexEntry(IndexEntryKey),
82 ColumnSequence(ColumnSequenceKey),
83 CdcConsumer(CdcConsumerKey),
84 View(ViewKey),
85 NamespaceView(NamespaceViewKey),
86 PrimaryKey(PrimaryKeyKey),
87 OperatorState(OperatorStateKey),
88 RingBuffer(RingBufferKey),
89 NamespaceRingBuffer(NamespaceRingBufferKey),
90 RingBufferMetadata(RingBufferMetadataKey),
91 Flow(FlowKey),
92 NamespaceFlow(NamespaceFlowKey),
93 Operator(OperatorKey),
94 OperatorByFlow(OperatorByFlowKey),
95 FlowEdge(FlowEdgeKey),
96 FlowEdgeByFlow(FlowEdgeByFlowKey),
97 OutputFrontier(OutputFrontierKey),
98 Dictionary(DictionaryKey),
99 DictionaryEntry(DictionaryEntryKey),
100 DictionaryEntryIndex(DictionaryEntryIndexKey),
101 NamespaceDictionary(NamespaceDictionaryKey),
102 Metric(MetricKey),
103 FlowVersion(FlowVersionKey),
104 RowShape(RowShapeKey),
105 RowShapeField(RowShapeFieldKey),
106 SumType(SumTypeKey),
107 NamespaceSumType(NamespaceSumTypeKey),
108 Handler(HandlerKey),
109 NamespaceHandler(NamespaceHandlerKey),
110 VariantHandler(VariantHandlerKey),
111 Series(SeriesKey),
112 NamespaceSeries(NamespaceSeriesKey),
113 SeriesPartitionMetadata(SeriesPartitionMetadataKey),
114 Identity(IdentityKey),
115 Role(RoleKey),
116 GrantedRole(GrantedRoleKey),
117 Policy(PolicyKey),
118 PolicyOp(PolicyOpKey),
119 Migration(MigrationKey),
120 MigrationEvent(MigrationEventKey),
121 Authentication(AuthenticationKey),
122 ConfigStorage(ConfigStorageKey),
123 Token(TokenKey),
124 Source(SourceKey),
125 NamespaceSource(NamespaceSourceKey),
126 Sink(SinkKey),
127 NamespaceSink(NamespaceSinkKey),
128 RowSettings(RowSettingsKey),
129 Procedure(ProcedureKey),
130 NamespaceProcedure(NamespaceProcedureKey),
131 ProcedureParam(ProcedureParamKey),
132 Binding(BindingKey),
133 NamespaceBinding(NamespaceBindingKey),
134 OperatorRetention(OperatorRetentionKey),
135 ColumnBlock(ColumnBlockKey),
136 SeriesColumnBlock(SeriesColumnBlockKey),
137 TableColumnBlock(TableColumnBlockKey),
138 VersionEpoch(VersionEpochKey),
139 IdentityAttribute(IdentityAttributeKey),
140 IdentityAttributeValue(IdentityAttributeValueKey),
141 PartitionedRow(PartitionedRowKey),
142 Partition(PartitionKey),
143 Queue(QueueKey),
144 NamespaceQueue(NamespaceQueueKey),
145 QueueDeduplication(QueueDeduplicationKey),
146 Relationship(RelationshipKey),
147 SeriesRow(SeriesRowKey),
148 PartitionedSeriesRow(PartitionedSeriesRowKey),
149 QueuePartition(QueuePartitionKey),
150 QueueItemState(QueueItemStateKey),
151 QueueDue(QueueDueKey),
152 QueueAttempt(QueueAttemptKey),
153 QueueKeyActive(QueueKeyActiveKey),
154 SortedViewRow(SortedViewRowKey),
155 PartitionedSortedViewRow(PartitionedSortedViewRowKey),
156}
157
158impl TaggedKey {
159 pub fn kind(&self) -> KeyTag {
160 match self {
161 Self::Namespace(_) => KeyTag::Namespace,
162 Self::Table(_) => KeyTag::Table,
163 Self::Row(_) => KeyTag::Row,
164 Self::NamespaceTable(_) => KeyTag::NamespaceTable,
165 Self::SystemSequence(_) => KeyTag::SystemSequence,
166 Self::Columns(_) => KeyTag::Columns,
167 Self::Column(_) => KeyTag::Column,
168 Self::RowSequence(_) => KeyTag::RowSequence,
169 Self::ColumnProperty(_) => KeyTag::ColumnProperty,
170 Self::SystemVersion(_) => KeyTag::SystemVersion,
171 Self::Index(_) => KeyTag::Index,
172 Self::IndexEntry(_) => KeyTag::IndexEntry,
173 Self::ColumnSequence(_) => KeyTag::ColumnSequence,
174 Self::CdcConsumer(_) => KeyTag::CdcConsumer,
175 Self::View(_) => KeyTag::View,
176 Self::NamespaceView(_) => KeyTag::NamespaceView,
177 Self::PrimaryKey(_) => KeyTag::PrimaryKey,
178 Self::OperatorState(_) => KeyTag::OperatorState,
179 Self::RingBuffer(_) => KeyTag::RingBuffer,
180 Self::NamespaceRingBuffer(_) => KeyTag::NamespaceRingBuffer,
181 Self::RingBufferMetadata(_) => KeyTag::RingBufferMetadata,
182 Self::Flow(_) => KeyTag::Flow,
183 Self::NamespaceFlow(_) => KeyTag::NamespaceFlow,
184 Self::Operator(_) => KeyTag::Operator,
185 Self::OperatorByFlow(_) => KeyTag::OperatorByFlow,
186 Self::FlowEdge(_) => KeyTag::FlowEdge,
187 Self::FlowEdgeByFlow(_) => KeyTag::FlowEdgeByFlow,
188 Self::OutputFrontier(_) => KeyTag::OutputFrontier,
189 Self::Dictionary(_) => KeyTag::Dictionary,
190 Self::DictionaryEntry(_) => KeyTag::DictionaryEntry,
191 Self::DictionaryEntryIndex(_) => KeyTag::DictionaryEntryIndex,
192 Self::NamespaceDictionary(_) => KeyTag::NamespaceDictionary,
193 Self::Metric(_) => KeyTag::Metric,
194 Self::FlowVersion(_) => KeyTag::FlowVersion,
195 Self::RowShape(_) => KeyTag::RowShape,
196 Self::RowShapeField(_) => KeyTag::RowShapeField,
197 Self::SumType(_) => KeyTag::SumType,
198 Self::NamespaceSumType(_) => KeyTag::NamespaceSumType,
199 Self::Handler(_) => KeyTag::Handler,
200 Self::NamespaceHandler(_) => KeyTag::NamespaceHandler,
201 Self::VariantHandler(_) => KeyTag::VariantHandler,
202 Self::Series(_) => KeyTag::Series,
203 Self::NamespaceSeries(_) => KeyTag::NamespaceSeries,
204 Self::SeriesPartitionMetadata(_) => KeyTag::SeriesPartitionMetadata,
205 Self::Identity(_) => KeyTag::Identity,
206 Self::Role(_) => KeyTag::Role,
207 Self::GrantedRole(_) => KeyTag::GrantedRole,
208 Self::Policy(_) => KeyTag::Policy,
209 Self::PolicyOp(_) => KeyTag::PolicyOp,
210 Self::Migration(_) => KeyTag::Migration,
211 Self::MigrationEvent(_) => KeyTag::MigrationEvent,
212 Self::Authentication(_) => KeyTag::Authentication,
213 Self::ConfigStorage(_) => KeyTag::ConfigStorage,
214 Self::Token(_) => KeyTag::Token,
215 Self::Source(_) => KeyTag::Source,
216 Self::NamespaceSource(_) => KeyTag::NamespaceSource,
217 Self::Sink(_) => KeyTag::Sink,
218 Self::NamespaceSink(_) => KeyTag::NamespaceSink,
219 Self::RowSettings(_) => KeyTag::RowSettings,
220 Self::Procedure(_) => KeyTag::Procedure,
221 Self::NamespaceProcedure(_) => KeyTag::NamespaceProcedure,
222 Self::ProcedureParam(_) => KeyTag::ProcedureParam,
223 Self::Binding(_) => KeyTag::Binding,
224 Self::NamespaceBinding(_) => KeyTag::NamespaceBinding,
225 Self::OperatorRetention(_) => KeyTag::OperatorRetention,
226 Self::ColumnBlock(_) => KeyTag::ColumnBlock,
227 Self::SeriesColumnBlock(_) => KeyTag::SeriesColumnBlock,
228 Self::TableColumnBlock(_) => KeyTag::TableColumnBlock,
229 Self::VersionEpoch(_) => KeyTag::VersionEpoch,
230 Self::IdentityAttribute(_) => KeyTag::IdentityAttribute,
231 Self::IdentityAttributeValue(_) => KeyTag::IdentityAttributeValue,
232 Self::PartitionedRow(_) => KeyTag::PartitionedRow,
233 Self::Partition(_) => KeyTag::Partition,
234 Self::Queue(_) => KeyTag::Queue,
235 Self::NamespaceQueue(_) => KeyTag::NamespaceQueue,
236 Self::QueueDeduplication(_) => KeyTag::QueueDeduplication,
237 Self::Relationship(_) => KeyTag::Relationship,
238 Self::SeriesRow(_) => KeyTag::SeriesRow,
239 Self::PartitionedSeriesRow(_) => KeyTag::PartitionedSeriesRow,
240 Self::QueuePartition(_) => KeyTag::QueuePartition,
241 Self::QueueItemState(_) => KeyTag::QueueItemState,
242 Self::QueueDue(_) => KeyTag::QueueDue,
243 Self::QueueAttempt(_) => KeyTag::QueueAttempt,
244 Self::QueueKeyActive(_) => KeyTag::QueueKeyActive,
245 Self::SortedViewRow(_) => KeyTag::SortedViewRow,
246 Self::PartitionedSortedViewRow(_) => KeyTag::PartitionedSortedViewRow,
247 }
248 }
249
250 pub fn encode(&self) -> EncodedKey {
251 match self {
252 Self::Namespace(key) => key.encode(),
253 Self::Table(key) => key.encode(),
254 Self::Row(key) => key.encode(),
255 Self::NamespaceTable(key) => key.encode(),
256 Self::SystemSequence(key) => key.encode(),
257 Self::Columns(key) => key.encode(),
258 Self::Column(key) => key.encode(),
259 Self::RowSequence(key) => key.encode(),
260 Self::ColumnProperty(key) => key.encode(),
261 Self::SystemVersion(key) => key.encode(),
262 Self::Index(key) => key.encode(),
263 Self::IndexEntry(key) => key.encode(),
264 Self::ColumnSequence(key) => key.encode(),
265 Self::CdcConsumer(key) => key.encode(),
266 Self::View(key) => key.encode(),
267 Self::NamespaceView(key) => key.encode(),
268 Self::PrimaryKey(key) => key.encode(),
269 Self::OperatorState(key) => key.encode(),
270 Self::RingBuffer(key) => key.encode(),
271 Self::NamespaceRingBuffer(key) => key.encode(),
272 Self::RingBufferMetadata(key) => key.encode(),
273 Self::Flow(key) => key.encode(),
274 Self::NamespaceFlow(key) => key.encode(),
275 Self::Operator(key) => key.encode(),
276 Self::OperatorByFlow(key) => key.encode(),
277 Self::FlowEdge(key) => key.encode(),
278 Self::FlowEdgeByFlow(key) => key.encode(),
279 Self::OutputFrontier(key) => key.encode(),
280 Self::Dictionary(key) => key.encode(),
281 Self::DictionaryEntry(key) => key.encode(),
282 Self::DictionaryEntryIndex(key) => key.encode(),
283 Self::NamespaceDictionary(key) => key.encode(),
284 Self::Metric(MetricKey::Cdc(key)) => key.encode(),
285 Self::Metric(MetricKey::Storage(key)) => key.encode(),
286 Self::FlowVersion(key) => key.encode(),
287 Self::RowShape(key) => key.encode(),
288 Self::RowShapeField(key) => key.encode(),
289 Self::SumType(key) => key.encode(),
290 Self::NamespaceSumType(key) => key.encode(),
291 Self::Handler(key) => key.encode(),
292 Self::NamespaceHandler(key) => key.encode(),
293 Self::VariantHandler(key) => key.encode(),
294 Self::Series(key) => key.encode(),
295 Self::NamespaceSeries(key) => key.encode(),
296 Self::SeriesPartitionMetadata(key) => key.encode(),
297 Self::Identity(key) => key.encode(),
298 Self::Role(key) => key.encode(),
299 Self::GrantedRole(key) => key.encode(),
300 Self::Policy(key) => key.encode(),
301 Self::PolicyOp(key) => key.encode(),
302 Self::Migration(key) => key.encode(),
303 Self::MigrationEvent(key) => key.encode(),
304 Self::Authentication(key) => key.encode(),
305 Self::ConfigStorage(key) => key.encode(),
306 Self::Token(key) => key.encode(),
307 Self::Source(key) => key.encode(),
308 Self::NamespaceSource(key) => key.encode(),
309 Self::Sink(key) => key.encode(),
310 Self::NamespaceSink(key) => key.encode(),
311 Self::RowSettings(key) => key.encode(),
312 Self::Procedure(key) => key.encode(),
313 Self::NamespaceProcedure(key) => key.encode(),
314 Self::ProcedureParam(key) => key.encode(),
315 Self::Binding(key) => key.encode(),
316 Self::NamespaceBinding(key) => key.encode(),
317 Self::OperatorRetention(key) => key.encode(),
318 Self::ColumnBlock(key) => key.encode(),
319 Self::SeriesColumnBlock(key) => key.encode(),
320 Self::TableColumnBlock(key) => key.encode(),
321 Self::VersionEpoch(key) => key.encode(),
322 Self::IdentityAttribute(key) => key.encode(),
323 Self::IdentityAttributeValue(key) => key.encode(),
324 Self::PartitionedRow(key) => key.encode(),
325 Self::Partition(key) => key.encode(),
326 Self::Queue(key) => key.encode(),
327 Self::NamespaceQueue(key) => key.encode(),
328 Self::QueueDeduplication(key) => key.encode(),
329 Self::Relationship(key) => key.encode(),
330 Self::SeriesRow(key) => key.encode(),
331 Self::PartitionedSeriesRow(key) => key.encode(),
332 Self::QueuePartition(key) => key.encode(),
333 Self::QueueItemState(key) => key.encode(),
334 Self::QueueDue(key) => key.encode(),
335 Self::QueueAttempt(key) => key.encode(),
336 Self::QueueKeyActive(key) => key.encode(),
337 Self::SortedViewRow(key) => key.encode(),
338 Self::PartitionedSortedViewRow(key) => key.encode(),
339 }
340 }
341
342 pub fn decode(key: &EncodedKey) -> Option<Self> {
343 match KeyTag::of(key)? {
344 KeyTag::Namespace => NamespaceKey::decode(key).map(Self::Namespace),
345 KeyTag::Table => TableKey::decode(key).map(Self::Table),
346 KeyTag::Row => RowKey::decode(key).map(Self::Row),
347 KeyTag::NamespaceTable => NamespaceTableKey::decode(key).map(Self::NamespaceTable),
348 KeyTag::SystemSequence => SystemSequenceKey::decode(key).map(Self::SystemSequence),
349 KeyTag::Columns => ColumnsKey::decode(key).map(Self::Columns),
350 KeyTag::Column => ColumnKey::decode(key).map(Self::Column),
351 KeyTag::RowSequence => RowSequenceKey::decode(key).map(Self::RowSequence),
352 KeyTag::ColumnProperty => ColumnPropertyKey::decode(key).map(Self::ColumnProperty),
353 KeyTag::SystemVersion => SystemVersionKey::decode(key).map(Self::SystemVersion),
354 KeyTag::Index => IndexKey::decode(key).map(Self::Index),
355 KeyTag::IndexEntry => IndexEntryKey::decode(key).map(Self::IndexEntry),
356 KeyTag::ColumnSequence => ColumnSequenceKey::decode(key).map(Self::ColumnSequence),
357 KeyTag::CdcConsumer => CdcConsumerKey::decode(key).map(Self::CdcConsumer),
358 KeyTag::View => ViewKey::decode(key).map(Self::View),
359 KeyTag::NamespaceView => NamespaceViewKey::decode(key).map(Self::NamespaceView),
360 KeyTag::PrimaryKey => PrimaryKeyKey::decode(key).map(Self::PrimaryKey),
361 KeyTag::OperatorState => OperatorStateKey::decode(key).map(Self::OperatorState),
362 KeyTag::RingBuffer => RingBufferKey::decode(key).map(Self::RingBuffer),
363 KeyTag::NamespaceRingBuffer => {
364 NamespaceRingBufferKey::decode(key).map(Self::NamespaceRingBuffer)
365 }
366 KeyTag::RingBufferMetadata => RingBufferMetadataKey::decode(key).map(Self::RingBufferMetadata),
367 KeyTag::Flow => FlowKey::decode(key).map(Self::Flow),
368 KeyTag::NamespaceFlow => NamespaceFlowKey::decode(key).map(Self::NamespaceFlow),
369 KeyTag::Operator => OperatorKey::decode(key).map(Self::Operator),
370 KeyTag::OperatorByFlow => OperatorByFlowKey::decode(key).map(Self::OperatorByFlow),
371 KeyTag::FlowEdge => FlowEdgeKey::decode(key).map(Self::FlowEdge),
372 KeyTag::FlowEdgeByFlow => FlowEdgeByFlowKey::decode(key).map(Self::FlowEdgeByFlow),
373 KeyTag::OutputFrontier => OutputFrontierKey::decode(key).map(Self::OutputFrontier),
374 KeyTag::Dictionary => DictionaryKey::decode(key).map(Self::Dictionary),
375 KeyTag::DictionaryEntry => DictionaryEntryKey::decode(key).map(Self::DictionaryEntry),
376 KeyTag::DictionaryEntryIndex => {
377 DictionaryEntryIndexKey::decode(key).map(Self::DictionaryEntryIndex)
378 }
379 KeyTag::NamespaceDictionary => {
380 NamespaceDictionaryKey::decode(key).map(Self::NamespaceDictionary)
381 }
382 KeyTag::Metric => decode_metric(key),
383 KeyTag::FlowVersion => FlowVersionKey::decode(key).map(Self::FlowVersion),
384 KeyTag::RowShape => RowShapeKey::decode(key).map(Self::RowShape),
385 KeyTag::RowShapeField => RowShapeFieldKey::decode(key).map(Self::RowShapeField),
386 KeyTag::SumType => SumTypeKey::decode(key).map(Self::SumType),
387 KeyTag::NamespaceSumType => NamespaceSumTypeKey::decode(key).map(Self::NamespaceSumType),
388 KeyTag::Handler => HandlerKey::decode(key).map(Self::Handler),
389 KeyTag::NamespaceHandler => NamespaceHandlerKey::decode(key).map(Self::NamespaceHandler),
390 KeyTag::VariantHandler => VariantHandlerKey::decode(key).map(Self::VariantHandler),
391 KeyTag::Series => SeriesKey::decode(key).map(Self::Series),
392 KeyTag::NamespaceSeries => NamespaceSeriesKey::decode(key).map(Self::NamespaceSeries),
393 KeyTag::SeriesPartitionMetadata => {
394 SeriesPartitionMetadataKey::decode(key).map(Self::SeriesPartitionMetadata)
395 }
396 KeyTag::Identity => IdentityKey::decode(key).map(Self::Identity),
397 KeyTag::Role => RoleKey::decode(key).map(Self::Role),
398 KeyTag::GrantedRole => GrantedRoleKey::decode(key).map(Self::GrantedRole),
399 KeyTag::Policy => PolicyKey::decode(key).map(Self::Policy),
400 KeyTag::PolicyOp => PolicyOpKey::decode(key).map(Self::PolicyOp),
401 KeyTag::Migration => MigrationKey::decode(key).map(Self::Migration),
402 KeyTag::MigrationEvent => MigrationEventKey::decode(key).map(Self::MigrationEvent),
403 KeyTag::Authentication => AuthenticationKey::decode(key).map(Self::Authentication),
404 KeyTag::ConfigStorage => ConfigStorageKey::decode(key).map(Self::ConfigStorage),
405 KeyTag::Token => TokenKey::decode(key).map(Self::Token),
406 KeyTag::Source => SourceKey::decode(key).map(Self::Source),
407 KeyTag::NamespaceSource => NamespaceSourceKey::decode(key).map(Self::NamespaceSource),
408 KeyTag::Sink => SinkKey::decode(key).map(Self::Sink),
409 KeyTag::NamespaceSink => NamespaceSinkKey::decode(key).map(Self::NamespaceSink),
410 KeyTag::RowSettings => RowSettingsKey::decode(key).map(Self::RowSettings),
411 KeyTag::Procedure => ProcedureKey::decode(key).map(Self::Procedure),
412 KeyTag::NamespaceProcedure => NamespaceProcedureKey::decode(key).map(Self::NamespaceProcedure),
413 KeyTag::ProcedureParam => ProcedureParamKey::decode(key).map(Self::ProcedureParam),
414 KeyTag::Binding => BindingKey::decode(key).map(Self::Binding),
415 KeyTag::NamespaceBinding => NamespaceBindingKey::decode(key).map(Self::NamespaceBinding),
416 KeyTag::OperatorRetention => OperatorRetentionKey::decode(key).map(Self::OperatorRetention),
417 KeyTag::ColumnBlock => ColumnBlockKey::decode(key).map(Self::ColumnBlock),
418 KeyTag::SeriesColumnBlock => SeriesColumnBlockKey::decode(key).map(Self::SeriesColumnBlock),
419 KeyTag::TableColumnBlock => TableColumnBlockKey::decode(key).map(Self::TableColumnBlock),
420 KeyTag::VersionEpoch => VersionEpochKey::decode(key).map(Self::VersionEpoch),
421 KeyTag::IdentityAttribute => IdentityAttributeKey::decode(key).map(Self::IdentityAttribute),
422 KeyTag::IdentityAttributeValue => {
423 IdentityAttributeValueKey::decode(key).map(Self::IdentityAttributeValue)
424 }
425 KeyTag::PartitionedRow => PartitionedRowKey::decode(key).map(Self::PartitionedRow),
426 KeyTag::Partition => PartitionKey::decode(key).map(Self::Partition),
427 KeyTag::Queue => QueueKey::decode(key).map(Self::Queue),
428 KeyTag::NamespaceQueue => NamespaceQueueKey::decode(key).map(Self::NamespaceQueue),
429 KeyTag::QueueDeduplication => QueueDeduplicationKey::decode(key).map(Self::QueueDeduplication),
430 KeyTag::Relationship => RelationshipKey::decode(key).map(Self::Relationship),
431 KeyTag::SeriesRow => SeriesRowKey::decode(key).map(Self::SeriesRow),
432 KeyTag::PartitionedSeriesRow => {
433 PartitionedSeriesRowKey::decode(key).map(Self::PartitionedSeriesRow)
434 }
435 KeyTag::QueuePartition => QueuePartitionKey::decode(key).map(Self::QueuePartition),
436 KeyTag::QueueItemState => QueueItemStateKey::decode(key).map(Self::QueueItemState),
437 KeyTag::QueueDue => QueueDueKey::decode(key).map(Self::QueueDue),
438 KeyTag::QueueAttempt => QueueAttemptKey::decode(key).map(Self::QueueAttempt),
439 KeyTag::QueueKeyActive => QueueKeyActiveKey::decode(key).map(Self::QueueKeyActive),
440 KeyTag::SortedViewRow => SortedViewRowKey::decode(key).map(Self::SortedViewRow),
441 KeyTag::PartitionedSortedViewRow => {
442 PartitionedSortedViewRowKey::decode(key).map(Self::PartitionedSortedViewRow)
443 }
444 }
445 }
446}
447
448fn decode_metric(key: &EncodedKey) -> Option<TaggedKey> {
449 MetricStorageKey::decode(key)
450 .map(MetricKey::Storage)
451 .or_else(|| MetricCdcKey::decode(key).map(MetricKey::Cdc))
452 .map(TaggedKey::Metric)
453}
454
455impl From<NamespaceKey> for TaggedKey {
456 fn from(key: NamespaceKey) -> Self {
457 Self::Namespace(key)
458 }
459}
460
461impl From<TableKey> for TaggedKey {
462 fn from(key: TableKey) -> Self {
463 Self::Table(key)
464 }
465}
466
467impl From<RowKey> for TaggedKey {
468 fn from(key: RowKey) -> Self {
469 Self::Row(key)
470 }
471}
472
473impl From<NamespaceTableKey> for TaggedKey {
474 fn from(key: NamespaceTableKey) -> Self {
475 Self::NamespaceTable(key)
476 }
477}
478
479impl From<SystemSequenceKey> for TaggedKey {
480 fn from(key: SystemSequenceKey) -> Self {
481 Self::SystemSequence(key)
482 }
483}
484
485impl From<ColumnsKey> for TaggedKey {
486 fn from(key: ColumnsKey) -> Self {
487 Self::Columns(key)
488 }
489}
490
491impl From<ColumnKey> for TaggedKey {
492 fn from(key: ColumnKey) -> Self {
493 Self::Column(key)
494 }
495}
496
497impl From<RowSequenceKey> for TaggedKey {
498 fn from(key: RowSequenceKey) -> Self {
499 Self::RowSequence(key)
500 }
501}
502
503impl From<ColumnPropertyKey> for TaggedKey {
504 fn from(key: ColumnPropertyKey) -> Self {
505 Self::ColumnProperty(key)
506 }
507}
508
509impl From<SystemVersionKey> for TaggedKey {
510 fn from(key: SystemVersionKey) -> Self {
511 Self::SystemVersion(key)
512 }
513}
514
515impl From<IndexKey> for TaggedKey {
516 fn from(key: IndexKey) -> Self {
517 Self::Index(key)
518 }
519}
520
521impl From<IndexEntryKey> for TaggedKey {
522 fn from(key: IndexEntryKey) -> Self {
523 Self::IndexEntry(key)
524 }
525}
526
527impl From<ColumnSequenceKey> for TaggedKey {
528 fn from(key: ColumnSequenceKey) -> Self {
529 Self::ColumnSequence(key)
530 }
531}
532
533impl From<CdcConsumerKey> for TaggedKey {
534 fn from(key: CdcConsumerKey) -> Self {
535 Self::CdcConsumer(key)
536 }
537}
538
539impl From<ViewKey> for TaggedKey {
540 fn from(key: ViewKey) -> Self {
541 Self::View(key)
542 }
543}
544
545impl From<NamespaceViewKey> for TaggedKey {
546 fn from(key: NamespaceViewKey) -> Self {
547 Self::NamespaceView(key)
548 }
549}
550
551impl From<PrimaryKeyKey> for TaggedKey {
552 fn from(key: PrimaryKeyKey) -> Self {
553 Self::PrimaryKey(key)
554 }
555}
556
557impl From<OperatorStateKey> for TaggedKey {
558 fn from(key: OperatorStateKey) -> Self {
559 Self::OperatorState(key)
560 }
561}
562
563impl From<RingBufferKey> for TaggedKey {
564 fn from(key: RingBufferKey) -> Self {
565 Self::RingBuffer(key)
566 }
567}
568
569impl From<NamespaceRingBufferKey> for TaggedKey {
570 fn from(key: NamespaceRingBufferKey) -> Self {
571 Self::NamespaceRingBuffer(key)
572 }
573}
574
575impl From<RingBufferMetadataKey> for TaggedKey {
576 fn from(key: RingBufferMetadataKey) -> Self {
577 Self::RingBufferMetadata(key)
578 }
579}
580
581impl From<FlowKey> for TaggedKey {
582 fn from(key: FlowKey) -> Self {
583 Self::Flow(key)
584 }
585}
586
587impl From<NamespaceFlowKey> for TaggedKey {
588 fn from(key: NamespaceFlowKey) -> Self {
589 Self::NamespaceFlow(key)
590 }
591}
592
593impl From<OperatorKey> for TaggedKey {
594 fn from(key: OperatorKey) -> Self {
595 Self::Operator(key)
596 }
597}
598
599impl From<OperatorByFlowKey> for TaggedKey {
600 fn from(key: OperatorByFlowKey) -> Self {
601 Self::OperatorByFlow(key)
602 }
603}
604
605impl From<FlowEdgeKey> for TaggedKey {
606 fn from(key: FlowEdgeKey) -> Self {
607 Self::FlowEdge(key)
608 }
609}
610
611impl From<FlowEdgeByFlowKey> for TaggedKey {
612 fn from(key: FlowEdgeByFlowKey) -> Self {
613 Self::FlowEdgeByFlow(key)
614 }
615}
616
617impl From<OutputFrontierKey> for TaggedKey {
618 fn from(key: OutputFrontierKey) -> Self {
619 Self::OutputFrontier(key)
620 }
621}
622
623impl From<DictionaryKey> for TaggedKey {
624 fn from(key: DictionaryKey) -> Self {
625 Self::Dictionary(key)
626 }
627}
628
629impl From<DictionaryEntryKey> for TaggedKey {
630 fn from(key: DictionaryEntryKey) -> Self {
631 Self::DictionaryEntry(key)
632 }
633}
634
635impl From<DictionaryEntryIndexKey> for TaggedKey {
636 fn from(key: DictionaryEntryIndexKey) -> Self {
637 Self::DictionaryEntryIndex(key)
638 }
639}
640
641impl From<NamespaceDictionaryKey> for TaggedKey {
642 fn from(key: NamespaceDictionaryKey) -> Self {
643 Self::NamespaceDictionary(key)
644 }
645}
646
647impl From<FlowVersionKey> for TaggedKey {
648 fn from(key: FlowVersionKey) -> Self {
649 Self::FlowVersion(key)
650 }
651}
652
653impl From<RowShapeKey> for TaggedKey {
654 fn from(key: RowShapeKey) -> Self {
655 Self::RowShape(key)
656 }
657}
658
659impl From<RowShapeFieldKey> for TaggedKey {
660 fn from(key: RowShapeFieldKey) -> Self {
661 Self::RowShapeField(key)
662 }
663}
664
665impl From<SumTypeKey> for TaggedKey {
666 fn from(key: SumTypeKey) -> Self {
667 Self::SumType(key)
668 }
669}
670
671impl From<NamespaceSumTypeKey> for TaggedKey {
672 fn from(key: NamespaceSumTypeKey) -> Self {
673 Self::NamespaceSumType(key)
674 }
675}
676
677impl From<HandlerKey> for TaggedKey {
678 fn from(key: HandlerKey) -> Self {
679 Self::Handler(key)
680 }
681}
682
683impl From<NamespaceHandlerKey> for TaggedKey {
684 fn from(key: NamespaceHandlerKey) -> Self {
685 Self::NamespaceHandler(key)
686 }
687}
688
689impl From<VariantHandlerKey> for TaggedKey {
690 fn from(key: VariantHandlerKey) -> Self {
691 Self::VariantHandler(key)
692 }
693}
694
695impl From<SeriesKey> for TaggedKey {
696 fn from(key: SeriesKey) -> Self {
697 Self::Series(key)
698 }
699}
700
701impl From<NamespaceSeriesKey> for TaggedKey {
702 fn from(key: NamespaceSeriesKey) -> Self {
703 Self::NamespaceSeries(key)
704 }
705}
706
707impl From<SeriesPartitionMetadataKey> for TaggedKey {
708 fn from(key: SeriesPartitionMetadataKey) -> Self {
709 Self::SeriesPartitionMetadata(key)
710 }
711}
712
713impl From<IdentityKey> for TaggedKey {
714 fn from(key: IdentityKey) -> Self {
715 Self::Identity(key)
716 }
717}
718
719impl From<RoleKey> for TaggedKey {
720 fn from(key: RoleKey) -> Self {
721 Self::Role(key)
722 }
723}
724
725impl From<GrantedRoleKey> for TaggedKey {
726 fn from(key: GrantedRoleKey) -> Self {
727 Self::GrantedRole(key)
728 }
729}
730
731impl From<PolicyKey> for TaggedKey {
732 fn from(key: PolicyKey) -> Self {
733 Self::Policy(key)
734 }
735}
736
737impl From<PolicyOpKey> for TaggedKey {
738 fn from(key: PolicyOpKey) -> Self {
739 Self::PolicyOp(key)
740 }
741}
742
743impl From<MigrationKey> for TaggedKey {
744 fn from(key: MigrationKey) -> Self {
745 Self::Migration(key)
746 }
747}
748
749impl From<MigrationEventKey> for TaggedKey {
750 fn from(key: MigrationEventKey) -> Self {
751 Self::MigrationEvent(key)
752 }
753}
754
755impl From<AuthenticationKey> for TaggedKey {
756 fn from(key: AuthenticationKey) -> Self {
757 Self::Authentication(key)
758 }
759}
760
761impl From<ConfigStorageKey> for TaggedKey {
762 fn from(key: ConfigStorageKey) -> Self {
763 Self::ConfigStorage(key)
764 }
765}
766
767impl From<TokenKey> for TaggedKey {
768 fn from(key: TokenKey) -> Self {
769 Self::Token(key)
770 }
771}
772
773impl From<SourceKey> for TaggedKey {
774 fn from(key: SourceKey) -> Self {
775 Self::Source(key)
776 }
777}
778
779impl From<NamespaceSourceKey> for TaggedKey {
780 fn from(key: NamespaceSourceKey) -> Self {
781 Self::NamespaceSource(key)
782 }
783}
784
785impl From<SinkKey> for TaggedKey {
786 fn from(key: SinkKey) -> Self {
787 Self::Sink(key)
788 }
789}
790
791impl From<NamespaceSinkKey> for TaggedKey {
792 fn from(key: NamespaceSinkKey) -> Self {
793 Self::NamespaceSink(key)
794 }
795}
796
797impl From<RowSettingsKey> for TaggedKey {
798 fn from(key: RowSettingsKey) -> Self {
799 Self::RowSettings(key)
800 }
801}
802
803impl From<ProcedureKey> for TaggedKey {
804 fn from(key: ProcedureKey) -> Self {
805 Self::Procedure(key)
806 }
807}
808
809impl From<NamespaceProcedureKey> for TaggedKey {
810 fn from(key: NamespaceProcedureKey) -> Self {
811 Self::NamespaceProcedure(key)
812 }
813}
814
815impl From<ProcedureParamKey> for TaggedKey {
816 fn from(key: ProcedureParamKey) -> Self {
817 Self::ProcedureParam(key)
818 }
819}
820
821impl From<BindingKey> for TaggedKey {
822 fn from(key: BindingKey) -> Self {
823 Self::Binding(key)
824 }
825}
826
827impl From<NamespaceBindingKey> for TaggedKey {
828 fn from(key: NamespaceBindingKey) -> Self {
829 Self::NamespaceBinding(key)
830 }
831}
832
833impl From<OperatorRetentionKey> for TaggedKey {
834 fn from(key: OperatorRetentionKey) -> Self {
835 Self::OperatorRetention(key)
836 }
837}
838
839impl From<ColumnBlockKey> for TaggedKey {
840 fn from(key: ColumnBlockKey) -> Self {
841 Self::ColumnBlock(key)
842 }
843}
844
845impl From<SeriesColumnBlockKey> for TaggedKey {
846 fn from(key: SeriesColumnBlockKey) -> Self {
847 Self::SeriesColumnBlock(key)
848 }
849}
850
851impl From<TableColumnBlockKey> for TaggedKey {
852 fn from(key: TableColumnBlockKey) -> Self {
853 Self::TableColumnBlock(key)
854 }
855}
856
857impl From<VersionEpochKey> for TaggedKey {
858 fn from(key: VersionEpochKey) -> Self {
859 Self::VersionEpoch(key)
860 }
861}
862
863impl From<IdentityAttributeKey> for TaggedKey {
864 fn from(key: IdentityAttributeKey) -> Self {
865 Self::IdentityAttribute(key)
866 }
867}
868
869impl From<IdentityAttributeValueKey> for TaggedKey {
870 fn from(key: IdentityAttributeValueKey) -> Self {
871 Self::IdentityAttributeValue(key)
872 }
873}
874
875impl From<PartitionedRowKey> for TaggedKey {
876 fn from(key: PartitionedRowKey) -> Self {
877 Self::PartitionedRow(key)
878 }
879}
880
881impl From<PartitionKey> for TaggedKey {
882 fn from(key: PartitionKey) -> Self {
883 Self::Partition(key)
884 }
885}
886
887impl From<QueueKey> for TaggedKey {
888 fn from(key: QueueKey) -> Self {
889 Self::Queue(key)
890 }
891}
892
893impl From<NamespaceQueueKey> for TaggedKey {
894 fn from(key: NamespaceQueueKey) -> Self {
895 Self::NamespaceQueue(key)
896 }
897}
898
899impl From<QueueDeduplicationKey> for TaggedKey {
900 fn from(key: QueueDeduplicationKey) -> Self {
901 Self::QueueDeduplication(key)
902 }
903}
904
905impl From<RelationshipKey> for TaggedKey {
906 fn from(key: RelationshipKey) -> Self {
907 Self::Relationship(key)
908 }
909}
910
911impl From<SeriesRowKey> for TaggedKey {
912 fn from(key: SeriesRowKey) -> Self {
913 Self::SeriesRow(key)
914 }
915}
916
917impl From<PartitionedSeriesRowKey> for TaggedKey {
918 fn from(key: PartitionedSeriesRowKey) -> Self {
919 Self::PartitionedSeriesRow(key)
920 }
921}
922
923impl From<QueuePartitionKey> for TaggedKey {
924 fn from(key: QueuePartitionKey) -> Self {
925 Self::QueuePartition(key)
926 }
927}
928
929impl From<QueueItemStateKey> for TaggedKey {
930 fn from(key: QueueItemStateKey) -> Self {
931 Self::QueueItemState(key)
932 }
933}
934
935impl From<QueueDueKey> for TaggedKey {
936 fn from(key: QueueDueKey) -> Self {
937 Self::QueueDue(key)
938 }
939}
940
941impl From<QueueAttemptKey> for TaggedKey {
942 fn from(key: QueueAttemptKey) -> Self {
943 Self::QueueAttempt(key)
944 }
945}
946
947impl From<QueueKeyActiveKey> for TaggedKey {
948 fn from(key: QueueKeyActiveKey) -> Self {
949 Self::QueueKeyActive(key)
950 }
951}
952
953impl From<SortedViewRowKey> for TaggedKey {
954 fn from(key: SortedViewRowKey) -> Self {
955 Self::SortedViewRow(key)
956 }
957}
958
959impl From<PartitionedSortedViewRowKey> for TaggedKey {
960 fn from(key: PartitionedSortedViewRowKey) -> Self {
961 Self::PartitionedSortedViewRow(key)
962 }
963}
964
965impl From<MetricKey> for TaggedKey {
966 fn from(key: MetricKey) -> Self {
967 Self::Metric(key)
968 }
969}
970
971impl From<MetricStorageKey> for TaggedKey {
972 fn from(key: MetricStorageKey) -> Self {
973 Self::Metric(MetricKey::Storage(key))
974 }
975}
976
977impl From<MetricCdcKey> for TaggedKey {
978 fn from(key: MetricCdcKey) -> Self {
979 Self::Metric(MetricKey::Cdc(key))
980 }
981}
982
983fn desc<T: Ord + ?Sized>(left: &T, right: &T) -> Ordering {
984 right.cmp(left)
985}
986
987fn object_cmp(left: &ObjectId, right: &ObjectId) -> Ordering {
988 left.type_tag().cmp(&right.type_tag()).then_with(|| right.as_u64().cmp(&left.as_u64()))
989}
990
991pub(crate) fn index_tag(index: &IndexId) -> u8 {
992 match index {
993 IndexId::Primary(_) => 0x01,
994 }
995}
996
997fn tier_byte(tier: Tier) -> u8 {
998 match tier {
999 Tier::Buffer => 0x00,
1000 Tier::Persistent => 0x01,
1001 }
1002}
1003
1004fn metrics_id_cmp(left: &MetricsId, right: &MetricsId) -> Ordering {
1005 match (left, right) {
1006 (MetricsId::System, MetricsId::System) => Ordering::Equal,
1007 (MetricsId::System, MetricsId::Object(_)) => Ordering::Less,
1008 (MetricsId::Object(_), MetricsId::System) => Ordering::Greater,
1009 (MetricsId::Object(left), MetricsId::Object(right)) => object_cmp(left, right),
1010 }
1011}
1012
1013pub(crate) fn encode_values(values: &[Value]) -> EncodedKey {
1014 let mut serializer = KeySerializer::new();
1015 for value in values {
1016 serializer.extend_value(value);
1017 }
1018 serializer.to_encoded_key()
1019}
1020
1021impl Ord for MetricKey {
1022 fn cmp(&self, other: &Self) -> Ordering {
1023 match (self, other) {
1024 (Self::Cdc(left), Self::Cdc(right)) => metrics_id_cmp(&left.id, &right.id),
1025 (Self::Cdc(_), Self::Storage(_)) => Ordering::Less,
1026 (Self::Storage(_), Self::Cdc(_)) => Ordering::Greater,
1027 (Self::Storage(left), Self::Storage(right)) => {
1028 desc(&tier_byte(left.tier), &tier_byte(right.tier))
1029 .then_with(|| metrics_id_cmp(&left.id, &right.id))
1030 }
1031 }
1032 }
1033}
1034
1035impl PartialOrd for MetricKey {
1036 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1037 Some(self.cmp(other))
1038 }
1039}
1040
1041impl Eq for TaggedKey {}
1042
1043#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1044pub enum Width {
1045 U8,
1046 U16,
1047 U32,
1048 U64,
1049 U128,
1050 Varint,
1051}
1052
1053impl Width {
1054 fn byte_len(self) -> usize {
1055 match self {
1056 Self::U8 => 1,
1057 Self::U16 => 2,
1058 Self::U32 => 4,
1059 Self::U64 => 8,
1060 Self::U128 => 16,
1061 Self::Varint => 0,
1062 }
1063 }
1064}
1065
1066#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1067pub enum ByteEncoding {
1068 Fixed,
1069 Escaped,
1070}
1071
1072#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1073pub enum RawEncoding {
1074 Verbatim,
1075 SortRun,
1076}
1077
1078#[derive(Debug, Clone)]
1079pub enum Field<'a> {
1080 UAsc(Width, u128),
1081 UDesc(Width, u128),
1082 BytesDesc(ByteEncoding, Cow<'a, [u8]>),
1083 RawAsc(RawEncoding, Cow<'a, [u8]>),
1084}
1085
1086impl Field<'_> {
1087 fn variant_rank(&self) -> u8 {
1088 match self {
1089 Self::UAsc(..) => 0,
1090 Self::UDesc(..) => 1,
1091 Self::BytesDesc(..) => 2,
1092 Self::RawAsc(..) => 3,
1093 }
1094 }
1095
1096 pub fn encode(&self, out: &mut Vec<u8>) {
1097 match self {
1098 Self::UAsc(width, value) => {
1099 debug_assert!(
1100 !matches!(width, Width::Varint),
1101 "there is no ascending varint primitive in the key codec"
1102 );
1103 out.extend_from_slice(&value.to_be_bytes()[16 - width.byte_len()..]);
1104 }
1105 Self::UDesc(Width::Varint, value) => encode_u128_varint(*value, out),
1106 Self::UDesc(width, value) => {
1107 out.extend_from_slice(&(!*value).to_be_bytes()[16 - width.byte_len()..]);
1108 }
1109 Self::BytesDesc(ByteEncoding::Fixed, bytes) => out.extend(bytes.iter().map(|byte| !byte)),
1110 Self::BytesDesc(ByteEncoding::Escaped, bytes) => encode_bytes(bytes, out),
1111 Self::RawAsc(RawEncoding::Verbatim, bytes) => out.extend_from_slice(bytes),
1112 Self::RawAsc(RawEncoding::SortRun, bytes) => encode_sort_run(bytes, out),
1113 }
1114 }
1115}
1116
1117impl Ord for Field<'_> {
1118 fn cmp(&self, other: &Self) -> Ordering {
1119 match (self, other) {
1120 (Self::UAsc(_, left), Self::UAsc(_, right)) => left.cmp(right),
1121 (Self::UDesc(_, left), Self::UDesc(_, right)) => right.cmp(left),
1122 (Self::BytesDesc(_, left), Self::BytesDesc(_, right)) => right.as_ref().cmp(left.as_ref()),
1123 (Self::RawAsc(_, left), Self::RawAsc(_, right)) => left.as_ref().cmp(right.as_ref()),
1124 (left, right) => left.variant_rank().cmp(&right.variant_rank()),
1125 }
1126 }
1127}
1128
1129impl PartialOrd for Field<'_> {
1130 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1131 Some(self.cmp(other))
1132 }
1133}
1134
1135impl PartialEq for Field<'_> {
1136 fn eq(&self, other: &Self) -> bool {
1137 self.cmp(other) == Ordering::Equal
1138 }
1139}
1140
1141impl Eq for Field<'_> {}
1142
1143pub trait KeyFields {
1144 fn fields(&self) -> SmallVec<[Field<'_>; 6]>;
1145}
1146
1147impl KeyFields for MetricKey {
1148 fn fields(&self) -> SmallVec<[Field<'_>; 6]> {
1149 match self {
1150 Self::Cdc(key) => key.fields(),
1151 Self::Storage(key) => key.fields(),
1152 }
1153 }
1154}
1155
1156impl KeyFields for TaggedKey {
1157 fn fields(&self) -> SmallVec<[Field<'_>; 6]> {
1158 match self {
1159 Self::Namespace(key) => key.fields(),
1160 Self::Table(key) => key.fields(),
1161 Self::Row(key) => key.fields(),
1162 Self::NamespaceTable(key) => key.fields(),
1163 Self::SystemSequence(key) => key.fields(),
1164 Self::Columns(key) => key.fields(),
1165 Self::Column(key) => key.fields(),
1166 Self::RowSequence(key) => key.fields(),
1167 Self::ColumnProperty(key) => key.fields(),
1168 Self::SystemVersion(key) => key.fields(),
1169 Self::Index(key) => key.fields(),
1170 Self::IndexEntry(key) => key.fields(),
1171 Self::ColumnSequence(key) => key.fields(),
1172 Self::CdcConsumer(key) => key.fields(),
1173 Self::View(key) => key.fields(),
1174 Self::NamespaceView(key) => key.fields(),
1175 Self::PrimaryKey(key) => key.fields(),
1176 Self::OperatorState(key) => key.fields(),
1177 Self::RingBuffer(key) => key.fields(),
1178 Self::NamespaceRingBuffer(key) => key.fields(),
1179 Self::RingBufferMetadata(key) => key.fields(),
1180 Self::Flow(key) => key.fields(),
1181 Self::NamespaceFlow(key) => key.fields(),
1182 Self::Operator(key) => key.fields(),
1183 Self::OperatorByFlow(key) => key.fields(),
1184 Self::FlowEdge(key) => key.fields(),
1185 Self::FlowEdgeByFlow(key) => key.fields(),
1186 Self::OutputFrontier(key) => key.fields(),
1187 Self::Dictionary(key) => key.fields(),
1188 Self::DictionaryEntry(key) => key.fields(),
1189 Self::DictionaryEntryIndex(key) => key.fields(),
1190 Self::NamespaceDictionary(key) => key.fields(),
1191 Self::Metric(key) => key.fields(),
1192 Self::FlowVersion(key) => key.fields(),
1193 Self::RowShape(key) => key.fields(),
1194 Self::RowShapeField(key) => key.fields(),
1195 Self::SumType(key) => key.fields(),
1196 Self::NamespaceSumType(key) => key.fields(),
1197 Self::Handler(key) => key.fields(),
1198 Self::NamespaceHandler(key) => key.fields(),
1199 Self::VariantHandler(key) => key.fields(),
1200 Self::Series(key) => key.fields(),
1201 Self::NamespaceSeries(key) => key.fields(),
1202 Self::SeriesPartitionMetadata(key) => key.fields(),
1203 Self::Identity(key) => key.fields(),
1204 Self::Role(key) => key.fields(),
1205 Self::GrantedRole(key) => key.fields(),
1206 Self::Policy(key) => key.fields(),
1207 Self::PolicyOp(key) => key.fields(),
1208 Self::Migration(key) => key.fields(),
1209 Self::MigrationEvent(key) => key.fields(),
1210 Self::Authentication(key) => key.fields(),
1211 Self::ConfigStorage(key) => key.fields(),
1212 Self::Token(key) => key.fields(),
1213 Self::Source(key) => key.fields(),
1214 Self::NamespaceSource(key) => key.fields(),
1215 Self::Sink(key) => key.fields(),
1216 Self::NamespaceSink(key) => key.fields(),
1217 Self::RowSettings(key) => key.fields(),
1218 Self::Procedure(key) => key.fields(),
1219 Self::NamespaceProcedure(key) => key.fields(),
1220 Self::ProcedureParam(key) => key.fields(),
1221 Self::Binding(key) => key.fields(),
1222 Self::NamespaceBinding(key) => key.fields(),
1223 Self::OperatorRetention(key) => key.fields(),
1224 Self::ColumnBlock(key) => key.fields(),
1225 Self::SeriesColumnBlock(key) => key.fields(),
1226 Self::TableColumnBlock(key) => key.fields(),
1227 Self::VersionEpoch(key) => key.fields(),
1228 Self::IdentityAttribute(key) => key.fields(),
1229 Self::IdentityAttributeValue(key) => key.fields(),
1230 Self::PartitionedRow(key) => key.fields(),
1231 Self::Partition(key) => key.fields(),
1232 Self::Queue(key) => key.fields(),
1233 Self::NamespaceQueue(key) => key.fields(),
1234 Self::QueueDeduplication(key) => key.fields(),
1235 Self::Relationship(key) => key.fields(),
1236 Self::SeriesRow(key) => key.fields(),
1237 Self::PartitionedSeriesRow(key) => key.fields(),
1238 Self::QueuePartition(key) => key.fields(),
1239 Self::QueueItemState(key) => key.fields(),
1240 Self::QueueDue(key) => key.fields(),
1241 Self::QueueAttempt(key) => key.fields(),
1242 Self::QueueKeyActive(key) => key.fields(),
1243 Self::SortedViewRow(key) => key.fields(),
1244 Self::PartitionedSortedViewRow(key) => key.fields(),
1245 }
1246 }
1247}
1248
1249impl Ord for TaggedKey {
1250 fn cmp(&self, other: &Self) -> Ordering {
1251 match (self, other) {
1252 (Self::Namespace(left), Self::Namespace(right)) => left.cmp_fields(right),
1253 (Self::Table(left), Self::Table(right)) => left.cmp_fields(right),
1254 (Self::Row(left), Self::Row(right)) => left.cmp_fields(right),
1255 (Self::NamespaceTable(left), Self::NamespaceTable(right)) => left.cmp_fields(right),
1256 (Self::SystemSequence(left), Self::SystemSequence(right)) => left.cmp_fields(right),
1257 (Self::Columns(left), Self::Columns(right)) => left.cmp_fields(right),
1258 (Self::Column(left), Self::Column(right)) => left.cmp_fields(right),
1259 (Self::RowSequence(left), Self::RowSequence(right)) => left.cmp_fields(right),
1260 (Self::ColumnProperty(left), Self::ColumnProperty(right)) => left.cmp_fields(right),
1261 (Self::SystemVersion(left), Self::SystemVersion(right)) => left.cmp_fields(right),
1262 (Self::Index(left), Self::Index(right)) => left.cmp_fields(right),
1263 (Self::IndexEntry(left), Self::IndexEntry(right)) => left.cmp_fields(right),
1264 (Self::ColumnSequence(left), Self::ColumnSequence(right)) => left.cmp_fields(right),
1265 (Self::CdcConsumer(left), Self::CdcConsumer(right)) => left.cmp_fields(right),
1266 (Self::View(left), Self::View(right)) => left.cmp_fields(right),
1267 (Self::NamespaceView(left), Self::NamespaceView(right)) => left.cmp_fields(right),
1268 (Self::PrimaryKey(left), Self::PrimaryKey(right)) => left.cmp_fields(right),
1269 (Self::OperatorState(left), Self::OperatorState(right)) => left.cmp_fields(right),
1270 (Self::RingBuffer(left), Self::RingBuffer(right)) => left.cmp_fields(right),
1271 (Self::NamespaceRingBuffer(left), Self::NamespaceRingBuffer(right)) => left.cmp_fields(right),
1272 (Self::RingBufferMetadata(left), Self::RingBufferMetadata(right)) => left.cmp_fields(right),
1273 (Self::Flow(left), Self::Flow(right)) => left.cmp_fields(right),
1274 (Self::NamespaceFlow(left), Self::NamespaceFlow(right)) => left.cmp_fields(right),
1275 (Self::Operator(left), Self::Operator(right)) => left.cmp_fields(right),
1276 (Self::OperatorByFlow(left), Self::OperatorByFlow(right)) => left.cmp_fields(right),
1277 (Self::FlowEdge(left), Self::FlowEdge(right)) => left.cmp_fields(right),
1278 (Self::FlowEdgeByFlow(left), Self::FlowEdgeByFlow(right)) => left.cmp_fields(right),
1279 (Self::OutputFrontier(left), Self::OutputFrontier(right)) => left.cmp_fields(right),
1280 (Self::Dictionary(left), Self::Dictionary(right)) => left.cmp_fields(right),
1281 (Self::DictionaryEntry(left), Self::DictionaryEntry(right)) => left.cmp_fields(right),
1282 (Self::DictionaryEntryIndex(left), Self::DictionaryEntryIndex(right)) => left.cmp_fields(right),
1283 (Self::NamespaceDictionary(left), Self::NamespaceDictionary(right)) => left.cmp_fields(right),
1284 (Self::Metric(left), Self::Metric(right)) => left.cmp(right),
1285 (Self::FlowVersion(left), Self::FlowVersion(right)) => left.cmp_fields(right),
1286 (Self::RowShape(left), Self::RowShape(right)) => left.cmp_fields(right),
1287 (Self::RowShapeField(left), Self::RowShapeField(right)) => left.cmp_fields(right),
1288 (Self::SumType(left), Self::SumType(right)) => left.cmp_fields(right),
1289 (Self::NamespaceSumType(left), Self::NamespaceSumType(right)) => left.cmp_fields(right),
1290 (Self::Handler(left), Self::Handler(right)) => left.cmp_fields(right),
1291 (Self::NamespaceHandler(left), Self::NamespaceHandler(right)) => left.cmp_fields(right),
1292 (Self::VariantHandler(left), Self::VariantHandler(right)) => left.cmp_fields(right),
1293 (Self::Series(left), Self::Series(right)) => left.cmp_fields(right),
1294 (Self::NamespaceSeries(left), Self::NamespaceSeries(right)) => left.cmp_fields(right),
1295 (Self::SeriesPartitionMetadata(left), Self::SeriesPartitionMetadata(right)) => {
1296 left.cmp_fields(right)
1297 }
1298 (Self::Identity(left), Self::Identity(right)) => left.cmp_fields(right),
1299 (Self::Role(left), Self::Role(right)) => left.cmp_fields(right),
1300 (Self::GrantedRole(left), Self::GrantedRole(right)) => left.cmp_fields(right),
1301 (Self::Policy(left), Self::Policy(right)) => left.cmp_fields(right),
1302 (Self::PolicyOp(left), Self::PolicyOp(right)) => left.cmp_fields(right),
1303 (Self::Migration(left), Self::Migration(right)) => left.cmp_fields(right),
1304 (Self::MigrationEvent(left), Self::MigrationEvent(right)) => left.cmp_fields(right),
1305 (Self::Authentication(left), Self::Authentication(right)) => left.cmp_fields(right),
1306 (Self::ConfigStorage(left), Self::ConfigStorage(right)) => left.cmp_fields(right),
1307 (Self::Token(left), Self::Token(right)) => left.cmp_fields(right),
1308 (Self::Source(left), Self::Source(right)) => left.cmp_fields(right),
1309 (Self::NamespaceSource(left), Self::NamespaceSource(right)) => left.cmp_fields(right),
1310 (Self::Sink(left), Self::Sink(right)) => left.cmp_fields(right),
1311 (Self::NamespaceSink(left), Self::NamespaceSink(right)) => left.cmp_fields(right),
1312 (Self::RowSettings(left), Self::RowSettings(right)) => left.cmp_fields(right),
1313 (Self::Procedure(left), Self::Procedure(right)) => left.cmp_fields(right),
1314 (Self::NamespaceProcedure(left), Self::NamespaceProcedure(right)) => left.cmp_fields(right),
1315 (Self::ProcedureParam(left), Self::ProcedureParam(right)) => left.cmp_fields(right),
1316 (Self::Binding(left), Self::Binding(right)) => left.cmp_fields(right),
1317 (Self::NamespaceBinding(left), Self::NamespaceBinding(right)) => left.cmp_fields(right),
1318 (Self::OperatorRetention(left), Self::OperatorRetention(right)) => left.cmp_fields(right),
1319 (Self::ColumnBlock(left), Self::ColumnBlock(right)) => left.cmp_fields(right),
1320 (Self::SeriesColumnBlock(left), Self::SeriesColumnBlock(right)) => left.cmp_fields(right),
1321 (Self::TableColumnBlock(left), Self::TableColumnBlock(right)) => left.cmp_fields(right),
1322 (Self::VersionEpoch(left), Self::VersionEpoch(right)) => left.cmp_fields(right),
1323 (Self::IdentityAttribute(left), Self::IdentityAttribute(right)) => left.cmp_fields(right),
1324 (Self::IdentityAttributeValue(left), Self::IdentityAttributeValue(right)) => {
1325 left.cmp_fields(right)
1326 }
1327 (Self::PartitionedRow(left), Self::PartitionedRow(right)) => left.cmp_fields(right),
1328 (Self::Partition(left), Self::Partition(right)) => left.cmp_fields(right),
1329 (Self::Queue(left), Self::Queue(right)) => left.cmp_fields(right),
1330 (Self::NamespaceQueue(left), Self::NamespaceQueue(right)) => left.cmp_fields(right),
1331 (Self::QueueDeduplication(left), Self::QueueDeduplication(right)) => left.cmp_fields(right),
1332 (Self::Relationship(left), Self::Relationship(right)) => left.cmp_fields(right),
1333 (Self::SeriesRow(left), Self::SeriesRow(right)) => left.cmp_fields(right),
1334 (Self::PartitionedSeriesRow(left), Self::PartitionedSeriesRow(right)) => left.cmp_fields(right),
1335 (Self::QueuePartition(left), Self::QueuePartition(right)) => left.cmp_fields(right),
1336 (Self::QueueItemState(left), Self::QueueItemState(right)) => left.cmp_fields(right),
1337 (Self::QueueDue(left), Self::QueueDue(right)) => left.cmp_fields(right),
1338 (Self::QueueAttempt(left), Self::QueueAttempt(right)) => left.cmp_fields(right),
1339 (Self::QueueKeyActive(left), Self::QueueKeyActive(right)) => left.cmp_fields(right),
1340 (Self::SortedViewRow(left), Self::SortedViewRow(right)) => left.cmp_fields(right),
1341 (Self::PartitionedSortedViewRow(left), Self::PartitionedSortedViewRow(right)) => {
1342 left.cmp_fields(right)
1343 }
1344 _ => desc(&(self.kind() as u8), &(other.kind() as u8))
1345 .then_with(|| self.fields().cmp(&other.fields())),
1346 }
1347 }
1348}
1349
1350impl PartialOrd for TaggedKey {
1351 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1352 Some(self.cmp(other))
1353 }
1354}
1355
1356#[cfg(test)]
1357mod tests {
1358 use std::{borrow::Cow, cmp::Ordering};
1359
1360 use reifydb_codec::{key::encoded::EncodedKey, row::shape::fingerprint::RowShapeFingerprint};
1361 use reifydb_runtime::version_epoch::EpochSeconds;
1362 use reifydb_value::value::{
1363 Value, datetime::DateTime, dictionary::DictionaryId, identity::IdentityId, partition::Partition,
1364 row_number::RowNumber, sumtype::SumTypeId,
1365 };
1366 use smallvec::SmallVec;
1367
1368 use super::{Field, KeyFields, MetricCdcKey, MetricKey, MetricStorageKey, RawEncoding, TaggedKey};
1369 use crate::{
1370 interface::{
1371 catalog::{
1372 config::ConfigKey,
1373 flow::{FlowEdgeId, FlowId, OperatorId},
1374 id::{
1375 BindingId, ColumnBlockId, ColumnId, ColumnPropertyId, HandlerId, IndexId,
1376 MigrationEventId, MigrationId, NamespaceId, PrimaryKeyId, ProcedureId, QueueId,
1377 RelationshipId, RingBufferId, SequenceId, SeriesId, SinkId, SourceId, TableId,
1378 ViewId,
1379 },
1380 metrics::MetricsId,
1381 object::ObjectId,
1382 storage::StorageId,
1383 },
1384 cdc::CdcConsumerId,
1385 store::Tier,
1386 },
1387 key::{
1388 bound::{OwnedField, TaggedKeyBound},
1389 catalog::{
1390 BindingKey, ColumnPropertyKey, DictionaryEntryIndexKey, DictionaryEntryKey,
1391 DictionaryKey, HandlerKey, IndexEntryKey, IndexKey, PrimaryKeyKey, RelationshipKey,
1392 SinkKey, SourceKey, SumTypeKey, TableKey, VariantHandlerKey, ViewKey,
1393 },
1394 cdc::CdcConsumerKey,
1395 column::{
1396 ColumnBlockKey, ColumnKey, ColumnSequenceKey, ColumnsKey, SeriesColumnBlockKey,
1397 TableColumnBlockKey,
1398 },
1399 config::ConfigStorageKey,
1400 flow::{FlowEdgeByFlowKey, FlowEdgeKey, FlowKey, FlowVersionKey},
1401 identity::{
1402 AuthenticationKey, GrantedRoleKey, IdentityAttributeKey, IdentityAttributeValueKey,
1403 IdentityKey, PolicyKey, PolicyOpKey, RoleKey, TokenKey,
1404 },
1405 namespace::{
1406 NamespaceBindingKey, NamespaceDictionaryKey, NamespaceFlowKey, NamespaceHandlerKey,
1407 NamespaceKey, NamespaceProcedureKey, NamespaceQueueKey, NamespaceRingBufferKey,
1408 NamespaceSeriesKey, NamespaceSinkKey, NamespaceSourceKey, NamespaceSumTypeKey,
1409 NamespaceTableKey, NamespaceViewKey,
1410 },
1411 operator::{
1412 key::{OperatorByFlowKey, OperatorKey},
1413 state::{GroupId, KeyspaceId, OperatorStateKey},
1414 },
1415 operator_retention::OperatorRetentionKey,
1416 output_frontier::OutputFrontierKey,
1417 partition::PartitionKey,
1418 procedure::{ProcedureKey, ProcedureParamKey},
1419 queue::{
1420 QueueAttemptKey, QueueDeduplicationKey, QueueDueKey, QueueItemStateKey, QueueKey,
1421 QueueKeyActiveKey, QueuePartitionKey,
1422 },
1423 ringbuffer::{RingBufferKey, RingBufferMetadataKey},
1424 row::{
1425 PartitionedRowKey, PartitionedSortedViewRowKey, RowKey, RowSequenceKey, RowSettingsKey,
1426 RowShapeFieldKey, RowShapeKey, SortedViewRowKey,
1427 },
1428 series::{PartitionedSeriesRowKey, SeriesKey, SeriesPartitionMetadataKey, SeriesRowKey},
1429 sort_run::SortRun,
1430 system::{
1431 MigrationEventKey, MigrationKey, SystemSequenceKey, SystemVersion, SystemVersionKey,
1432 VersionEpochKey,
1433 },
1434 tag::KeyTag,
1435 },
1436 value::index::encoded::EncodedIndexKey,
1437 };
1438
1439 fn probe<K>(key: K) -> (TaggedKey, EncodedKey)
1440 where
1441 TaggedKey: From<K>,
1442 {
1443 let key = TaggedKey::from(key);
1444 let encoded = key.encode();
1445 (key, encoded)
1446 }
1447
1448 fn probe_encodable<K>(key: K) -> (TaggedKey, EncodedKey)
1449 where
1450 TaggedKey: From<K>,
1451 {
1452 let key = TaggedKey::from(key);
1453 let encoded = key.encode();
1454 (key, encoded)
1455 }
1456
1457 fn assert_ascending(probes: &[(TaggedKey, EncodedKey)]) {
1458 for pair in probes.windows(2) {
1459 let (left, left_bytes) = &pair[0];
1460 let (right, right_bytes) = &pair[1];
1461 assert_eq!(left.cmp(right), Ordering::Less, "{left:?} must sort before {right:?}");
1462 assert!(left_bytes < right_bytes, "{left:?} must encode before {right:?}");
1463 }
1464 }
1465
1466 fn dictionary_entry(dictionary: u64, hash: u8) -> DictionaryEntryKey {
1467 DictionaryEntryKey {
1468 dictionary: DictionaryId(dictionary),
1469 hash: [hash; 16],
1470 }
1471 }
1472
1473 fn series_row(variant_tag: Option<u8>) -> SeriesRowKey {
1474 SeriesRowKey {
1475 storage: StorageId::series(1),
1476 variant_tag,
1477 key: 0,
1478 sequence: 0,
1479 }
1480 }
1481
1482 fn consumer(name: &str) -> CdcConsumerKey {
1483 CdcConsumerKey {
1484 consumer: CdcConsumerId::new(name),
1485 }
1486 }
1487
1488 #[test]
1489 fn test_cross_kind_order_reverses_the_discriminant() {
1490 let mut probes = [
1493 probe(NamespaceKey {
1494 namespace: NamespaceId(1),
1495 }),
1496 probe(RowKey {
1497 storage: StorageId::table(1),
1498 row: RowNumber(1),
1499 }),
1500 probe_encodable(consumer("a")),
1501 probe(MetricCdcKey::new(MetricsId::System)),
1502 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::System)),
1503 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x10u8]), RowNumber(1))),
1504 probe(PartitionedSortedViewRowKey::new(
1505 StorageId::view(1),
1506 Partition(1),
1507 SortRun::new([0x10u8]),
1508 RowNumber(1),
1509 )),
1510 ];
1511 probes.sort_by(|left, right| left.0.cmp(&right.0));
1512
1513 let encoded: Vec<EncodedKey> = probes.iter().map(|(_, bytes)| bytes.clone()).collect();
1514 let mut expected = encoded.clone();
1515 expected.sort();
1516 assert_eq!(encoded, expected);
1517
1518 assert_eq!(probes.first().unwrap().0.kind(), KeyTag::PartitionedSortedViewRow);
1519 assert_eq!(probes.last().unwrap().0.kind(), KeyTag::Namespace);
1520 }
1521
1522 #[test]
1523 fn test_object_id_tag_ascends_while_its_id_descends() {
1524 assert_ascending(&[
1527 probe(ColumnKey {
1528 object: ObjectId::table(2),
1529 column: ColumnId(1),
1530 }),
1531 probe(ColumnKey {
1532 object: ObjectId::table(1),
1533 column: ColumnId(1),
1534 }),
1535 probe(ColumnKey {
1536 object: ObjectId::view(2),
1537 column: ColumnId(1),
1538 }),
1539 probe(ColumnKey {
1540 object: ObjectId::view(1),
1541 column: ColumnId(1),
1542 }),
1543 ]);
1544 }
1545
1546 #[test]
1547 fn test_series_row_variant_tag_polarity() {
1548 assert_ascending(&[probe(series_row(Some(2))), probe(series_row(Some(1))), probe(series_row(None))]);
1551 }
1552
1553 #[test]
1554 fn test_partitioned_series_row_variant_tag_polarity() {
1555 let partitioned = |variant_tag| PartitionedSeriesRowKey {
1556 storage: StorageId::series(1),
1557 partition: Partition(1),
1558 variant_tag,
1559 key: 0,
1560 sequence: 0,
1561 };
1562 assert_ascending(&[probe(partitioned(Some(2))), probe(partitioned(Some(1))), probe(partitioned(None))]);
1563 }
1564
1565 #[test]
1566 fn test_cdc_consumer_name_sorts_descending() {
1567 assert_ascending(&[
1570 probe_encodable(consumer("c")),
1571 probe_encodable(consumer("b")),
1572 probe_encodable(consumer("ab")),
1573 probe_encodable(consumer("a")),
1574 ]);
1575 }
1576
1577 #[test]
1578 fn test_config_key_sorts_by_its_rendered_name_not_its_discriminant() {
1579 assert_ascending(&[
1581 probe_encodable(ConfigStorageKey::new(ConfigKey::QueryRowBatchSize)),
1582 probe_encodable(ConfigStorageKey::new(ConfigKey::OracleWindowSize)),
1583 ]);
1584 }
1585
1586 #[test]
1587 fn test_dictionary_entry_hash_sorts_ascending() {
1588 assert_ascending(&[
1590 probe(dictionary_entry(2, 0xFF)),
1591 probe(dictionary_entry(1, 0x00)),
1592 probe(dictionary_entry(1, 0x01)),
1593 ]);
1594 }
1595
1596 #[test]
1597 fn test_metric_cdc_sorts_before_metric_storage() {
1598 assert_ascending(&[
1601 probe(MetricCdcKey::new(MetricsId::System)),
1602 probe(MetricCdcKey::new(MetricsId::Object(ObjectId::table(2)))),
1603 probe(MetricCdcKey::new(MetricsId::Object(ObjectId::table(1)))),
1604 probe(MetricStorageKey::new(Tier::Persistent, MetricsId::System)),
1605 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::System)),
1606 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::Object(ObjectId::table(1)))),
1607 ]);
1608 }
1609
1610 #[test]
1611 fn test_index_and_index_entry_encode_the_index_id_differently() {
1612 assert_ascending(&[
1615 probe(IndexKey {
1616 object: ObjectId::table(1),
1617 index: IndexId::primary(PrimaryKeyId(2)),
1618 }),
1619 probe(IndexKey {
1620 object: ObjectId::table(1),
1621 index: IndexId::primary(PrimaryKeyId(1)),
1622 }),
1623 ]);
1624 assert_ascending(&[
1625 probe_encodable(IndexEntryKey::new(
1626 ObjectId::table(1),
1627 IndexId::primary(PrimaryKeyId(1)),
1628 EncodedIndexKey::new([0x01u8]),
1629 )),
1630 probe_encodable(IndexEntryKey::new(
1631 ObjectId::table(1),
1632 IndexId::primary(PrimaryKeyId(1)),
1633 EncodedIndexKey::new([0x02u8]),
1634 )),
1635 ]);
1636 }
1637
1638 #[test]
1639 fn test_operator_state_suffix_sorts_ascending_under_descending_fields() {
1640 assert_ascending(&[
1643 probe_encodable(OperatorStateKey::new(OperatorId(1), GroupId::ROOT, KeyspaceId(2), [0x01u8])),
1644 probe_encodable(OperatorStateKey::new(OperatorId(1), GroupId::ROOT, KeyspaceId(2), [0x02u8])),
1645 probe_encodable(OperatorStateKey::new(OperatorId(1), GroupId::ROOT, KeyspaceId(1), [0x00u8])),
1646 ]);
1647 }
1648
1649 fn probes() -> Vec<(TaggedKey, EncodedKey)> {
1650 vec![
1651 probe(NamespaceKey {
1652 namespace: NamespaceId(1),
1653 }),
1654 probe(NamespaceKey {
1655 namespace: NamespaceId(2),
1656 }),
1657 probe(RowKey {
1658 storage: StorageId::table(1),
1659 row: RowNumber(1),
1660 }),
1661 probe(RowKey {
1662 storage: StorageId::table(1),
1663 row: RowNumber(2),
1664 }),
1665 probe(RowKey {
1666 storage: StorageId::view(1),
1667 row: RowNumber(1),
1668 }),
1669 probe(ColumnKey {
1670 object: ObjectId::table(1),
1671 column: ColumnId(1),
1672 }),
1673 probe(ColumnKey {
1674 object: ObjectId::queue(1),
1675 column: ColumnId(1),
1676 }),
1677 probe(IndexKey {
1678 object: ObjectId::table(1),
1679 index: IndexId::primary(PrimaryKeyId(1)),
1680 }),
1681 probe_encodable(IndexEntryKey::new(
1682 ObjectId::table(1),
1683 IndexId::primary(PrimaryKeyId(1)),
1684 EncodedIndexKey::new([0x01u8]),
1685 )),
1686 probe_encodable(IndexEntryKey::new(
1687 ObjectId::table(1),
1688 IndexId::primary(PrimaryKeyId(1)),
1689 EncodedIndexKey::new([0x01u8, 0x02]),
1690 )),
1691 probe_encodable(consumer("a")),
1692 probe_encodable(consumer("ab")),
1693 probe_encodable(consumer("b")),
1694 probe(dictionary_entry(1, 0x00)),
1695 probe(dictionary_entry(1, 0xFF)),
1696 probe(dictionary_entry(2, 0x00)),
1697 probe_encodable(DictionaryEntryIndexKey::new(DictionaryId(1), 1)),
1698 probe_encodable(DictionaryEntryIndexKey::new(DictionaryId(1), 1 << 20)),
1699 probe_encodable(DictionaryEntryIndexKey::new(DictionaryId(1), u128::from(u64::MAX) + 5)),
1700 probe_encodable(OperatorStateKey::new(OperatorId(1), GroupId::ROOT, KeyspaceId(1), [0x00u8])),
1701 probe_encodable(OperatorStateKey::new(OperatorId(1), GroupId::MAX, KeyspaceId(1), [0x00u8])),
1702 probe_encodable(ConfigStorageKey::new(ConfigKey::OracleWindowSize)),
1703 probe_encodable(ConfigStorageKey::new(ConfigKey::QueryRowBatchSize)),
1704 probe(series_row(Some(0))),
1705 probe(series_row(Some(7))),
1706 probe(series_row(None)),
1707 probe(QueueDueKey {
1708 queue: QueueId(1),
1709 partition: 0,
1710 due: DateTime::from_order(1),
1711 row: RowNumber(1),
1712 }),
1713 probe(QueueDueKey {
1714 queue: QueueId(1),
1715 partition: 0,
1716 due: DateTime::from_order(2),
1717 row: RowNumber(1),
1718 }),
1719 probe_encodable(QueueDeduplicationKey::new(QueueId(1), [0x01u8])),
1720 probe_encodable(QueueDeduplicationKey::new(QueueId(1), [0x01u8, 0x02])),
1721 probe_encodable(RingBufferMetadataKey::new(StorageId::ringbuffer(1))),
1722 probe_encodable(RingBufferMetadataKey::partition(
1723 StorageId::ringbuffer(1),
1724 vec![Value::Uint8(1)],
1725 )),
1726 probe_encodable(RingBufferMetadataKey::partition(
1727 StorageId::ringbuffer(1),
1728 vec![Value::Uint8(2)],
1729 )),
1730 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x10u8]), RowNumber(1))),
1731 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x10u8]), RowNumber(2))),
1732 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x20u8]), RowNumber(1))),
1733 probe(PartitionedSortedViewRowKey::new(
1734 StorageId::view(1),
1735 Partition(1),
1736 SortRun::new([0x10u8]),
1737 RowNumber(1),
1738 )),
1739 probe(PartitionedSortedViewRowKey::new(
1740 StorageId::view(1),
1741 Partition(2),
1742 SortRun::new([0x10u8]),
1743 RowNumber(1),
1744 )),
1745 probe(MetricCdcKey::new(MetricsId::System)),
1746 probe(MetricCdcKey::new(MetricsId::Object(ObjectId::table(1)))),
1747 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::System)),
1748 probe(MetricStorageKey::new(Tier::Persistent, MetricsId::System)),
1749 probe(SystemVersionKey {
1750 version: SystemVersion::Storage,
1751 }),
1752 probe(TableKey {
1753 table: TableId(1),
1754 }),
1755 ]
1756 }
1757
1758 #[test]
1759 fn test_ord_agrees_with_encoded_order_for_every_pair() {
1760 let probes = probes();
1763 for (left, left_bytes) in &probes {
1764 for (right, right_bytes) in &probes {
1765 assert_eq!(left.cmp(right), left_bytes.cmp(right_bytes), "{left:?} vs {right:?}");
1766 }
1767 }
1768 }
1769 fn assert_projection_matches_bytes(samples: Vec<(TaggedKey, EncodedKey)>, label: &str) {
1770 assert!(samples.len() >= 2, "{label} needs at least two samples to exercise a direction");
1771 for (left, left_bytes) in &samples {
1772 for (right, right_bytes) in &samples {
1773 let projected = (right.kind() as u8)
1774 .cmp(&(left.kind() as u8))
1775 .then_with(|| left.fields().cmp(&right.fields()));
1776 assert_eq!(
1777 projected,
1778 left_bytes.cmp(right_bytes),
1779 "{label}: kind and fields() disagree with encoded byte order\n a = \
1780 {left:?}\n b = {right:?}\n a bytes = {:?}\n b bytes = {:?}",
1781 left_bytes.as_slice(),
1782 right_bytes.as_slice()
1783 );
1784 }
1785 }
1786 }
1787
1788 fn encode_via_fields(key: &TaggedKey) -> EncodedKey {
1789 let mut out = vec![!(key.kind() as u8)];
1790 for field in key.fields().iter() {
1791 field.encode(&mut out);
1792 }
1793 EncodedKey::new(out)
1794 }
1795
1796 #[test]
1797 fn every_projection_replays_the_exact_bytes_its_encoder_wrote() {
1798 let probes = all_probes();
1803 assert!(probes.len() >= 80, "the byte replay is only worth running over every key type");
1804 for (key, encoded) in probes {
1805 assert_eq!(encode_via_fields(&key), encoded, "{key:?}");
1806 }
1807 }
1808
1809 #[test]
1810 fn every_hand_written_key_projects_to_the_order_its_encoder_produces() {
1811 assert_projection_matches_bytes(
1814 vec![
1815 probe(BindingKey {
1816 binding: BindingId(1),
1817 }),
1818 probe(BindingKey {
1819 binding: BindingId(2),
1820 }),
1821 ],
1822 "BindingKey",
1823 );
1824 assert_projection_matches_bytes(
1825 vec![
1826 probe(ProcedureKey {
1827 procedure: ProcedureId::persistent(1),
1828 }),
1829 probe(ProcedureKey {
1830 procedure: ProcedureId::persistent(2),
1831 }),
1832 ],
1833 "ProcedureKey",
1834 );
1835 assert_projection_matches_bytes(
1836 vec![
1837 probe(ProcedureParamKey {
1838 procedure: ProcedureId::persistent(1),
1839 param_index: 1,
1840 }),
1841 probe(ProcedureParamKey {
1842 procedure: ProcedureId::persistent(1),
1843 param_index: 2,
1844 }),
1845 probe(ProcedureParamKey {
1846 procedure: ProcedureId::persistent(2),
1847 param_index: 1,
1848 }),
1849 ],
1850 "ProcedureParamKey",
1851 );
1852 assert_projection_matches_bytes(
1853 vec![
1854 probe(SinkKey {
1855 sink: SinkId(1),
1856 }),
1857 probe(SinkKey {
1858 sink: SinkId(2),
1859 }),
1860 ],
1861 "SinkKey",
1862 );
1863 assert_projection_matches_bytes(
1864 vec![
1865 probe(SourceKey {
1866 source: SourceId(1),
1867 }),
1868 probe(SourceKey {
1869 source: SourceId(2),
1870 }),
1871 ],
1872 "SourceKey",
1873 );
1874 assert_projection_matches_bytes(
1875 vec![
1876 probe(ViewKey {
1877 view: ViewId(1),
1878 }),
1879 probe(ViewKey {
1880 view: ViewId(2),
1881 }),
1882 ],
1883 "ViewKey",
1884 );
1885 assert_projection_matches_bytes(
1886 vec![
1887 probe(SumTypeKey {
1888 sumtype: SumTypeId(1),
1889 }),
1890 probe(SumTypeKey {
1891 sumtype: SumTypeId(2),
1892 }),
1893 ],
1894 "SumTypeKey",
1895 );
1896 assert_projection_matches_bytes(
1897 vec![
1898 probe_encodable(DictionaryEntryIndexKey {
1899 dictionary: DictionaryId(1),
1900 id: 1,
1901 }),
1902 probe_encodable(DictionaryEntryIndexKey {
1903 dictionary: DictionaryId(1),
1904 id: u128::from(u64::MAX) + 1,
1905 }),
1906 probe_encodable(DictionaryEntryIndexKey {
1907 dictionary: DictionaryId(2),
1908 id: 1,
1909 }),
1910 ],
1911 "DictionaryEntryIndexKey",
1912 );
1913 assert_projection_matches_bytes(
1914 vec![
1915 probe_encodable(IndexEntryKey::new(
1916 ObjectId::table(1),
1917 IndexId::primary(PrimaryKeyId(1)),
1918 EncodedIndexKey::new([0x01u8]),
1919 )),
1920 probe_encodable(IndexEntryKey::new(
1921 ObjectId::table(1),
1922 IndexId::primary(PrimaryKeyId(1)),
1923 EncodedIndexKey::new([0x02u8]),
1924 )),
1925 probe_encodable(IndexEntryKey::new(
1926 ObjectId::table(1),
1927 IndexId::primary(PrimaryKeyId(2)),
1928 EncodedIndexKey::new([0x01u8]),
1929 )),
1930 probe_encodable(IndexEntryKey::new(
1931 ObjectId::view(1),
1932 IndexId::primary(PrimaryKeyId(1)),
1933 EncodedIndexKey::new([0x01u8]),
1934 )),
1935 ],
1936 "IndexEntryKey",
1937 );
1938 assert_projection_matches_bytes(
1939 vec![
1940 probe_encodable(CdcConsumerKey::new(CdcConsumerId::new("a"))),
1941 probe_encodable(CdcConsumerKey::new(CdcConsumerId::new("b"))),
1942 probe_encodable(CdcConsumerKey::new(CdcConsumerId::new("ab"))),
1943 ],
1944 "CdcConsumerKey",
1945 );
1946 assert_projection_matches_bytes(
1947 vec![
1948 probe_encodable(ConfigStorageKey::new(ConfigKey::QueryRowBatchSize)),
1949 probe_encodable(ConfigStorageKey::new(ConfigKey::OracleWindowSize)),
1950 ],
1951 "ConfigStorageKey",
1952 );
1953 assert_projection_matches_bytes(
1954 vec![
1955 probe_encodable(QueueDeduplicationKey::new(QueueId(1), [0x01u8])),
1956 probe_encodable(QueueDeduplicationKey::new(QueueId(1), [0x02u8])),
1957 probe_encodable(QueueDeduplicationKey::new(QueueId(1), [0x01u8, 0x00])),
1958 probe_encodable(QueueDeduplicationKey::new(QueueId(2), [0x01u8])),
1959 ],
1960 "QueueDeduplicationKey",
1961 );
1962 assert_projection_matches_bytes(
1963 vec![
1964 probe_encodable(OperatorStateKey::new(
1965 OperatorId(1),
1966 GroupId::ROOT,
1967 KeyspaceId(1),
1968 [0x01u8],
1969 )),
1970 probe_encodable(OperatorStateKey::new(
1971 OperatorId(1),
1972 GroupId::ROOT,
1973 KeyspaceId(1),
1974 [0x02u8],
1975 )),
1976 probe_encodable(OperatorStateKey::new(
1977 OperatorId(1),
1978 GroupId::ROOT,
1979 KeyspaceId(2),
1980 [0x01u8],
1981 )),
1982 probe_encodable(OperatorStateKey::new(
1983 OperatorId(1),
1984 GroupId::from_bytes([0x01u8; 24]),
1985 KeyspaceId(1),
1986 [0x01u8],
1987 )),
1988 probe_encodable(OperatorStateKey::new(
1989 OperatorId(2),
1990 GroupId::ROOT,
1991 KeyspaceId(1),
1992 [0x01u8],
1993 )),
1994 ],
1995 "OperatorStateKey",
1996 );
1997 assert_projection_matches_bytes(
1998 vec![
1999 probe_encodable(RingBufferMetadataKey::partition(
2000 StorageId::ringbuffer(1),
2001 vec![Value::Uint8(1)],
2002 )),
2003 probe_encodable(RingBufferMetadataKey::partition(
2004 StorageId::ringbuffer(1),
2005 vec![Value::Uint8(2)],
2006 )),
2007 probe_encodable(RingBufferMetadataKey::partition(
2008 StorageId::ringbuffer(2),
2009 vec![Value::Uint8(1)],
2010 )),
2011 ],
2012 "RingBufferMetadataKey",
2013 );
2014 assert_projection_matches_bytes(
2015 vec![
2016 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x10u8]), RowNumber(1))),
2017 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x10u8]), RowNumber(2))),
2018 probe(SortedViewRowKey::new(StorageId::view(1), SortRun::new([0x20u8]), RowNumber(1))),
2019 probe(SortedViewRowKey::new(
2020 StorageId::view(1),
2021 SortRun::new([0x10u8, 0x00]),
2022 RowNumber(1),
2023 )),
2024 probe(SortedViewRowKey::new(StorageId::view(2), SortRun::new([0x10u8]), RowNumber(1))),
2025 ],
2026 "SortedViewRowKey",
2027 );
2028 assert_projection_matches_bytes(
2029 vec![
2030 probe(PartitionedSortedViewRowKey::new(
2031 StorageId::view(1),
2032 Partition(1),
2033 SortRun::new([0x10u8]),
2034 RowNumber(1),
2035 )),
2036 probe(PartitionedSortedViewRowKey::new(
2037 StorageId::view(1),
2038 Partition(1),
2039 SortRun::new([0x10u8]),
2040 RowNumber(2),
2041 )),
2042 probe(PartitionedSortedViewRowKey::new(
2043 StorageId::view(1),
2044 Partition(1),
2045 SortRun::new([0x20u8]),
2046 RowNumber(1),
2047 )),
2048 probe(PartitionedSortedViewRowKey::new(
2049 StorageId::view(1),
2050 Partition(2),
2051 SortRun::new([0x10u8]),
2052 RowNumber(1),
2053 )),
2054 probe(PartitionedSortedViewRowKey::new(
2055 StorageId::view(2),
2056 Partition(1),
2057 SortRun::new([0x10u8]),
2058 RowNumber(1),
2059 )),
2060 ],
2061 "PartitionedSortedViewRowKey",
2062 );
2063 assert_projection_matches_bytes(
2064 vec![
2065 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::System)),
2066 probe(MetricStorageKey::new(Tier::Persistent, MetricsId::System)),
2067 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::Object(ObjectId::table(1)))),
2068 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::Object(ObjectId::table(2)))),
2069 probe(MetricStorageKey::new(Tier::Buffer, MetricsId::Object(ObjectId::view(1)))),
2070 probe(MetricCdcKey::new(MetricsId::System)),
2071 probe(MetricCdcKey::new(MetricsId::Object(ObjectId::table(1)))),
2072 probe(MetricCdcKey::new(MetricsId::Object(ObjectId::table(2)))),
2073 ],
2074 "MetricKey",
2075 );
2076 }
2077
2078 fn all_probes() -> Vec<(TaggedKey, EncodedKey)> {
2079 vec![
2080 probe(NamespaceKey {
2081 namespace: NamespaceId(1),
2082 }),
2083 probe(TableKey {
2084 table: TableId(2),
2085 }),
2086 probe(RowKey {
2087 storage: StorageId::table(3),
2088 row: RowNumber(4),
2089 }),
2090 probe(NamespaceTableKey {
2091 namespace: NamespaceId(5),
2092 table: TableId(6),
2093 }),
2094 probe(SystemSequenceKey {
2095 sequence: SequenceId(7),
2096 }),
2097 probe(ColumnsKey {
2098 column: ColumnId(8),
2099 }),
2100 probe(ColumnKey {
2101 object: ObjectId::view(9),
2102 column: ColumnId(10),
2103 }),
2104 probe(RowSequenceKey {
2105 storage: StorageId::view(11),
2106 }),
2107 probe(ColumnPropertyKey {
2108 column: ColumnId(12),
2109 property: ColumnPropertyId(13),
2110 }),
2111 probe(SystemVersionKey {
2112 version: SystemVersion::Storage,
2113 }),
2114 probe(IndexKey {
2115 object: ObjectId::table(14),
2116 index: IndexId::primary(PrimaryKeyId(15)),
2117 }),
2118 probe_encodable(IndexEntryKey::new(
2119 ObjectId::table(16),
2120 IndexId::primary(PrimaryKeyId(17)),
2121 EncodedIndexKey::new([0x01u8, 0x02]),
2122 )),
2123 probe(ColumnSequenceKey {
2124 object: ObjectId::table(18),
2125 column: ColumnId(19),
2126 }),
2127 probe_encodable(CdcConsumerKey {
2128 consumer: CdcConsumerId::new("consumer"),
2129 }),
2130 probe(ViewKey {
2131 view: ViewId(20),
2132 }),
2133 probe(NamespaceViewKey {
2134 namespace: NamespaceId(21),
2135 view: ViewId(22),
2136 }),
2137 probe(PrimaryKeyKey {
2138 primary_key: PrimaryKeyId(23),
2139 }),
2140 probe_encodable(OperatorStateKey::new(
2141 OperatorId(24),
2142 GroupId::ROOT,
2143 KeyspaceId(2),
2144 [0x01u8, 0x02],
2145 )),
2146 probe(RingBufferKey {
2147 ringbuffer: RingBufferId(25),
2148 }),
2149 probe(NamespaceRingBufferKey {
2150 namespace: NamespaceId(26),
2151 ringbuffer: RingBufferId(27),
2152 }),
2153 probe_encodable(RingBufferMetadataKey::partition(
2154 StorageId::ringbuffer(28),
2155 vec![Value::Utf8("east".to_string()), Value::Uint8(3)],
2156 )),
2157 probe(FlowKey {
2158 flow: FlowId(29),
2159 }),
2160 probe(NamespaceFlowKey {
2161 namespace: NamespaceId(30),
2162 flow: FlowId(31),
2163 }),
2164 probe(OperatorKey {
2165 operator: OperatorId(32),
2166 }),
2167 probe(OperatorByFlowKey {
2168 flow: FlowId(33),
2169 operator: OperatorId(34),
2170 }),
2171 probe(FlowEdgeKey {
2172 edge: FlowEdgeId(35),
2173 }),
2174 probe(FlowEdgeByFlowKey {
2175 flow: FlowId(36),
2176 edge: FlowEdgeId(37),
2177 }),
2178 probe(OutputFrontierKey {
2179 object: ObjectId::view(38),
2180 }),
2181 probe(DictionaryKey {
2182 dictionary: DictionaryId(39),
2183 }),
2184 probe(DictionaryEntryKey {
2185 dictionary: DictionaryId(40),
2186 hash: [0x5Au8; 16],
2187 }),
2188 probe_encodable(DictionaryEntryIndexKey::new(DictionaryId(41), u128::from(u64::MAX) + 9)),
2189 probe(NamespaceDictionaryKey {
2190 namespace: NamespaceId(42),
2191 dictionary: DictionaryId(43),
2192 }),
2193 probe(MetricStorageKey::new(Tier::Persistent, MetricsId::Object(ObjectId::table(44)))),
2194 probe(MetricCdcKey::new(MetricsId::System)),
2195 probe(FlowVersionKey {
2196 flow: FlowId(45),
2197 }),
2198 probe(RowShapeKey {
2199 fingerprint: RowShapeFingerprint::new(46),
2200 }),
2201 probe(RowShapeFieldKey {
2202 shape_fingerprint: RowShapeFingerprint::new(47),
2203 field_index: 48,
2204 }),
2205 probe(SumTypeKey {
2206 sumtype: SumTypeId(49),
2207 }),
2208 probe(NamespaceSumTypeKey {
2209 namespace: NamespaceId(50),
2210 sumtype: SumTypeId(51),
2211 }),
2212 probe(HandlerKey {
2213 handler: HandlerId(52),
2214 }),
2215 probe(NamespaceHandlerKey {
2216 namespace: NamespaceId(53),
2217 handler: HandlerId(54),
2218 }),
2219 probe(VariantHandlerKey {
2220 namespace: NamespaceId(55),
2221 sumtype: SumTypeId(56),
2222 variant_tag: 57,
2223 handler: HandlerId(58),
2224 }),
2225 probe(SeriesKey {
2226 series: SeriesId(59),
2227 }),
2228 probe(NamespaceSeriesKey {
2229 namespace: NamespaceId(60),
2230 series: SeriesId(61),
2231 }),
2232 probe(SeriesPartitionMetadataKey {
2233 storage: StorageId::series(62),
2234 partition: Partition(0x0000_0001_0000_0002_0000_0003_0000_0004),
2235 }),
2236 probe(IdentityKey {
2237 identity: IdentityId::anonymous(),
2238 }),
2239 probe(RoleKey {
2240 role: 63,
2241 }),
2242 probe(GrantedRoleKey {
2243 identity: IdentityId::root(),
2244 role: 64,
2245 }),
2246 probe(PolicyKey {
2247 policy: 65,
2248 }),
2249 probe(PolicyOpKey {
2250 policy: 66,
2251 op_index: 67,
2252 }),
2253 probe(MigrationKey {
2254 migration: MigrationId(68),
2255 }),
2256 probe(MigrationEventKey {
2257 event: MigrationEventId(69),
2258 }),
2259 probe(AuthenticationKey {
2260 authentication: 70,
2261 }),
2262 probe_encodable(ConfigStorageKey::new(ConfigKey::QueryRowBatchSize)),
2263 probe(TokenKey {
2264 token: 71,
2265 }),
2266 probe(SourceKey {
2267 source: SourceId(72),
2268 }),
2269 probe(NamespaceSourceKey {
2270 namespace: NamespaceId(73),
2271 source: SourceId(74),
2272 }),
2273 probe(SinkKey {
2274 sink: SinkId(75),
2275 }),
2276 probe(NamespaceSinkKey {
2277 namespace: NamespaceId(76),
2278 sink: SinkId(77),
2279 }),
2280 probe(RowSettingsKey {
2281 storage: StorageId::ringbuffer(78),
2282 }),
2283 probe(ProcedureKey {
2284 procedure: ProcedureId::persistent(79),
2285 }),
2286 probe(NamespaceProcedureKey {
2287 namespace: NamespaceId(80),
2288 procedure: ProcedureId::persistent(81),
2289 }),
2290 probe(ProcedureParamKey {
2291 procedure: ProcedureId::persistent(82),
2292 param_index: 83,
2293 }),
2294 probe(BindingKey {
2295 binding: BindingId(84),
2296 }),
2297 probe(NamespaceBindingKey {
2298 namespace: NamespaceId(85),
2299 binding: BindingId(86),
2300 }),
2301 probe(OperatorRetentionKey {
2302 operator: OperatorId(87),
2303 }),
2304 probe(ColumnBlockKey {
2305 block: ColumnBlockId(88),
2306 }),
2307 probe(SeriesColumnBlockKey {
2308 series: SeriesId(89),
2309 partition: Partition(0xDEAD_BEEF_0000_0001_0000_0000_0000_0002),
2310 block: ColumnBlockId(90),
2311 }),
2312 probe(TableColumnBlockKey {
2313 table: TableId(91),
2314 block: ColumnBlockId(92),
2315 }),
2316 probe(VersionEpochKey {
2317 bucket: EpochSeconds::new(93),
2318 }),
2319 probe(IdentityAttributeKey {
2320 attribute: 94,
2321 }),
2322 probe(IdentityAttributeValueKey {
2323 identity: IdentityId::anonymous(),
2324 attribute: 95,
2325 }),
2326 probe(PartitionedRowKey {
2327 storage: StorageId::table(96),
2328 partition: Partition(97),
2329 row: RowNumber(98),
2330 }),
2331 probe(PartitionKey {
2332 object: ObjectId::table(99),
2333 partition: Partition(100),
2334 }),
2335 probe(QueueKey {
2336 queue: QueueId(101),
2337 }),
2338 probe(NamespaceQueueKey {
2339 namespace: NamespaceId(102),
2340 queue: QueueId(103),
2341 }),
2342 probe_encodable(QueueDeduplicationKey::new(QueueId(104), [0xFFu8, 0x00, 0xFF])),
2343 probe(RelationshipKey {
2344 relationship: RelationshipId(105),
2345 }),
2346 probe(SeriesRowKey {
2347 storage: StorageId::series(106),
2348 variant_tag: Some(5),
2349 key: 107,
2350 sequence: 108,
2351 }),
2352 probe(PartitionedSeriesRowKey {
2353 storage: StorageId::series(109),
2354 partition: Partition(110),
2355 variant_tag: None,
2356 key: 111,
2357 sequence: 112,
2358 }),
2359 probe(QueuePartitionKey {
2360 queue: QueueId(113),
2361 partition: 114,
2362 }),
2363 probe(QueueItemStateKey {
2364 queue: QueueId(115),
2365 partition: 116,
2366 row: RowNumber(117),
2367 }),
2368 probe(QueueDueKey {
2369 queue: QueueId(118),
2370 partition: 119,
2371 due: DateTime::from_order(120),
2372 row: RowNumber(121),
2373 }),
2374 probe(QueueAttemptKey {
2375 queue: QueueId(122),
2376 row: RowNumber(123),
2377 attempt: 124,
2378 }),
2379 probe(QueueKeyActiveKey {
2380 queue: QueueId(125),
2381 partition: 126,
2382 key_hash: 127,
2383 row: RowNumber(128),
2384 }),
2385 probe(SortedViewRowKey::new(
2386 StorageId::view(129),
2387 SortRun::new([0x00u8, 0xFF, 0x10]),
2388 RowNumber(130),
2389 )),
2390 probe(PartitionedSortedViewRowKey::new(
2391 StorageId::view(131),
2392 Partition(132),
2393 SortRun::new([0x10u8]),
2394 RowNumber(133),
2395 )),
2396 ]
2397 }
2398
2399 fn owned_field(field: &Field<'_>) -> OwnedField {
2400 match field {
2401 Field::UAsc(width, value) => Field::UAsc(*width, *value),
2402 Field::UDesc(width, value) => Field::UDesc(*width, *value),
2403 Field::BytesDesc(encoding, bytes) => {
2404 Field::BytesDesc(*encoding, Cow::Owned(bytes.as_ref().to_vec()))
2405 }
2406 Field::RawAsc(encoding, bytes) => Field::RawAsc(*encoding, Cow::Owned(bytes.as_ref().to_vec())),
2407 }
2408 }
2409
2410 fn bounds_derived_from(key: &TaggedKey) -> Vec<TaggedKeyBound> {
2419 let mut out = vec![TaggedKeyBound::Kind(key.kind()), TaggedKeyBound::KindEnd(key.kind())];
2420 let fields = key.fields();
2421
2422 for len in 0..=fields.len() {
2423 let head: SmallVec<[OwnedField; 6]> = fields[..len].iter().map(owned_field).collect();
2424 out.push(TaggedKeyBound::Prefix(key.kind(), head.clone()));
2425 if len > 0 {
2426 out.push(TaggedKeyBound::PrefixEnd(key.kind(), head));
2432 }
2433 }
2434
2435 if let Some(Field::RawAsc(RawEncoding::Verbatim, bytes)) = fields.last()
2436 && bytes.len() > 1
2437 {
2438 let mut head: SmallVec<[OwnedField; 6]> =
2439 fields[..fields.len() - 1].iter().map(owned_field).collect();
2440 head.push(Field::RawAsc(RawEncoding::Verbatim, Cow::Owned(bytes[..bytes.len() - 1].to_vec())));
2441 out.push(TaggedKeyBound::Prefix(key.kind(), head.clone()));
2442 out.push(TaggedKeyBound::PrefixEnd(key.kind(), head));
2443 }
2444
2445 out
2446 }
2447
2448 #[test]
2449 fn every_bound_shape_orders_against_every_key_the_way_their_bytes_do() {
2450 let probes = all_probes();
2458 let bounds: Vec<TaggedKeyBound> = probes.iter().flat_map(|(key, _)| bounds_derived_from(key)).collect();
2459
2460 for bound in &bounds {
2461 let bound_bytes = bound.encode();
2462 if bound_bytes.as_slice().is_empty() {
2463 continue;
2467 }
2468 for (key, key_bytes) in &probes {
2469 let probe = TaggedKeyBound::Key(key.clone());
2470 assert_eq!(
2471 bound.cmp(&probe),
2472 bound_bytes.as_slice().cmp(key_bytes.as_slice()),
2473 "bound order disagrees with encoded order\n bound = {bound:?}\n key \
2474 = {key:?}\n bound bytes = {:02x?}\n key bytes = {:02x?}",
2475 bound_bytes.as_slice(),
2476 key_bytes.as_slice()
2477 );
2478 }
2479 }
2480 }
2481
2482 #[test]
2483 fn kind_end_is_the_spelling_that_agrees_with_bytes_for_a_whole_kind_span() {
2484 for (key, key_bytes) in all_probes() {
2488 let end = TaggedKeyBound::KindEnd(key.kind());
2489 let end_bytes = end.encode();
2490 let probe = TaggedKeyBound::Key(key.clone());
2491
2492 assert_eq!(
2493 end.cmp(&probe),
2494 end_bytes.as_slice().cmp(key_bytes.as_slice()),
2495 "KindEnd disagrees with its bytes for {key:?}"
2496 );
2497 assert_eq!(
2498 end_bytes.as_slice(),
2499 TaggedKeyBound::PrefixEnd(key.kind(), SmallVec::new()).encode().as_slice(),
2500 "KindEnd and an empty PrefixEnd must still encode alike for {key:?}"
2501 );
2502 }
2503 }
2504
2505 #[test]
2506 fn test_every_variant_round_trips_through_the_shared_decoder() {
2507 for (key, bytes) in all_probes() {
2509 assert_eq!(TaggedKey::decode(&bytes), Some(key.clone()), "{key:?}");
2510 }
2511 }
2512
2513 #[test]
2514 fn test_encoding_through_any_key_is_byte_identical() {
2515 for (key, bytes) in all_probes() {
2517 assert_eq!(key.encode(), bytes, "{key:?}");
2518 }
2519 }
2520
2521 #[test]
2522 fn test_probes_cover_every_live_kind() {
2523 let mut kinds: Vec<u8> = all_probes().iter().map(|(key, _)| key.kind() as u8).collect();
2525 kinds.sort_unstable();
2526 kinds.dedup();
2527 assert_eq!(kinds.len(), 86);
2528 }
2529
2530 #[test]
2531 fn test_metric_sub_families_decode_into_their_own_variant() {
2532 let storage = MetricStorageKey::new(Tier::Persistent, MetricsId::System);
2534 let cdc = MetricCdcKey::new(MetricsId::System);
2535 assert_eq!(TaggedKey::decode(&storage.encode()), Some(TaggedKey::Metric(MetricKey::Storage(storage))));
2536 assert_eq!(TaggedKey::decode(&cdc.encode()), Some(TaggedKey::Metric(MetricKey::Cdc(cdc))));
2537 }
2538
2539 #[test]
2540 fn test_decode_rejects_bytes_that_name_no_live_kind() {
2541 assert_eq!(TaggedKey::decode(&EncodedKey::new(Vec::<u8>::new())), None);
2543 for hole in [0x24u8, 0x25, 0x26, 0x3F] {
2544 assert_eq!(TaggedKey::decode(&EncodedKey::new(vec![!hole, 0x00, 0x01])), None);
2545 }
2546 }
2547
2548 #[test]
2549 fn test_decode_rejects_a_truncated_payload() {
2550 let bytes = RowKey {
2552 storage: StorageId::table(1),
2553 row: RowNumber(1),
2554 }
2555 .encode();
2556 let mut truncated = bytes.as_slice().to_vec();
2557 truncated.truncate(truncated.len() - 1);
2558 assert_eq!(TaggedKey::decode(&EncodedKey::new(truncated)), None);
2559 }
2560
2561 #[test]
2562 fn test_index_entry_with_an_empty_suffix_round_trips() {
2563 let key = IndexEntryKey::new(
2565 ObjectId::table(1),
2566 IndexId::primary(PrimaryKeyId(1)),
2567 EncodedIndexKey::new([0u8; 0]),
2568 );
2569 let bytes = key.encode();
2570 assert_eq!(TaggedKey::from(key.clone()).encode(), bytes);
2571 assert_eq!(TaggedKey::decode(&bytes), Some(TaggedKey::from(key)));
2572 }
2573
2574 #[test]
2575 fn test_any_key_fits_two_machine_words_beyond_an_encoded_key() {
2576 assert_eq!(size_of::<EncodedKey>(), 48);
2578 assert_eq!(size_of::<TaggedKey>(), 96);
2579 assert_eq!(size_of::<PartitionedSortedViewRowKey>(), size_of::<TaggedKey>());
2580 }
2581}