xitdb 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/README.md +15 -3
  4. data/docs/benchmarks.md +4 -1
  5. data/docs/core.md +15 -2
  6. data/docs/learning.md +211 -0
  7. data/docs/native-profile-performance.md +254 -0
  8. data/docs/ruby-profile-v1.md +2 -0
  9. data/docs/ruby-profile-v2.md +279 -0
  10. data/docs/ruby-profile-v3.md +53 -0
  11. data/docs/ruby-profile-v4.md +67 -0
  12. data/docs/ruby.md +26 -3
  13. data/examples/indexed_users.rb +3 -0
  14. data/examples/portable.rb +3 -0
  15. data/examples/ruby.rb +2 -0
  16. data/lib/xitdb/collection_declaration.rb +39 -0
  17. data/lib/xitdb/context.rb +154 -8
  18. data/lib/xitdb/conversion/byte_source.rb +112 -0
  19. data/lib/xitdb/conversion.rb +35 -73
  20. data/lib/xitdb/core/array_builder.rb +74 -0
  21. data/lib/xitdb/core/array_list.rb +92 -8
  22. data/lib/xitdb/core/b_tree.rb +127 -19
  23. data/lib/xitdb/core/byte_value.rb +33 -0
  24. data/lib/xitdb/core/bytes/source.rb +59 -0
  25. data/lib/xitdb/core/bytes.rb +54 -58
  26. data/lib/xitdb/core/compaction.rb +49 -7
  27. data/lib/xitdb/core/crc64.rb +8 -1
  28. data/lib/xitdb/core/cursor.rb +108 -18
  29. data/lib/xitdb/core/database.rb +163 -29
  30. data/lib/xitdb/core/file_store.rb +43 -1
  31. data/lib/xitdb/core/format.rb +39 -98
  32. data/lib/xitdb/core/hash_map.rb +119 -17
  33. data/lib/xitdb/core/hasher.rb +33 -2
  34. data/lib/xitdb/core/header.rb +98 -0
  35. data/lib/xitdb/core/linked_array_list.rb +70 -1
  36. data/lib/xitdb/core/memory_store.rb +23 -224
  37. data/lib/xitdb/core/offset_map.rb +22 -1
  38. data/lib/xitdb/core/record.rb +64 -0
  39. data/lib/xitdb/core/replication.rb +108 -25
  40. data/lib/xitdb/core/slot.rb +123 -0
  41. data/lib/xitdb/core/sorted_map/tree.rb +317 -0
  42. data/lib/xitdb/core/sorted_map.rb +78 -256
  43. data/lib/xitdb/core/store.rb +286 -0
  44. data/lib/xitdb/core/transaction.rb +84 -6
  45. data/lib/xitdb/core.rb +12 -0
  46. data/lib/xitdb/database.rb +194 -15
  47. data/lib/xitdb/declarations.rb +33 -33
  48. data/lib/xitdb/errors.rb +15 -0
  49. data/lib/xitdb/history.rb +21 -0
  50. data/lib/xitdb/input_guard.rb +15 -1
  51. data/lib/xitdb/profiles/portable/adapter.rb +380 -0
  52. data/lib/xitdb/profiles/portable.rb +129 -243
  53. data/lib/xitdb/profiles/ruby.rb +206 -24
  54. data/lib/xitdb/revision.rb +17 -0
  55. data/lib/xitdb/ruby/codec.rb +61 -54
  56. data/lib/xitdb/ruby/codec_registry.rb +79 -0
  57. data/lib/xitdb/ruby/containers.rb +355 -82
  58. data/lib/xitdb/ruby/encoded_value.rb +38 -0
  59. data/lib/xitdb/ruby/indexed_page_decoder.rb +72 -0
  60. data/lib/xitdb/ruby/indexed_page_encoder.rb +58 -0
  61. data/lib/xitdb/ruby/input.rb +55 -0
  62. data/lib/xitdb/ruby/key_encoding.rb +43 -5
  63. data/lib/xitdb/ruby/ordered_keys.rb +46 -3
  64. data/lib/xitdb/ruby/packed_array.rb +179 -0
  65. data/lib/xitdb/ruby/packed_map.rb +272 -0
  66. data/lib/xitdb/ruby/packing_state.rb +84 -0
  67. data/lib/xitdb/ruby/page_array.rb +218 -0
  68. data/lib/xitdb/ruby/page_cell.rb +20 -0
  69. data/lib/xitdb/ruby/page_codec.rb +46 -0
  70. data/lib/xitdb/ruby/page_decoder.rb +172 -0
  71. data/lib/xitdb/ruby/page_draft.rb +24 -0
  72. data/lib/xitdb/ruby/page_encoder.rb +149 -0
  73. data/lib/xitdb/ruby/page_reference.rb +26 -0
  74. data/lib/xitdb/ruby/page_row.rb +108 -0
  75. data/lib/xitdb/ruby/pages.rb +94 -0
  76. data/lib/xitdb/ruby/scalars.rb +175 -33
  77. data/lib/xitdb/ruby/wire/reader.rb +138 -0
  78. data/lib/xitdb/ruby/wire.rb +36 -90
  79. data/lib/xitdb/ruby.rb +43 -3
  80. data/lib/xitdb/snapshot.rb +8 -0
  81. data/lib/xitdb/streams/handle.rb +46 -0
  82. data/lib/xitdb/streams/reader.rb +122 -0
  83. data/lib/xitdb/streams/writer.rb +43 -0
  84. data/lib/xitdb/streams.rb +8 -140
  85. data/lib/xitdb/uint.rb +17 -0
  86. data/lib/xitdb/value_walker.rb +86 -16
  87. data/lib/xitdb/version.rb +2 -1
  88. data/lib/xitdb/views/array.rb +94 -74
  89. data/lib/xitdb/views/base.rb +144 -12
  90. data/lib/xitdb/views/linked_array.rb +7 -1
  91. data/lib/xitdb/views/map.rb +71 -3
  92. data/lib/xitdb/views/set.rb +13 -1
  93. data/lib/xitdb/views/slice.rb +101 -0
  94. data/lib/xitdb/views/sorted.rb +25 -37
  95. data/lib/xitdb/views/sorted_map.rb +39 -0
  96. data/lib/xitdb/views/sorted_set.rb +10 -0
  97. data/lib/xitdb.rb +3 -0
  98. data/sig/core.rbs +65 -34
  99. data/sig/public.rbs +24 -19
  100. data/sig/ruby.rbs +260 -42
  101. metadata +42 -1
