1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! The namespace manifest and its compare-and-swap update.
//!
//! The manifest is the one mutable object in a namespace. It records the
//! schema, which segment files are live, and how much of the WAL has been
//! folded into segments. Everything else in a namespace is written once and
//! never modified.
//!
//! It also carries the namespace's WAL and segment format levels, which is how
//! a newer build tells older ones to stay away (see [`Manifest::wal_format`]
//! and [`Manifest::segment_format`]).
//!
//! Two operations change it, and both rely on the object store to arbitrate
//! between concurrent writers:
//!
//! - [`create`] writes it with put-if-absent, so exactly one caller creates a
//! namespace.
//! - [`update`] and [`update_if`] rewrite it with a conditional put tied to
//! the version that was read, so concurrent updates cannot silently
//! overwrite each other. Compaction publishes segments through
//! [`update_if`].
use BTreeMap;
use Bytes;
use Path;
use ;
use ;
use crateSchema;
use crate;
use crate::;
/// Version stamped into every manifest. [`load`] rejects any other value with
/// [`ItzmaError::UnsupportedFormat`].
pub const FORMAT_VERSION: u32 = 1;
/// How many read-modify-write rounds [`update`] tries before giving up with
/// [`ItzmaError::ManifestContention`].
pub const MAX_UPDATE_ATTEMPTS: u32 = 32;
/// The contents of `<namespace>/manifest/current.json`.
///
/// # JSON form
///
/// ```json
/// {
/// "format_version": 1,
/// "schema": {"dim": 2, "metric": "l2"},
/// "live_segments": [],
/// "wal_folded_through": 0,
/// "wal_format": 5,
/// "segment_format": 2,
/// "indexes": {},
/// "sparse_indexes": {}
/// }
/// ```
/// Which index object belongs to a segment: the object is
/// `segments/<id>/index-<generation>.bin` and was built by the algorithm
/// `kind`.
///
/// JSON form: `{"gen": 1, "kind": "sq8"}`.
/// Which sparse inverted-index object belongs to a segment: the object is
/// `segments/<id>/sparse-idx-<generation>.bin`. Unlike
/// [`IndexEntry`] there is no `kind` — one algorithm, an inverted index over
/// term-weight pairs.
///
/// JSON form: `{"gen": 1}`.
/// Object key of a namespace's manifest: `<namespace>/manifest/current.json`.
///
/// Does not validate `namespace`; that is [`Namespace`](crate::Namespace)'s job.
/// Serialize to JSON bytes, tagging any failure with a label instead of a key
/// since the object has not been written yet.
/// Write the manifest for a new namespace, failing if one already exists.
///
/// Uses `PutMode::Create` (put-if-absent), which the store performs
/// atomically. When several callers race to create the same id, exactly one
/// succeeds and the rest see [`ItzmaError::NamespaceExists`].
///
/// # Errors
///
/// - [`ItzmaError::NamespaceExists`] if the manifest is already there.
/// - [`ItzmaError::Storage`] for any other backend failure.
///
/// # Examples
///
/// ```
/// # #[tokio::main]
/// # async fn main() -> itzma_core::Result<()> {
/// use itzma_core::manifest::{self, Manifest};
/// use itzma_core::{ItzmaError, Metric, Schema};
/// use object_store::memory::InMemory;
///
/// let store = InMemory::new();
/// let m = Manifest::new(Schema::new(3, Metric::Cosine));
///
/// manifest::create(&store, "docs", &m).await?;
/// let again = manifest::create(&store, "docs", &m).await;
/// assert!(matches!(again, Err(ItzmaError::NamespaceExists(_))));
/// # Ok(())
/// # }
/// ```
pub async
/// Read and decode the manifest, returning it with the version token needed
/// to update it conditionally.
///
/// The returned [`UpdateVersion`] carries the object's ETag and version id,
/// whichever the backend provides. Hand it to `PutMode::Update` to say "only
/// write if nobody changed this since I read it".
///
/// # Errors
///
/// - [`ItzmaError::NamespaceNotFound`] if there is no manifest.
/// - [`ItzmaError::Serde`] if the object is not valid manifest JSON. The error
/// names the object key.
/// - [`ItzmaError::UnsupportedFormat`] if `format_version` is not
/// [`FORMAT_VERSION`].
/// - [`ItzmaError::WalFormatTooNew`] if `wal_format` is above what this build
/// reads. Every operation on a namespace starts here, so this is the one
/// place an older build is turned away, and it has written nothing yet.
/// - [`ItzmaError::SegmentFormatTooNew`] if `segment_format` is above what this
/// build reads. Checked after the WAL level, and turned away the same way.
/// - [`ItzmaError::Storage`] for any other backend failure.
pub async
/// Atomically change the manifest, unless the closure declines.
///
/// Like [`update`], each round loads the current manifest and applies `f`, and
/// writes the result back with `PutMode::Update` tied to the version that was
/// read. A lost race restarts the round from a fresh read. The closure may
/// therefore run several times and **must be re-runnable**.
///
/// The closure returns `true` to publish its change and `false` to decline.
/// Declining writes nothing and returns `Ok(None)`. Compaction uses this to
/// say "publish my segment only if the manifest still looks the way it did
/// when I planned it".
///
/// # Errors
///
/// Same as [`update`]: [`ItzmaError::ManifestContention`] after 32 lost
/// rounds, anything [`load`] can return, and [`ItzmaError::Storage`] for
/// backend failures other than a lost race.
///
/// # Examples
///
/// ```
/// # #[tokio::main]
/// # async fn main() -> itzma_core::Result<()> {
/// use itzma_core::manifest::{self, Manifest};
/// use itzma_core::{Metric, Schema};
/// use object_store::memory::InMemory;
///
/// let store = InMemory::new();
/// manifest::create(&store, "docs", &Manifest::new(Schema::new(3, Metric::L2))).await?;
///
/// // Publish only if nothing has been folded yet.
/// let first = manifest::update_if(&store, "docs", |m| {
/// if m.wal_folded_through != 0 {
/// return false;
/// }
/// m.wal_folded_through = 4;
/// true
/// })
/// .await?;
/// assert_eq!(first.map(|m| m.wal_folded_through), Some(4));
///
/// // The same call now declines.
/// let second = manifest::update_if(&store, "docs", |m| m.wal_folded_through == 0).await?;
/// assert!(second.is_none());
/// # Ok(())
/// # }
/// ```
pub async
/// Atomically change the manifest by read, modify, conditional write.
///
/// Each round loads the current manifest, applies `f` to it, and writes the
/// result back with `PutMode::Update` tied to the version that was read. If
/// another writer got in first the store answers with a precondition failure,
/// and the round restarts from a fresh read, so `f` runs again on the new
/// contents. That means `f` may be called several times and **must be
/// re-runnable**: derive the change from the manifest it is given, and do not
/// carry state between calls.
///
/// The winning manifest is returned. After [`MAX_UPDATE_ATTEMPTS`] lost rounds
/// the call gives up. Use [`update_if`] when the change should be abandoned
/// if the manifest is no longer what the caller expected.
///
/// # Errors
///
/// - [`ItzmaError::ManifestContention`] after 32 lost rounds.
/// - Anything [`load`] can return.
/// - [`ItzmaError::Storage`] if the backend rejects the write for any reason
/// other than a lost race. `LocalFileSystem` does not implement conditional
/// update, so on that backend this is always a `NotImplemented` storage
/// error. Use `InMemory` or a cloud store.
///
/// # Examples
///
/// ```
/// # #[tokio::main]
/// # async fn main() -> itzma_core::Result<()> {
/// use itzma_core::manifest::{self, Manifest};
/// use itzma_core::{Metric, Schema};
/// use object_store::memory::InMemory;
///
/// let store = InMemory::new();
/// let m = Manifest::new(Schema::new(3, Metric::L2));
/// manifest::create(&store, "docs", &m).await?;
///
/// let updated = manifest::update(&store, "docs", |m| m.wal_folded_through += 1).await?;
/// assert_eq!(updated.wal_folded_through, 1);
/// # Ok(())
/// # }
/// ```
pub async