Skip to main content

waratah_compute/
fanout.rs

1//! Write fan-out: encode once → `RegisterStrings` → parallel `InsertQuads` to S/P/O.
2//!
3//! This is Slice B of the MVP cluster contract. Raft (Phase 8) wraps the same
4//! hexastore apply path; multi-registry sharding uses
5//! [`waratah_router::ClusterConfig::registry_for_hash`] already.
6
7use std::collections::BTreeMap;
8use std::sync::Arc;
9
10use waratah_proto::QuadVersion;
11use waratah_router::ClusterConfig;
12use waratah_storage::{
13    CommitTs, EncodedQuad, PartitionAxis, Quad, StorageOp, StrHash, Term, VisibilityLabel,
14    encode_quad, registry_entries_for_quad, vocab,
15};
16
17use crate::clients::{
18    BlobStoreClient, GrpcHexastoreClients, GrpcRegistryClients, HexastoreCompact, HexastoreFlush,
19    HexastoreGeo, HexastoreInsert, StringRegister, StringRegistryCompact, StringRegistryFlush,
20};
21use crate::error::{ComputeError, RetryPolicy, with_retry};
22
23/// Maximum quads sent in one `InsertQuads` RPC.
24///
25/// Large loads are split into chunks of this size so gRPC payloads stay bounded
26/// while still applying many records per round-trip.
27pub const INSERT_QUAD_CHUNK: usize = 20_000;
28
29/// Byte budget for one `PutGeoIndex` RPC (headroom under
30/// [`waratah_proto::GRPC_MAX_MESSAGE_SIZE`]).
31///
32/// GeoIndex sends flush on accumulated **posting bytes**, not quad count:
33/// at `max_cells = 32` (~50–60 bytes per posting) a geo-dense 20 000-quad
34/// chunk is tens of MiB of index rows, far past the frame ceiling.
35pub const GEO_INDEX_WIRE_BUDGET_BYTES: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE * 7 / 8;
36
37/// Wire budget for one temporal-index posting frame (same shape as the geo
38/// budget: flush on accumulated posting bytes, never on quad count).
39pub const TEMPORAL_INDEX_WIRE_BUDGET_BYTES: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE * 7 / 8;
40
41/// Byte budget for one `PutTextIndex` RPC frame. Unlike the geo / temporal
42/// posting frames this flush runs BEFORE the three axis `InsertQuads`
43/// calls (ordering C3), so its latency is on the write critical path — the
44/// budget exists to bound one message, not to defer work.
45pub const TEXT_INDEX_WIRE_BUDGET_BYTES: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE * 7 / 8;
46
47/// One `TextIndexDoc`'s estimated wire size: ~5 bytes of proto field
48/// framing + term + lexical + language tag. The ONE estimator for both
49/// framing sites that batch these documents — the write path's
50/// `TEXT_INDEX_WIRE_BUDGET_BYTES` flush and the rebuild driver's
51/// `put_text_index` client backstop — so the two cannot drift (a divergent
52/// estimate on either side would flush the same documents at different
53/// frame boundaries).
54pub fn text_index_doc_wire_bytes(doc: &waratah_storage::TextIndexDoc) -> usize {
55    5 + doc.term.len() + doc.lexical.len() + doc.language.as_deref().map_or(0, str::len)
56}
57
58/// Byte budget for one batched `PutBlobs` RPC (headroom under
59/// [`waratah_proto::GRPC_MAX_MESSAGE_SIZE`]).
60///
61/// Whole-blob puts flush on accumulated **payload bytes**, not blob count:
62/// the 7/8 headroom absorbs per-blob framing (16-byte id + proto tags), so
63/// a batch of many small blobs still fits one message. Blobs whose payload
64/// alone exceeds this budget take the streaming `PutBlobChunks` path.
65pub const PUT_BLOBS_BATCH_BYTES: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE * 7 / 8;
66
67/// Maximum hashes in one `ResolveStrings` RPC (same bound as insert / broadcast).
68pub const RESOLVE_STRING_CHUNK: usize = INSERT_QUAD_CHUNK;
69
70/// Waratah data-validity rule: the object of an exactly-`rdf:type` predicate
71/// must be an IRI or a blank node.
72///
73/// RDF 1.1 syntax permits a literal in the object position of any predicate,
74/// but a literal class is semantically wrong (RDFS types `rdf:type` objects
75/// as `rdfs:Class`) and no real-world dataset uses one — the realistic
76/// producer is a mis-mapped CSV→RDF conversion, for which a loud ingest
77/// failure is the useful outcome. The rule is unconditional on every write
78/// path (HTTP ingest, `waratah import`, SPARQL UPDATE, demo load): it is a
79/// data-validity contract, deliberately stricter than the RDF spec, and not
80/// a `--strict-sparql` query deviation. Subproperties of `rdf:type` are NOT
81/// covered — only the exact predicate IRI is matched.
82///
83/// Besides rejecting semantically wrong data, the rule maintains a storage
84/// invariant: the TSG column family keys quads as `Type‖Subject‖Graph`, and
85/// with literal type objects excluded its slot-0 term is always a node
86/// encoding (named node or blank node) — every node encoding is exactly 17
87/// bytes, so `tsg` can use the same fixed 17-byte prefix extractor as the
88/// S/P-leading column families.
89///
90/// Validation is op-independent: a delete of such a quad is rejected too.
91/// The quad can never be stored, so the delete version could never match a
92/// row anyway; rejecting it keeps the rule a property of the quad rather
93/// than of the operation.
94fn validate_type_objects(quads: &[Quad]) -> Result<(), ComputeError> {
95    for quad in quads {
96        if quad.predicate == vocab::rdf::TYPE
97            && !matches!(quad.object, Term::NamedNode(_) | Term::BlankNode(_))
98        {
99            return Err(ComputeError::InvalidQuad(format!(
100                "rdf:type object must be an IRI or a blank node, not a literal: {quad}"
101            )));
102        }
103    }
104    Ok(())
105}
106
107/// Coordinator that fans one logical insert out to registry + S/P/O.
108#[derive(Debug, Clone)]
109pub struct WriteFanout<H, R> {
110    hexastore: H,
111    registry: R,
112    retry: RetryPolicy,
113}
114
115impl<H, R> WriteFanout<H, R> {
116    /// Build over injected clients (mocks in unit tests; tonic in integration).
117    pub fn new(hexastore: H, registry: R, retry: RetryPolicy) -> Self {
118        Self {
119            hexastore,
120            registry,
121            retry,
122        }
123    }
124
125    /// Retry policy used for registry and hexastore RPCs.
126    pub fn retry_policy(&self) -> RetryPolicy {
127        self.retry
128    }
129
130    /// Hexastore client used for catalog RPCs (S axis).
131    pub fn hexastore(&self) -> &H {
132        &self.hexastore
133    }
134
135    /// Registry client used for late materialization.
136    pub fn registry(&self) -> &R {
137        &self.registry
138    }
139}
140
141impl WriteFanout<GrpcHexastoreClients, GrpcRegistryClients> {
142    /// Connect tonic clients for every address in `config`.
143    pub async fn connect(config: &ClusterConfig, retry: RetryPolicy) -> Result<Self, ComputeError> {
144        let hexastore = GrpcHexastoreClients::connect(config).await?;
145        let registry = GrpcRegistryClients::connect(config).await?;
146        Ok(Self::new(hexastore, registry, retry))
147    }
148}
149
150impl<H: HexastoreInsert + HexastoreGeo, R: StringRegister + BlobStoreClient> WriteFanout<H, R> {
151    /// Encode `quad` once, register hashed strings, then insert on S, P, and O.
152    ///
153    /// Hexastore inserts run in parallel. A transient failure on one axis is
154    /// retried per [`RetryPolicy`]; if every axis fails, returns
155    /// [`ComputeError::AllAxesFailed`].
156    pub async fn insert_quad(
157        &self,
158        quad: &Quad,
159        commit_ts: CommitTs,
160        op: StorageOp,
161        visibility: VisibilityLabel,
162    ) -> Result<InsertResult, ComputeError> {
163        self.insert_quads(std::slice::from_ref(quad), commit_ts, op, visibility)
164            .await
165    }
166
167    /// Batch encode → register → parallel fan-out for many quads at one timestamp.
168    ///
169    /// Requests larger than [`INSERT_QUAD_CHUNK`] are split across multiple
170    /// `InsertQuads` RPCs per axis. Data-validity rules
171    /// ([`validate_type_objects`]) run over the WHOLE slice before any chunk
172    /// ships: one offending quad rejects the entire request without partially
173    /// applying earlier chunks.
174    pub async fn insert_quads(
175        &self,
176        quads: &[Quad],
177        commit_ts: CommitTs,
178        op: StorageOp,
179        visibility: VisibilityLabel,
180    ) -> Result<InsertResult, ComputeError> {
181        validate_type_objects(quads)?;
182        if quads.is_empty() || quads.len() <= INSERT_QUAD_CHUNK {
183            return self
184                .insert_quads_rpc(quads, commit_ts, op, visibility)
185                .await;
186        }
187
188        let mut total = InsertResult {
189            quads: 0,
190            registered: 0,
191            inserted_per_axis: BTreeMap::new(),
192            spike_reductions: 0,
193        };
194        for chunk in quads.chunks(INSERT_QUAD_CHUNK) {
195            let part = self
196                .insert_quads_rpc(chunk, commit_ts, op, visibility)
197                .await?;
198            total.quads += part.quads;
199            total.registered += part.registered;
200            total.spike_reductions += part.spike_reductions;
201            for (axis, n) in part.inserted_per_axis {
202                *total.inserted_per_axis.entry(axis).or_default() += n;
203            }
204        }
205        Ok(total)
206    }
207
208    async fn insert_quads_rpc(
209        &self,
210        quads: &[Quad],
211        commit_ts: CommitTs,
212        op: StorageOp,
213        visibility: VisibilityLabel,
214    ) -> Result<InsertResult, ComputeError> {
215        let mut versions = Vec::with_capacity(quads.len());
216        let mut entries: Vec<(StrHash, String)> = Vec::new();
217        // Write plugins (GeoSPARQL, temporal) run BEFORE encoding: each
218        // returns a sparse object-rewrite overlay over the plain encoding of
219        // the input, plus registry blobs and opaque O-axis postings with the
220        // same commit_ts / op. Overlays compose in registration order; two
221        // plugins rewriting one position with DIFFERENT terms is an error.
222        let mut encoded: Vec<EncodedQuad> = Vec::with_capacity(quads.len());
223        for quad in quads {
224            encoded.push(encode_quad(quad)?);
225        }
226        let mut prepared_blobs: Vec<(StrHash, Arc<[u8]>)> = Vec::new();
227        let mut geo_puts: Vec<waratah_storage::GeoIndexPut> = Vec::new();
228        let mut temporal_puts: Vec<waratah_storage::TemporalIndexPut> = Vec::new();
229        let mut text_docs: Vec<waratah_storage::TextIndexDoc> = Vec::new();
230        let mut warnings: Vec<String> = Vec::new();
231        let mut spike_reductions = 0_u64;
232        let plugins = crate::plugin::process_plugins();
233        if plugins.write_plugins().next().is_some() {
234            let mut prepared = plugins.write_plugins().try_fold(
235                crate::plugin::PreparedInsert::default(),
236                |mut acc, plugin| {
237                    let mut part = plugin.prepare_insert(quads, commit_ts, op)?;
238                    acc.blobs.append(&mut part.blobs);
239                    acc.geo_puts.append(&mut part.geo_puts);
240                    acc.temporal_puts.append(&mut part.temporal_puts);
241                    acc.text_docs.append(&mut part.text_docs);
242                    acc.warnings.append(&mut part.warnings);
243                    acc.spike_reductions += part.spike_reductions;
244                    for (index, term) in part.object_rewrites {
245                        if index >= quads.len() {
246                            return Err(ComputeError::UnsupportedSparql(format!(
247                                "write plugin rewrote quad index {index} of {}",
248                                quads.len()
249                            )));
250                        }
251                        let existing = &mut acc.object_rewrites;
252                        if let Some(slot) = existing.iter_mut().find(|(i, _)| *i == index) {
253                            if slot.1 != term {
254                                return Err(ComputeError::UnsupportedSparql(format!(
255                                    "two write plugins rewrote quad {index} differently"
256                                )));
257                            }
258                        } else {
259                            existing.push((index, term));
260                        }
261                    }
262                    Ok::<_, ComputeError>(acc)
263                },
264            )?;
265            for (index, term) in prepared.object_rewrites {
266                encoded[index].object = term;
267            }
268            for (quad, item) in quads.iter().zip(&encoded) {
269                entries.extend(registry_entries_for_quad(quad, item));
270            }
271            prepared_blobs = std::mem::take(&mut prepared.blobs);
272            warnings.append(&mut prepared.warnings);
273            spike_reductions = prepared.spike_reductions;
274            // Term-liveness rule for the term-keyed O-axis indexes (geo,
275            // temporal): their postings are keyed by TERM, not by quad, so a
276            // delete must never retract them — tombstoning every posting of
277            // term T because ONE quad referencing T was deleted would make
278            // the live quads vanish from candidate scans. The plugins emit
279            // only Put-shaped postings; on delete batches they are discarded
280            // here and nothing is sent for either index. Never retract on
281            // delete: the index stays a conservative superset at every
282            // snapshot (a dead term posted ahead of the store joins nothing,
283            // while a live term missing from the index silently drops rows)
284            // and the rebuild passes are the garbage collectors of dead
285            // terms. The object rewrites above STILL apply to delete
286            // batches: a delete version must land on the SAME encoded
287            // (native plugin) term key its insert rewrote to, otherwise it
288            // would never tombstone the native-term row.
289            geo_puts = if op == StorageOp::Delete {
290                Vec::new()
291            } else {
292                prepared.geo_puts
293            };
294            temporal_puts = if op == StorageOp::Delete {
295                Vec::new()
296            } else {
297                prepared.temporal_puts
298            };
299            // The text index is term-keyed like the other two O-axis
300            // indexes: a delete never retracts documents (the rebuild is
301            // the only cleaner), so delete batches discard them here.
302            text_docs = if op == StorageOp::Delete {
303                Vec::new()
304            } else {
305                prepared.text_docs
306            };
307        } else {
308            for (quad, item) in quads.iter().zip(&encoded) {
309                entries.extend(registry_entries_for_quad(quad, item));
310            }
311        }
312        // Consume `encoded`: this is its last use, and `QuadVersion` owns
313        // its quad — moving the elements avoids a deep clone of every quad
314        // on the hottest write path. The S/P/O axis RPCs below only borrow
315        // `versions`, so one owned copy serves all three axes.
316        for item in encoded {
317            versions.push(QuadVersion {
318                quad: item,
319                commit_ts,
320                op,
321                visibility,
322            });
323        }
324
325        // Deduplicate registry entries by hash (last write wins, same as shard map).
326        entries = dedupe_registry_entries(entries);
327
328        let registered = self.register_with_retry(&entries).await?;
329
330        // Blobs go BEFORE hexastore inserts (same ordering as
331        // RegisterStrings): a quad visible before its payload would decode
332        // to a blob miss at read time. The invariant is preserved across
333        // both write paths below — every blob RPC completes (including
334        // retries) before the first InsertQuads fires — and there is no
335        // timestamp parameter: durability-before-commit IS the consistency
336        // mechanism.
337        //
338        // Whole blobs batch into one unary `PutBlobs` per
339        // [`PUT_BLOBS_BATCH_BYTES`] of accumulated payload (copy-free: the
340        // cache pre-warm and every batch frame share the plugin's `Arc`
341        // buffer). A blob whose payload alone exceeds the budget takes the
342        // legacy streaming `PutBlobChunks` path, flushing any pending
343        // batch first so ordering stays strict. `PutBlobs` commits the
344        // batch atomically server-side (hash validation before any write,
345        // skip-existing), so `with_retry` may resubmit a whole batch
346        // idempotently; the first blob failure still fails the prepare
347        // (`?`).
348        let mut batch: Vec<(StrHash, Arc<[u8]>)> = Vec::new();
349        let mut batch_bytes = 0usize;
350        for (blob_id, payload) in &prepared_blobs {
351            crate::blob_cache::BlobCache::process()
352                .insert(std::iter::once((*blob_id, Arc::clone(payload))));
353            if payload.len() > PUT_BLOBS_BATCH_BYTES {
354                // Oversize: flush the pending batch first, then stream this
355                // blob chunk-by-chunk (per-blob retry, same as ever).
356                if !batch.is_empty() {
357                    self.put_blobs_with_retry(&batch).await?;
358                    batch.clear();
359                    batch_bytes = 0;
360                }
361                with_retry(
362                    self.retry,
363                    || self.registry.put_blob_chunks(*blob_id, Arc::clone(payload)),
364                    |attempts, message| ComputeError::RegisterStrings { attempts, message },
365                )
366                .await?;
367                continue;
368            }
369            if batch_bytes + payload.len() > PUT_BLOBS_BATCH_BYTES && !batch.is_empty() {
370                self.put_blobs_with_retry(&batch).await?;
371                batch.clear();
372                batch_bytes = 0;
373            }
374            batch_bytes += payload.len();
375            batch.push((*blob_id, Arc::clone(payload)));
376        }
377        // Tail batch.
378        if !batch.is_empty() {
379            self.put_blobs_with_retry(&batch).await?;
380        }
381
382        // Text-index documents flush BEFORE the hexastore inserts (ordering
383        // C3 — deliberately opposite to the geo / temporal postings below):
384        // a document committed ahead of its row leaves at worst a harmless
385        // phantom (no visible row joins it), while a row visible without its
386        // document is the forbidden state — both query forms would silently
387        // drop it. The partition commits and reloads its reader before
388        // acknowledging, so once this RPC returns the document is
389        // searchable. Frames flush on accumulated document bytes, never on
390        // quad count. Failure semantics: a failure here precedes any
391        // hexastore write, so the whole insert fails — no axis ever commits
392        // without its document.
393        if !text_docs.is_empty() {
394            // Fail-closed lexical bound: the wire payload carries the full
395            // lexical, so a literal above the index limit can never be a
396            // valid document. Rejecting here — after this insert's
397            // registry/blob RPCs, but before the text frames and the three
398            // axis writes — fails the whole insert loudly instead of
399            // failing a transport error mid-frame or silently skipping the
400            // document. (The oversized string may already sit in the
401            // registry dictionary from `RegisterStrings` — a harmless
402            // phantom dictionary entry; no row ever lands.)
403            if let Some(doc) = text_docs.iter().find(|doc| {
404                doc.lexical.len() > waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES
405            }) {
406                return Err(ComputeError::UnsupportedSparql(format!(
407                    "text index: a string literal's lexical is {} bytes, above the {} KiB \
408                     indexed-lexical limit; the write is rejected — shorten the literal, or \
409                     run this store without the text plugin (in-process stores only: a \
410                     clustered store's string registry enforces the same limit on registered \
411                     strings with the plugin on or off)",
412                    doc.lexical.len(),
413                    waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES / 1024
414                )));
415            }
416            let mut frame: Vec<waratah_storage::TextIndexDoc> = Vec::new();
417            let mut frame_bytes = 0usize;
418            for doc in text_docs {
419                let bytes = text_index_doc_wire_bytes(&doc);
420                if !frame.is_empty() && frame_bytes + bytes > TEXT_INDEX_WIRE_BUDGET_BYTES {
421                    self.put_text_with_retry(&frame).await?;
422                    frame.clear();
423                    frame_bytes = 0;
424                }
425                frame_bytes += bytes;
426                frame.push(doc);
427            }
428            if !frame.is_empty() {
429                self.put_text_with_retry(&frame).await?;
430            }
431        }
432
433        let (s, p, o) = tokio::join!(
434            self.insert_axis_with_retry(PartitionAxis::S, &versions),
435            self.insert_axis_with_retry(PartitionAxis::P, &versions),
436            self.insert_axis_with_retry(PartitionAxis::O, &versions),
437        );
438
439        let mut inserted_per_axis = BTreeMap::new();
440        let mut failures = Vec::new();
441        for (axis, result) in [
442            (PartitionAxis::S, s),
443            (PartitionAxis::P, p),
444            (PartitionAxis::O, o),
445        ] {
446            match result {
447                Ok(n) => {
448                    inserted_per_axis.insert(axis, n);
449                }
450                Err(e) => failures.push((axis, e)),
451            }
452        }
453
454        if failures.len() == 3 {
455            let detail = failures
456                .iter()
457                .map(|(axis, e)| format!("{axis}: {e}"))
458                .collect::<Vec<_>>()
459                .join("; ");
460            return Err(ComputeError::AllAxesFailed(detail));
461        }
462        if let Some((_, err)) = failures.into_iter().next() {
463            return Err(err);
464        }
465
466        // Index postings flush AFTER the hexastore inserts commit — the
467        // ordering invariant that makes a concurrent index rebuild benign:
468        // "posting exists ⇒ hexastore row committed", so a rebuild either
469        // walks past a committed row (re-derives its posting) or wipes
470        // before the row's postings land (they survive the wipe). Both
471        // frames flush on accumulated bytes, never on quad count (a
472        // geo-dense chunk is tens of MiB of postings at max_cells).
473        // Failure semantics: a posting RPC failure after committed inserts
474        // fails the whole insert (the caller retries; every write here is
475        // idempotent at the same commit_ts), so a *reported* failure never
476        // hides a live-but-unindexed quad.
477        if !geo_puts.is_empty() {
478            let mut frame: Vec<waratah_storage::GeoIndexPut> = Vec::new();
479            let mut frame_bytes = 0usize;
480            for put in geo_puts {
481                let bytes = 8 + put.term.len() + 8 + 21;
482                if !frame.is_empty() && frame_bytes + bytes > GEO_INDEX_WIRE_BUDGET_BYTES {
483                    self.put_geo_with_retry(&frame).await?;
484                    frame.clear();
485                    frame_bytes = 0;
486                }
487                frame_bytes += bytes;
488                frame.push(put);
489            }
490            if !frame.is_empty() {
491                self.put_geo_with_retry(&frame).await?;
492            }
493        }
494
495        // Temporal-index postings flush identically (a span-dense chunk
496        // posts budget-many nodes per literal).
497        if !temporal_puts.is_empty() {
498            let mut frame: Vec<waratah_storage::TemporalIndexPut> = Vec::new();
499            let mut frame_bytes = 0usize;
500            for put in temporal_puts {
501                let bytes = 16 + put.term.len() + 8 + 37;
502                if !frame.is_empty() && frame_bytes + bytes > TEMPORAL_INDEX_WIRE_BUDGET_BYTES {
503                    self.put_temporal_with_retry(&frame).await?;
504                    frame.clear();
505                    frame_bytes = 0;
506                }
507                frame_bytes += bytes;
508                frame.push(put);
509            }
510            if !frame.is_empty() {
511                self.put_temporal_with_retry(&frame).await?;
512            }
513        }
514
515        for warning in warnings {
516            eprintln!("warning: {warning}");
517        }
518        Ok(InsertResult {
519            quads: versions.len() as u64,
520            registered,
521            inserted_per_axis,
522            spike_reductions,
523        })
524    }
525
526    /// One batched `PutBlobs` RPC with the registry retry policy. The
527    /// server commits the batch atomically (hash validation before any
528    /// write; pre-existing blobs skip), so resubmitting the whole batch on
529    /// a transient failure is idempotent under content addressing.
530    async fn put_blobs_with_retry(
531        &self,
532        batch: &[(StrHash, Arc<[u8]>)],
533    ) -> Result<(), ComputeError> {
534        with_retry(
535            self.retry,
536            || self.registry.put_blobs(batch),
537            |attempts, message| ComputeError::RegisterStrings { attempts, message },
538        )
539        .await
540    }
541
542    async fn put_geo_with_retry(
543        &self,
544        puts: &[waratah_storage::GeoIndexPut],
545    ) -> Result<(), ComputeError> {
546        with_retry(
547            self.retry,
548            || self.hexastore.put_geo_index(puts),
549            |attempts, message| ComputeError::HexastoreInsert {
550                axis: PartitionAxis::O,
551                attempts,
552                message,
553            },
554        )
555        .await
556        .map(|_| ())
557    }
558
559    async fn register_with_retry(
560        &self,
561        entries: &[(StrHash, String)],
562    ) -> Result<u64, ComputeError> {
563        if entries.is_empty() {
564            return Ok(0);
565        }
566        with_retry(
567            self.retry,
568            || self.registry.register_strings(entries),
569            |attempts, message| ComputeError::RegisterStrings { attempts, message },
570        )
571        .await
572    }
573
574    async fn insert_axis_with_retry(
575        &self,
576        axis: PartitionAxis,
577        versions: &[QuadVersion],
578    ) -> Result<u64, ComputeError> {
579        with_retry(
580            self.retry,
581            || self.hexastore.insert_quads(axis, versions),
582            |attempts, message| ComputeError::HexastoreInsert {
583                axis,
584                attempts,
585                message,
586            },
587        )
588        .await
589    }
590}
591
592impl<H: HexastoreFlush, R: StringRegistryFlush> WriteFanout<H, R> {
593    /// Flush MemTables on S, P, O, and the string registry.
594    ///
595    /// Hexastore axes and the registry run in parallel. Any failure after retries
596    /// fails the whole call.
597    pub async fn flush_memtables(&self) -> Result<(), ComputeError> {
598        let (hexastore, registry) = tokio::join!(self.flush_hexastore(), self.flush_registry());
599        hexastore?;
600        registry?;
601        Ok(())
602    }
603
604    async fn flush_hexastore(&self) -> Result<(), ComputeError> {
605        let (s, p, o) = tokio::join!(
606            self.flush_axis_with_retry(PartitionAxis::S),
607            self.flush_axis_with_retry(PartitionAxis::P),
608            self.flush_axis_with_retry(PartitionAxis::O),
609        );
610        join_axis_unit(s, p, o)
611    }
612
613    async fn flush_registry(&self) -> Result<(), ComputeError> {
614        with_retry(
615            self.retry,
616            || self.registry.flush_memtables(),
617            |attempts, message| ComputeError::RegistryFlush { attempts, message },
618        )
619        .await
620    }
621
622    async fn flush_axis_with_retry(&self, axis: PartitionAxis) -> Result<(), ComputeError> {
623        with_retry(
624            self.retry,
625            || self.hexastore.flush_memtables(axis),
626            |attempts, message| ComputeError::HexastoreFlush {
627                axis,
628                attempts,
629                message,
630            },
631        )
632        .await
633    }
634}
635
636impl<H: HexastoreCompact, R: StringRegistryCompact> WriteFanout<H, R> {
637    /// Compact S, P, O, and the string registry.
638    ///
639    /// Hexastore axes and the registry run in parallel. Any failure after retries
640    /// fails the whole call.
641    pub async fn compact_range(&self) -> Result<(), ComputeError> {
642        let (hexastore, registry) = tokio::join!(self.compact_hexastore(), self.compact_registry());
643        hexastore?;
644        registry?;
645        Ok(())
646    }
647
648    async fn compact_hexastore(&self) -> Result<(), ComputeError> {
649        let (s, p, o) = tokio::join!(
650            self.compact_axis_with_retry(PartitionAxis::S),
651            self.compact_axis_with_retry(PartitionAxis::P),
652            self.compact_axis_with_retry(PartitionAxis::O),
653        );
654        join_axis_unit(s, p, o)
655    }
656
657    async fn compact_registry(&self) -> Result<(), ComputeError> {
658        with_retry(
659            self.retry,
660            || self.registry.compact_range(),
661            |attempts, message| ComputeError::RegistryCompact { attempts, message },
662        )
663        .await
664    }
665
666    async fn compact_axis_with_retry(&self, axis: PartitionAxis) -> Result<(), ComputeError> {
667        with_retry(
668            self.retry,
669            || self.hexastore.compact_range(axis),
670            |attempts, message| ComputeError::HexastoreCompact {
671                axis,
672                attempts,
673                message,
674            },
675        )
676        .await
677    }
678}
679
680fn join_axis_unit(
681    s: Result<(), ComputeError>,
682    p: Result<(), ComputeError>,
683    o: Result<(), ComputeError>,
684) -> Result<(), ComputeError> {
685    let mut failures = Vec::new();
686    for (axis, result) in [
687        (PartitionAxis::S, s),
688        (PartitionAxis::P, p),
689        (PartitionAxis::O, o),
690    ] {
691        if let Err(error) = result {
692            failures.push((axis, error));
693        }
694    }
695    if failures.is_empty() {
696        return Ok(());
697    }
698    if failures.len() == 3 {
699        let detail = failures
700            .iter()
701            .map(|(axis, error)| format!("{axis}: {error}"))
702            .collect::<Vec<_>>()
703            .join("; ");
704        return Err(ComputeError::AllAxesFailed(detail));
705    }
706    Err(failures.into_iter().next().expect("non-empty failures").1)
707}
708
709/// Outcome of a successful fan-out insert.
710#[derive(Debug, Clone, PartialEq, Eq)]
711pub struct InsertResult {
712    /// Number of quads encoded and sent.
713    pub quads: u64,
714    /// Entries written by `RegisterStrings` (sum across registry nodes).
715    pub registered: u64,
716    /// Inserted count reported per hexastore axis.
717    pub inserted_per_axis: BTreeMap<PartitionAxis, u64>,
718    /// Number of stored geo literals accepted through exact zero-area spike
719    /// reduction. Import summaries report this per load.
720    pub spike_reductions: u64,
721}
722
723fn dedupe_registry_entries(entries: Vec<(StrHash, String)>) -> Vec<(StrHash, String)> {
724    let mut map = BTreeMap::new();
725    for (hash, raw) in entries {
726        map.insert(hash, raw);
727    }
728    map.into_iter().collect()
729}
730
731impl<H: HexastoreInsert + HexastoreGeo, R: StringRegister + BlobStoreClient> WriteFanout<H, R> {
732    async fn put_temporal_with_retry(
733        &self,
734        puts: &[waratah_storage::TemporalIndexPut],
735    ) -> Result<(), ComputeError> {
736        with_retry(
737            self.retry,
738            || self.hexastore.put_temporal_index(puts),
739            |attempts, message| ComputeError::HexastoreInsert {
740                axis: PartitionAxis::O,
741                attempts,
742                message,
743            },
744        )
745        .await
746        .map(|_| ())
747    }
748
749    /// One `PutTextIndex` frame with the hexastore retry policy. Runs
750    /// before the hexastore inserts (ordering C3), so a failure here fails
751    /// the prepare before any axis commits.
752    async fn put_text_with_retry(
753        &self,
754        docs: &[waratah_storage::TextIndexDoc],
755    ) -> Result<(), ComputeError> {
756        with_retry(
757            self.retry,
758            || self.hexastore.put_text_index(docs),
759            |attempts, message| ComputeError::HexastoreInsert {
760                axis: PartitionAxis::O,
761                attempts,
762                message,
763            },
764        )
765        .await
766        .map(|_| ())
767    }
768}