@@ -4,19 +4,45 @@ require_relative "ordered_keys"
4
4
 
5
5
  module XitDB
6
6
  module Ruby
7
- # Maintains Ruby collection envelopes and their storage indexes.
7
+ # Adapts Ruby-profile collections stored inside marked array envelopes.
8
+ # An envelope records the logical kind and the roots of its native storage structures.
9
+ # Maps and sets combine a hash lookup with a sorted insertion-identifier index to preserve insertion order.
10
+ # Typed sorted collections store ordering bytes alongside original keys, which retain their Ruby representation.
11
+ # Sequences wrap native array or linked-array storage. Reads validate envelope fields and index agreement.
8
12
  class Containers
13
+ # Version-one envelope markers identifying the logical Ruby collection kind.
9
14
  MARKERS = { array: 0x52420101, linked_array: 0x52420102, map: 0x52420103, set: 0x52420104,
10
15
  sorted_map: 0x52420105, sorted_set: 0x52420106 }.freeze
16
+ # Version-one numeric identifiers for typed sorted-key declarations.
11
17
  KEY_KINDS = { string: 1, integer: 2, float: 3, time: 4 }.freeze
12
18
 
13
19
  attr_reader :kind, :cursor
14
20
 
15
- def initialize(profile, cursor, context:, path:, kind: nil, key_kind: nil)
21
+ # @!attribute [r] kind
22
+ # Logical Ruby collection kind.
23
+ #
24
+ # @return [Symbol] logical Ruby collection kind
25
+ # @!attribute [r] cursor
26
+ # Cursor holding the collection envelope root.
27
+ #
28
+ # @return [Core::Cursor] cursor holding the collection envelope root
29
+
30
+ # Opens an envelope or initializes the requested empty collection.
31
+ # An uninitialized root represents an empty Ruby map.
32
+ #
33
+ # @param profile [Profiles::Ruby] scalar, key, and hash rules
34
+ # @param cursor [Core::Cursor] collection root cursor
35
+ # @param context [Context] snapshot or transaction owner
36
+ # @param path [Array<Object>] logical collection location
37
+ # @param kind [Symbol, nil] explicit logical kind for a new collection
38
+ # @param key_kind [Symbol, nil] :string, :integer, :float, or :time for typed sorted collections
39
+ # @raise [InvalidValueError] if the stored envelope is inconsistent
40
+ def initialize(profile, cursor, context:, path:, kind: nil, key_kind: nil, defer: false)
16
41
  @profile = profile
17
42
  @cursor = cursor
18
43
  @context = context
19
44
  @path = path
45
+ @deferred = defer
20
46
  if kind
21
47
  @kind = kind
22
48
  @key_kind = key_kind
@@ -28,58 +54,91 @@ module XitDB
28
54
  end
29
55
  end
30
56
 
57
+ # Returns the collection descriptor held by the adapter cursor.
58
+ #
59
+ # @return [Core::Slot] current stored collection root
31
60
  def slot
61
+ if @deferred
62
+ publish
63
+ @deferred = false
64
+ end
32
65
  cursor.slot
33
66
  end
34
67
 
68
+ # Counts the entries visible through this collection adapter.
69
+ #
70
+ # @return [Integer] number of keys, members, or sequence elements
35
71
  def size
36
72
  return 0 unless @envelope
37
73
 
38
- ordered? ? @lookup.size : @collection.size
74
+ ordered? ? @lookup.size : collection!.size
39
75
  end
40
76
 
77
+ # Checks whether the collection has any entries.
78
+ #
79
+ # @return [Boolean] true when the entry count is zero
41
80
  def empty?
42
81
  size.zero?
43
82
  end
44
83
 
84
+ # Looks up a stored child without decoding its scalar or collection value.
85
+ #
86
+ # @param selector [Object] key, member, or zero-based sequence index
87
+ # @return [Core::Slot, nil] stored child, or nil when absent
88
+ # @raise [TypeError] if a sequence selector is not an Integer
89
+ # @raise [ValueError] if the key or stored layout is invalid
45
90
  def lookup(selector)
46
91
  if sorted?
47
92
  bytes = key_bytes(selector)
48
- stored = sorted_collection.get(bytes)
93
+ stored = sorted_collection!.get(bytes)
49
94
  return sorted_entry(bytes, stored).last if stored
50
95
 
51
96
  return nil
52
97
  end
53
- return sequence_collection.get(index_selector(selector)) unless ordered?
98
+ return sequence_collection!.get(index_selector!(selector)) unless ordered?
54
99
 
55
100
  bytes = key_bytes(selector)
56
101
  return nil unless @envelope
57
102
 
58
- record_for(@profile.hasher.digest(bytes), expected_bytes: bytes)&.get(1)
103
+ record_for(@profile.hasher.digest(bytes), expected_bytes: bytes)&.[](1)
59
104
  end
60
105
 
106
+ # Stores an encoded child at a key or sequence position.
107
+ # A sequence position equal to size appends the child.
108
+ #
109
+ # @param selector [Object] key, member, or nonnegative sequence index
110
+ # @param stored [Core::Slot] already encoded child value
111
+ # @return [self] this adapter
112
+ # @raise [ValueError] if the key or stored layout is invalid
61
113
  def assign(selector, stored)
114
+ stored = Pages.persist(stored, @context)
62
115
  if sorted?
63
116
  assign_sorted(selector, stored)
64
117
  elsif ordered?
65
118
  assign_ordered(selector, stored)
66
119
  elsif selector == size
67
- sequence_collection.append(stored)
120
+ sequence_collection!.append(stored)
68
121
  else
69
- sequence_collection.put(index_selector(selector),
70
- stored)
122
+ sequence_collection!.put(index_selector!(selector),
123
+ stored)
71
124
  end
72
- publish
125
+ @deferred ? self : publish
73
126
  end
74
127
 
128
+ # Removes a key, set member, or sequence element.
129
+ # Deleting a sequence element shifts the following positions down by one.
130
+ #
131
+ # @param selector [Object] key, member, or nonnegative sequence index
132
+ # @return [self] this adapter
133
+ # @raise [IndexError] if an array index is outside the collection
75
134
  def delete(selector)
76
135
  if sorted?
77
136
  bytes = key_bytes(selector)
78
- stored = sorted_collection.get(bytes)
137
+ stored = sorted_collection!.get(bytes)
79
138
  return self unless stored
80
139
 
81
140
  sorted_entry(bytes, stored)
82
- sorted_collection.remove(bytes)
141
+ sorted_collection!.remove(bytes)
83
142
  elsif ordered?
84
143
  bytes = key_bytes(selector)
85
144
  digest = @profile.hasher.digest(bytes)
@@ -89,59 +148,86 @@ module XitDB
89
148
  @order.remove([fetch_slot(record, 2).value].pack("Q>"))
90
149
  @lookup.remove(digest)
91
150
  elsif kind == :linked_array
92
- linked_collection.delete_at(index_selector(selector))
151
+ linked_collection!.delete_at(index_selector!(selector))
93
152
  else
94
153
  delete_array(selector)
95
154
  end
96
155
  publish
97
156
  end
98
157
 
158
+ # Checks whether clearing must remove entries or reset the insertion identifier counter.
159
+ #
160
+ # @return [Boolean] whether clearing changes stored state
99
161
  def clear_needed?
100
162
  size.positive? || (ordered? && @next_id&.positive? == true)
101
163
  end
102
164
 
165
+ # Replaces the collection with an empty envelope of the same kind and key type.
166
+ #
167
+ # @return [self] this adapter
103
168
  def clear
104
169
  initialize_empty
105
170
  self
106
171
  end
107
172
 
173
+ # Inserts a stored sequence element and shifts the following positions.
174
+ # Array insertion copies the suffix; linked arrays follow a counted tree path.
175
+ #
176
+ # @param index [Integer] nonnegative insertion position validated by the caller
177
+ # @param stored [Core::Slot] encoded element
178
+ # @return [self] this adapter
108
179
  def insert(index, stored)
180
+ stored = Pages.persist(stored, @context)
109
181
  if kind == :linked_array
110
- Core::BTree.new(linked_collection.cursor).insert(index, stored)
182
+ Core::BTree.new(linked_collection!.cursor).insert(index, stored)
111
183
  else
112
184
  count = size
113
- array_collection.append(stored)
185
+ array_collection!.append(stored)
114
186
  (count - 1).downto(index) do |position|
115
- array_collection.put(position + 1, required_slot(array_collection.get(position)))
187
+ array_collection!.put(position + 1, required_slot!(array_collection!.get(position)))
116
188
  end
117
- array_collection.put(index, stored)
189
+ array_collection!.put(index, stored)
118
190
  end
119
191
  publish
120
192
  end
121
193
 
194
+ # Keeps the first count elements of a sequence.
195
+ #
196
+ # @param count [Integer] retained length validated by the caller
197
+ # @return [self] this adapter
122
198
  def truncate(count)
123
199
  if kind == :linked_array
124
- @collection = linked_collection.slice(0, count)
200
+ @collection = linked_collection!.slice(0, count)
125
201
  else
126
- array_collection.truncate(count)
202
+ array_collection!.truncate(count)
127
203
  end
128
204
  publish
129
205
  end
130
206
 
207
+ # Builds a stored sequence containing a contiguous range of elements.
208
+ #
209
+ # @param start [Integer] nonnegative start position validated by the caller
210
+ # @param count [Integer] element count validated by the caller
211
+ # @return [Core::Slot] descriptor of the new sequence
131
212
  def slice(start, count)
132
213
  if kind == :linked_array
133
214
  return array([Core::Slot.uint(MARKERS.fetch(kind)),
134
- linked_collection.slice(start, count).cursor.slot]).cursor.slot
215
+ linked_collection!.slice(start, count).cursor.slot]).cursor.slot
135
216
  end
136
217
 
137
218
  output = @profile.empty_container(kind, context: @context, path: @path)
138
- count.times { |index| output.assign(index, required_slot(lookup(start + index))) }
219
+ count.times { |index| output.assign(index, required_slot!(lookup(start + index))) }
139
220
  output.slot
140
221
  end
141
222
 
223
+ # Appends the stored elements of another sequence.
224
+ # Two linked arrays can join through their tree structure.
225
+ #
226
+ # @param other [Object] sequence adapter implementing kind, cursor, and each_entry
227
+ # @return [self] this adapter
142
228
  def concat(other)
143
229
  if kind == :linked_array && other.is_a?(Containers) && other.kind == :linked_array
144
- @collection = linked_collection.concat(other.linked_collection)
230
+ @collection = linked_collection!.concat(other.linked_collection!)
145
231
  publish
146
232
  else
147
233
  other.each_entry { |_index, stored| assign(size, stored) }
@@ -149,6 +235,15 @@ module XitDB
149
235
  self
150
236
  end
151
237
 
238
+ # Visits sequence or sorted entries starting at an ordinal position.
239
+ # Negative positions count from the end; positions outside the collection visit no entries.
240
+ #
241
+ # @param index [Integer] starting ordinal position
242
+ # @return [self, Enumerator] this adapter with a block, otherwise an enumerator
243
+ # @yield [selector, stored] visits each remaining entry
244
+ # @yieldparam selector [Object] key or sequence position
245
+ # @yieldparam stored [Core::Slot] encoded child value
246
+ # @yieldreturn [void] ignored
152
247
  def each_from_index(index, &block)
153
248
  return enum_for(:each_from_index, index) unless block
154
249
 
@@ -159,27 +254,42 @@ module XitDB
159
254
  self
160
255
  end
161
256
 
257
+ # Visits entries after the caller normalizes and validates the ordinal start.
258
+ #
259
+ # @param index [Integer] nonnegative valid sequence or sorted-entry position
260
+ # @return [self] this adapter
261
+ # @yield [selector, stored] visits each remaining entry
262
+ # @yieldparam selector [Object] decoded sorted key or integer sequence position
263
+ # @yieldparam stored [Core::Slot] encoded child value
264
+ # @yieldreturn [void] ignored
162
265
  def each_normalized_index(index)
163
266
  if sorted?
164
- sorted_collection.each_from_index(index) do |bytes, stored|
267
+ sorted_collection!.each_from_index(index) do |bytes, stored|
165
268
  key, value = sorted_entry(bytes, stored)
166
269
  yield key, value
167
270
  end
168
271
  elsif kind == :linked_array
169
- linked_collection.each_from_index(index).with_index(index) { |stored, position| yield position, stored }
272
+ linked_collection!.each_from_index(index).with_index(index) { |stored, position| yield position, stored }
170
273
  else
171
- (index...size).each { |position| yield position, required_slot(lookup(position)) }
274
+ (index...size).each { |position| yield position, required_slot!(lookup(position)) }
172
275
  end
173
276
  self
174
277
  end
175
278
  private :each_normalized_index
176
279
 
280
+ # Visits every entry in the order defined by the collection layout.
281
+ #
282
+ # @return [self, Enumerator] this adapter with a block, otherwise an enumerator
283
+ # @yield [selector, stored] visits one entry
284
+ # @yieldparam selector [Object] decoded key or integer sequence position
285
+ # @yieldparam stored [Core::Slot] encoded child value
286
+ # @yieldreturn [void] ignored
177
287
  def each_entry
178
288
  return enum_for(:each_entry) unless block_given?
179
289
  return self unless @envelope
180
290
 
181
291
  if sorted?
182
- sorted_collection.each do |bytes, stored|
292
+ sorted_collection!.each do |bytes, stored|
183
293
  key, value = sorted_entry(bytes, stored)
184
294
  yield key, value
185
295
  end
@@ -189,34 +299,52 @@ module XitDB
189
299
  yield key, stored
190
300
  end
191
301
  else
192
- sequence_collection.each.with_index { |stored, index| yield index, stored }
302
+ sequence_collection!.each.with_index { |stored, index| yield index, stored }
193
303
  end
194
304
  self
195
305
  end
196
306
 
307
+ # Finds the number of sorted keys strictly less than the requested key.
308
+ #
309
+ # @param selector [Object] key in the sorted collection's accepted key type
310
+ # @return [Integer] zero-based position, including the insertion position for an absent key
197
311
  def rank(selector)
198
- sorted_collection.rank(key_bytes(selector))
312
+ sorted_collection!.rank(key_bytes(selector))
199
313
  end
200
314
 
315
+ # Visits sorted entries starting at the first key greater than or equal to the requested key.
316
+ #
317
+ # @param selector [Object] lower-bound sorted key
318
+ # @return [self, Enumerator] this adapter with a block, otherwise an enumerator
319
+ # @yield [key, stored] visits an entry in ascending key order
320
+ # @yieldparam key [Object] decoded key
321
+ # @yieldparam stored [Core::Slot] encoded child value
322
+ # @yieldreturn [void] ignored
201
323
  def each_from(selector)
202
324
  return enum_for(:each_from, selector) unless block_given?
203
325
 
204
- sorted_collection.each_from(key_bytes(selector)) do |bytes, stored|
326
+ sorted_collection!.each_from(key_bytes(selector)) do |bytes, stored|
205
327
  key, value = sorted_entry(bytes, stored)
206
328
  yield key, value
207
329
  end
208
330
  self
209
331
  end
210
332
 
333
+ # Returns the stable identity used to track a logical view location.
334
+ #
335
+ # @param selector [Object] key, member, or sequence position
336
+ # @return [Integer, String] sequence position or canonical key bytes
211
337
  def selector_identity(selector)
212
338
  %i[array linked_array].include?(kind) ? selector : key_bytes(selector)
213
339
  end
214
340
 
215
341
  protected
216
342
 
217
- attr_reader :collection
218
-
219
- def linked_collection
343
+ # Checks the active layout before using its collection-specific operations.
344
+ #
345
+ # @return [Core::LinkedArrayList] typed underlying collection
346
+ # @raise [InvalidValueError] if the active layout has the wrong collection type
347
+ def linked_collection!
220
348
  collection = @collection
221
349
  invalid! unless collection.is_a?(Core::LinkedArrayList)
222
350
 
@@ -225,76 +353,132 @@ module XitDB
225
353
 
226
354
  private
227
355
 
228
- def index_selector(selector)
356
+ # Requires backing storage for an indexed sequence or sorted collection.
357
+ def collection!
358
+ value = @collection
359
+ invalid! unless value
360
+
361
+ value
362
+ end
363
+
364
+ # Requires an Integer selector before passing an index to core storage.
365
+ #
366
+ # @param selector [Object] candidate sequence position
367
+ # @return [Integer] supplied index
368
+ # @raise [TypeError] if the selector is not an Integer
369
+ def index_selector!(selector)
229
370
  raise TypeError, "index must be an Integer" unless selector.is_a?(Integer)
230
371
 
231
372
  selector
232
373
  end
233
374
 
234
- def required_slot(slot)
375
+ # Requires a stored child where the collection structure promises one.
376
+ #
377
+ # @param slot [Core::Slot, nil] result of an internal child lookup
378
+ # @return [Core::Slot] present child
379
+ # @raise [InvalidValueError] if the promised child is absent
380
+ def required_slot!(slot)
235
381
  invalid! unless slot
236
382
 
237
383
  slot
238
384
  end
239
385
 
386
+ # Fetches an envelope or record field that must exist.
387
+ #
388
+ # @param collection [Core::ArrayList, Array<Core::Slot>] envelope or internal record fields
389
+ # @param index [Integer] nonnegative field position
390
+ # @return [Core::Slot] required field
391
+ # @raise [InvalidValueError] if the field is absent
240
392
  def fetch_slot(collection, index)
241
- required_slot(collection.get(index))
393
+ required_slot!(collection.is_a?(::Array) ? collection[index] : collection.get(index))
242
394
  end
243
395
 
244
- def envelope
396
+ # Requires the marked envelope before reading or publishing its fields.
397
+ #
398
+ # @return [Core::ArrayList] active envelope
399
+ # @raise [InvalidValueError] if no envelope has been initialized
400
+ def envelope!
245
401
  value = @envelope
246
402
  invalid! unless value
247
403
 
248
404
  value
249
405
  end
250
406
 
251
- def declared_key_kind
407
+ # Requires the key kind recorded for a typed sorted collection.
408
+ #
409
+ # @return [Symbol] declared sorted-key kind
410
+ # @raise [InvalidValueError] if the key-kind field is absent
411
+ def declared_key_kind!
252
412
  value = @key_kind
253
413
  invalid! unless value
254
414
 
255
415
  value
256
416
  end
257
417
 
258
- def array_collection
418
+ # Checks the active layout before using its collection-specific operations.
419
+ #
420
+ # @return [Core::ArrayList] typed underlying collection
421
+ # @raise [InvalidValueError] if the active layout has the wrong collection type
422
+ def array_collection!
259
423
  collection = @collection
260
424
  invalid! unless collection.is_a?(Core::ArrayList)
261
425
 
262
426
  collection
263
427
  end
264
428
 
265
- def sorted_collection
429
+ # Checks the active layout before using its collection-specific operations.
430
+ #
431
+ # @return [Core::SortedMap] typed underlying collection
432
+ # @raise [InvalidValueError] if the active layout has the wrong collection type
433
+ def sorted_collection!
266
434
  collection = @collection
267
435
  invalid! unless collection.is_a?(Core::SortedMap)
268
436
 
269
437
  collection
270
438
  end
271
439
 
272
- def sequence_collection
440
+ # Checks the active layout before using its collection-specific operations.
441
+ #
442
+ # @return [Core::ArrayList, Core::LinkedArrayList] typed underlying collection
443
+ # @raise [InvalidValueError] if the active layout has the wrong collection type
444
+ def sequence_collection!
273
445
  collection = @collection
274
446
  invalid! unless collection.is_a?(Core::ArrayList) || collection.is_a?(Core::LinkedArrayList)
275
447
 
276
448
  collection
277
449
  end
278
450
 
451
+ # Checks whether the collection uses a separate insertion-order index.
452
+ #
453
+ # @return [Boolean] true for Ruby maps and sets
279
454
  def ordered?
280
455
  %i[map set].include?(kind)
281
456
  end
282
457
 
458
+ # Checks whether keys use the declared typed sort order.
459
+ #
460
+ # @return [Boolean] true for sorted maps and sorted sets
283
461
  def sorted?
284
462
  %i[sorted_map sorted_set].include?(kind)
285
463
  end
286
464
 
465
+ # Builds a native array for an envelope or internal record.
466
+ #
467
+ # @param fields [Array<Core::Slot>] already encoded fields
468
+ # @return [Core::ArrayList] new native array containing the fields
287
469
  def array(fields)
288
- output = Core::ArrayList.new(@context.cursor(Core::Slot.new))
289
- fields.each { |field| output.append(field) }
290
- output
470
+ Core::ArrayList.new(@context.cursor(Core::Slot.new), fields: fields)
291
471
  end
292
472
 
473
+ # Builds empty storage and its envelope, then replaces the root cursor.
474
+ # Maps and sets also reset the next insertion identifier.
475
+ #
476
+ # @return [void]
293
477
  def initialize_empty
294
478
  marker = Core::Slot.uint(MARKERS.fetch(kind))
295
479
  if sorted?
296
480
  @collection = Core::SortedMap.new(@context.cursor(Core::Slot.new))
297
- @envelope = array([marker, Core::Slot.uint(KEY_KINDS.fetch(@key_kind)), @collection.cursor.slot])
481
+ @envelope = array([marker, Core::Slot.uint(KEY_KINDS.fetch(@key_kind)), collection!.cursor.slot])
298
482
  elsif ordered?
299
483
  @next_id = 0
300
484
  @lookup = Core::HashMap.new(@context.cursor(Core::Slot.new), counted: true)
@@ -303,45 +487,64 @@ module XitDB
303
487
  else
304
488
  klass = kind == :array ? Core::ArrayList : Core::LinkedArrayList
305
489
  @collection = klass.new(@context.cursor(Core::Slot.new))
306
- @envelope = array([marker, @collection.cursor.slot])
490
+ @envelope = array([marker, collection!.cursor.slot])
307
491
  end
308
- cursor.replace(envelope.cursor.slot)
492
+ cursor.replace(envelope!.cursor.slot)
309
493
  end
310
494
 
495
+ # Validates the marker and field count, then opens the corresponding child storage.
496
+ #
497
+ # @return [void]
498
+ # @raise [InvalidValueError] if the marker, field count, or child layout is inconsistent
311
499
  def read_envelope
312
500
  @envelope = Core::ArrayList.new(cursor)
313
- marker = fetch_slot(envelope, 0)
501
+ marker = fetch_slot(envelope!, 0)
314
502
  invalid! unless marker.tag == :uint && (@kind = MARKERS.key(marker.value))
315
- invalid! unless envelope.size == envelope_size
503
+ invalid! unless envelope!.size == envelope_size
504
+
505
+ fields = envelope!.to_a
316
506
  if sorted?
317
- read_sorted_envelope
507
+ read_sorted_envelope(fields)
318
508
  elsif ordered?
319
- read_ordered_envelope
509
+ read_ordered_envelope(fields)
320
510
  else
321
- read_sequence_envelope
511
+ read_sequence_envelope(fields)
322
512
  end
323
513
  end
324
514
 
515
+ # Copies changed child roots and counters into the envelope and replaces the root cursor.
516
+ #
517
+ # @return [self] this adapter
325
518
  def publish
326
- if sorted?
327
- envelope.put(2, @collection.cursor.slot)
328
- elsif ordered?
329
- envelope.put(1, Core::Slot.uint(@next_id))
330
- envelope.put(2, @lookup.cursor.slot)
331
- envelope.put(3, @order.cursor.slot)
332
- else
333
- envelope.put(1, @collection.cursor.slot)
334
- end
335
- cursor.replace(envelope.cursor.slot)
519
+ marker = Core::Slot.uint(MARKERS.fetch(kind))
520
+ fields = if sorted?
521
+ [marker, Core::Slot.uint(KEY_KINDS.fetch(@key_kind)), collection!.cursor.slot]
522
+ elsif ordered?
523
+ [marker, Core::Slot.uint(@next_id), @lookup.cursor.slot, @order.cursor.slot]
524
+ else
525
+ [marker, collection!.cursor.slot]
526
+ end
527
+ @envelope = array(fields)
528
+ cursor.replace(envelope!.cursor.slot)
336
529
  self
337
530
  end
338
531
 
532
+ # Encodes a selector and attaches its logical path to value errors.
533
+ #
534
+ # @param selector [Object] key or member to encode
535
+ # @return [String] canonical binary key bytes
536
+ # @raise [ValueError] if the key is unsupported for this collection
339
537
  def key_bytes(selector)
340
- sorted? ? OrderedKeys.dump(selector, kind: declared_key_kind) : @profile.key_bytes(selector)
538
+ sorted? ? OrderedKeys.dump(selector, kind: declared_key_kind!) : @profile.key_bytes(selector)
341
539
  rescue ValueError => e
342
540
  raise e.class.new(e.message, path: @path + [selector]), cause: e
343
541
  end
344
542
 
543
+ # Requires untagged byte storage before reading an index key or digest.
544
+ #
545
+ # @param slot [Core::Slot, nil] candidate stored byte descriptor
546
+ # @return [String] stored binary bytes
547
+ # @raise [InvalidValueError] if the slot is absent, has the wrong tag, or has a format label
345
548
  def raw_bytes(slot)
346
549
  invalid! unless slot && %i[bytes short_bytes].include?(slot.tag)
347
550
  value = @context.database.core.read_bytes(slot, bound: @context.read_bound)
@@ -349,6 +552,11 @@ module XitDB
349
552
  value.bytes
350
553
  end
351
554
 
555
+ # Decodes an original key and restricts it to supported key scalar types.
556
+ #
557
+ # @param slot [Core::Slot] original stored key
558
+ # @return [nil, Boolean, String, Integer, Float, Time, Symbol, UInt] decoded key
559
+ # @raise [InvalidValueError] if the decoded value cannot represent a stored key
352
560
  def decode_key(slot)
353
561
  value = Scalars.decode(slot, core: @context.database.core, bound: @context.read_bound)
354
562
  case value
@@ -357,19 +565,33 @@ module XitDB
357
565
  end
358
566
  end
359
567
 
568
+ # Looks up an insertion-ordered record and validates its key and order references.
569
+ #
570
+ # @param digest [String] SHA-256 digest of the canonical key bytes
571
+ # @param expected_bytes [String, nil] requested key identity, when lookup supplied one
572
+ # @return [Array<Core::Slot>, nil] validated three-field record fields, or nil when absent
573
+ # @raise [InvalidValueError] if the record or either index is inconsistent
360
574
  def record_for(digest, expected_bytes: nil)
361
575
  stored = @lookup.get(digest)
362
576
  return nil unless stored
363
577
 
364
578
  invalid! unless stored.tag == :array_list
365
- record = Core::ArrayList.new(@context.cursor(stored))
366
- invalid! unless record.size == 3
579
+ collection = Core::ArrayList.new(@context.cursor(stored))
580
+ invalid! unless collection.size == 3
581
+
582
+ record = collection.to_a
367
583
  id = fetch_slot(record, 2)
368
584
  invalid! unless id.tag == :uint && id.value < @next_id
369
- validate_record(record, digest, id, expected_bytes)
585
+ validate_record!(record, digest, id, expected_bytes)
370
586
  record
371
587
  end
372
588
 
589
+ # Validates a sorted entry against its original key and returns the logical child.
590
+ #
591
+ # @param bytes [String] ordering bytes from the sorted index
592
+ # @param stored [Core::Slot] original key or map record
593
+ # @return [Array(Object, Core::Slot)] decoded key and value slot, with a null value for set members
594
+ # @raise [InvalidValueError] if the record shape or re-encoded ordering bytes disagree
373
595
  def sorted_entry(bytes, stored)
374
596
  if kind == :sorted_map
375
597
  invalid! unless stored.tag == :array_list
@@ -383,16 +605,21 @@ module XitDB
383
605
  end
384
606
  key = decode_key(original)
385
607
  begin
386
- invalid! unless OrderedKeys.dump(key, kind: declared_key_kind) == bytes
608
+ invalid! unless OrderedKeys.dump(key, kind: declared_key_kind!) == bytes
387
609
  rescue UnsupportedValueError, UnsupportedEncodingError
388
610
  invalid!
389
611
  end
390
612
  [key, value]
391
613
  end
392
614
 
615
+ # Stores a sorted entry while retaining the first original key representation.
616
+ #
617
+ # @param selector [Object] typed sorted key
618
+ # @param stored [Core::Slot] encoded value, ignored for sorted sets
619
+ # @return [void]
393
620
  def assign_sorted(selector, stored)
394
621
  bytes = key_bytes(selector)
395
- previous = sorted_collection.get(bytes)
622
+ previous = sorted_collection!.get(bytes)
396
623
  if previous
397
624
  sorted_entry(bytes, previous)
398
625
  original = kind == :sorted_set ? previous : fetch_slot(Core::ArrayList.new(@context.cursor(previous)), 0)
@@ -400,9 +627,17 @@ module XitDB
400
627
  original = @profile.encode_scalar(selector, core: @context.database.core)
401
628
  end
402
629
  value = kind == :sorted_set ? original : array([original, stored]).cursor.slot
403
- sorted_collection.put(bytes, value: value)
630
+ sorted_collection!.put(bytes, value: value)
404
631
  end
405
632
 
633
+ # Updates an ordered entry or allocates its insertion identifier and both index entries.
634
+ # Replacing a value preserves its original key and insertion position.
635
+ #
636
+ # @param selector [Object] supported Ruby key
637
+ # @param stored [Core::Slot] encoded value, ignored for sets
638
+ # @return [void]
639
+ # @raise [RangeError] if another insertion identifier cannot fit in unsigned 64-bit storage
640
+ # @raise [InvalidValueError] if an existing record or its indexes are inconsistent
406
641
  def assign_ordered(selector, stored)
407
642
  bytes = key_bytes(selector)
408
643
  initialize_empty unless @envelope
@@ -421,6 +656,11 @@ module XitDB
421
656
  @lookup.put(digest, key: @context.database.core.bytes(bytes), value: record.cursor.slot)
422
657
  end
423
658
 
659
+ # Removes an array element by shifting each following stored slot to the previous position.
660
+ #
661
+ # @param selector [Integer] nonnegative element index
662
+ # @return [void]
663
+ # @raise [IndexError] if the selector is not an Integer within the array
424
664
  def delete_array(selector)
425
665
  count = size
426
666
  unless selector.is_a?(Integer) && selector >= 0 && selector < count
@@ -429,36 +669,51 @@ module XitDB
429
669
  end
430
670
 
431
671
  (selector...(count - 1)).each do |index|
432
- array_collection.put(index, required_slot(array_collection.get(index + 1)))
672
+ array_collection!.put(index, required_slot!(array_collection!.get(index + 1)))
433
673
  end
434
- array_collection.truncate(count - 1)
674
+ array_collection!.truncate(count - 1)
435
675
  end
436
676
 
677
+ # Reports the required envelope field count for the active logical kind.
678
+ #
679
+ # @return [Integer] four for insertion-ordered collections, three for sorted collections, or two for sequences
437
680
  def envelope_size
438
681
  return 4 if ordered?
439
682
 
440
683
  sorted? ? 3 : 2
441
684
  end
442
685
 
443
- def read_sequence_envelope
444
- child = fetch_slot(envelope, 1)
686
+ # Requires the native sequence tag that matches the envelope marker.
687
+ #
688
+ # @return [void]
689
+ # @raise [InvalidValueError] if the sequence field has the wrong native layout
690
+ def read_sequence_envelope(fields)
691
+ child = fetch_slot(fields, 1)
445
692
  expected = kind == :array ? :array_list : :linked_array_list
446
693
  invalid! unless child.tag == expected
447
694
  klass = kind == :array ? Core::ArrayList : Core::LinkedArrayList
448
695
  @collection = klass.new(@context.cursor(child))
449
696
  end
450
697
 
451
- def read_sorted_envelope
452
- key = fetch_slot(envelope, 1)
453
- child = fetch_slot(envelope, 2)
698
+ # Reads the declared key kind and opens its native sorted-map storage.
699
+ #
700
+ # @return [void]
701
+ # @raise [InvalidValueError] if the key-kind identifier or child tag is invalid
702
+ def read_sorted_envelope(fields)
703
+ key = fetch_slot(fields, 1)
704
+ child = fetch_slot(fields, 2)
454
705
  invalid! unless key.tag == :uint && (@key_kind = KEY_KINDS.key(key.value)) && child.tag == :sorted_map
455
706
  @collection = Core::SortedMap.new(@context.cursor(child))
456
707
  end
457
708
 
458
- def read_ordered_envelope
459
- id = fetch_slot(envelope, 1)
460
- lookup = fetch_slot(envelope, 2)
461
- order = fetch_slot(envelope, 3)
709
+ # Opens lookup and insertion-order indexes and checks their entry counts.
710
+ #
711
+ # @return [void]
712
+ # @raise [InvalidValueError] if tags, counts, or the next insertion identifier disagree
713
+ def read_ordered_envelope(fields)
714
+ id = fetch_slot(fields, 1)
715
+ lookup = fetch_slot(fields, 2)
716
+ order = fetch_slot(fields, 3)
462
717
  invalid! unless id.tag == :uint && lookup.tag == :counted_hash_map && order.tag == :sorted_map
463
718
  @next_id = id.value
464
719
  @lookup = Core::HashMap.new(@context.cursor(lookup), counted: true)
@@ -466,20 +721,34 @@ module XitDB
466
721
  invalid! unless @lookup.size == @order.size && @lookup.size <= @next_id
467
722
  end
468
723
 
724
+ # Validates an insertion-order index entry and resolves its logical key and value.
725
+ #
726
+ # @param id_bytes [String] eight-byte big-endian insertion identifier
727
+ # @param hash_slot [Core::Slot] untagged bytes containing the key digest
728
+ # @return [Array(Object, Core::Slot)] decoded key and encoded value
729
+ # @raise [InvalidValueError] if the identifier, digest, or referenced record is inconsistent
469
730
  def ordered_entry(id_bytes, hash_slot)
470
731
  invalid! unless id_bytes.bytesize == 8
471
732
  digest = raw_bytes(hash_slot)
472
733
  invalid! unless digest.bytesize == 32
473
734
  record = record_for(digest)
474
- invalid! unless record && fetch_slot(record, 2).value == id_bytes.unpack1("Q>")
735
+ invalid! unless record && fetch_slot(record, 2).value == Core::Format.unsigned(id_bytes)
475
736
  [decode_key(fetch_slot(record, 0)), fetch_slot(record, 1)]
476
737
  end
477
738
 
478
- def validate_record(record, digest, id, expected_bytes)
739
+ # Checks agreement between a record, its canonical key bytes, and both indexes.
740
+ #
741
+ # @param record [Core::ArrayList] three-field ordered record
742
+ # @param digest [String] lookup digest
743
+ # @param id [Core::Slot] validated insertion-identifier field
744
+ # @param expected_bytes [String, nil] requested canonical identity, when supplied
745
+ # @return [void]
746
+ # @raise [InvalidValueError] if key bytes, hashes, order references, or set values disagree
747
+ def validate_record!(record, digest, id, expected_bytes)
479
748
  bytes = raw_bytes(@lookup.key(digest))
480
749
  invalid! unless @profile.hasher.digest(bytes) == digest && (!expected_bytes || bytes == expected_bytes)
481
750
  begin
482
- invalid! unless @profile.key_bytes(decode_key(fetch_slot(record, 0))) == bytes
751
+ invalid! unless @profile.stored_key_bytes(decode_key(fetch_slot(record, 0))) == bytes
483
752
  rescue UnsupportedValueError
484
753
  invalid!
485
754
  end
@@ -487,6 +756,10 @@ module XitDB
487
756
  invalid! if kind == :set && fetch_slot(record, 1) != Core::Slot.null
488
757
  end
489
758
 
759
+ # Reports an invalid Ruby collection envelope or inconsistent index record.
760
+ #
761
+ # @return [void]
762
+ # @raise [InvalidValueError] always
490
763
  def invalid!
491
764
  raise InvalidValueError, "invalid Ruby container envelope or index record"
492
765
  end