Skip to main content

memstead_base/engine/query/
reads.rs

1//! Plain reads: status and context, the search indexes and their maintenance, list and search, and the entity, provenance and capability reads.
2
3use super::*;
4
5impl Engine {
6    /// Engine-wide [`crate::ops::Status`] across every mount — the graph
7    /// counts behind `memstead status` (renamed from `stats` with the
8    /// command, D11; fields unchanged).
9    pub fn status(&self) -> crate::ops::Status {
10        let mut types_in_use: Vec<String> = self
11            .store
12            .all_entities()
13            .filter(|e| !e.stub && !e.entity_type.is_empty())
14            .map(|e| e.entity_type.clone())
15            .collect();
16        types_in_use.sort();
17        types_in_use.dedup();
18
19        let mut edge_types: std::collections::BTreeMap<String, usize> =
20            std::collections::BTreeMap::new();
21        for id in self.store.all_ids() {
22            for edge in self.store.outgoing(id) {
23                *edge_types.entry(edge.rel_type.clone()).or_insert(0) += 1;
24            }
25        }
26
27        crate::ops::Status {
28            entity_count: self.store.all_entities().filter(|e| !e.stub).count(),
29            edge_count: self.store.edge_count(),
30            edge_types,
31            community_count: self.communities().count,
32            mem_count: self.mounts.len(),
33            types_in_use,
34        }
35    }
36
37    /// Build a [`ContextResult`] for `id`: the community cluster id
38    /// (or `None` when the entity is a stub or not present), plus the
39    /// outgoing + incoming neighbour lists.
40    pub fn context(&self, id: &EntityId) -> Option<ContextResult> {
41        let entity = self.store.get(id)?;
42        let community = self
43            .communities()
44            .entity_cluster_map
45            .get(id.as_ref())
46            .cloned();
47        let mut neighbors = Vec::new();
48        for edge in self.store.outgoing(id) {
49            if let Some(target) = self.store.get(&edge.target) {
50                neighbors.push(NeighborInfo {
51                    id: target.id.clone(),
52                    title: target.title.clone(),
53                    relationship: edge.rel_type.clone(),
54                    direction: Direction::Outgoing,
55                });
56            }
57        }
58        for edge in self.store.incoming(id) {
59            if let Some(source) = self.store.get(&edge.from) {
60                neighbors.push(NeighborInfo {
61                    id: source.id.clone(),
62                    title: source.title.clone(),
63                    relationship: edge.rel_type.clone(),
64                    direction: Direction::Incoming,
65                });
66            }
67        }
68        Some(ContextResult {
69            entity_id: entity.id.clone(),
70            community,
71            neighbors,
72        })
73    }
74
75    /// Lazily-built per-mem search index map. The map carries one
76    /// entry per writable mem. Build cost scales with entity count;
77    /// expect hundreds-of-ms for thousand-entity workspaces. Not
78    /// available on `wasm32` targets — search lives behind the bridge
79    /// (see [`Self::search`] for the typed refuse).
80    #[cfg(not(target_arch = "wasm32"))]
81    pub fn search_indexes(&self) -> &HashMap<String, MemIndex> {
82        if let Some((memo_key, _)) = self.search_indexes_memo.get() {
83            debug_assert_eq!(
84                *memo_key,
85                self.derived_key(),
86                "search memo key lags the engine — a mutation path missed invalidate_search_indexes"
87            );
88        }
89        &self
90            .search_indexes_memo
91            .get_or_init(|| (self.derived_key(), build_all(&self.store, &self.schemas)))
92            .1
93    }
94
95    /// Drop the cached per-mem search index map. No-op on `wasm32`
96    /// where no index exists; the method stays present so mutation
97    /// hooks can call it unconditionally.
98    /// Incrementally maintain the search-index memo for a known
99    /// touched-id set: replace or remove
100    /// exactly the touched documents in place and advance the memo's
101    /// key, instead of dropping the whole map. Semantics:
102    ///
103    /// - Memo empty → nothing to maintain; the next read builds fresh.
104    /// - Memo current (key matches) → no-op (rollback already landed).
105    /// - Schemas epoch moved → the index FIELD SET may have changed:
106    ///   the named, scoped fallback — drop the memo for a full
107    ///   rebuild. Never a silent widening: this is the one case the
108    ///   plan names (schema-shape change).
109    /// - Otherwise: per touched id, a real non-stub entity in the
110    ///   store is re-indexed (delete-then-add on the id term), and an
111    ///   absent or stub entry is removed — stubs stay excluded exactly
112    ///   as the bulk build excludes them. Touched mems' writers
113    ///   commit; any tantivy error falls back to dropping the memo
114    ///   (warn-logged), never to serving a stale index.
115    #[cfg(not(target_arch = "wasm32"))]
116    pub(crate) fn maintain_search_indexes(&mut self, touched: &[crate::EntityId]) {
117        let current = crate::engine::DerivedKey {
118            store_generation: self.store.generation(),
119            schemas_epoch: self.schemas_epoch,
120        };
121        let Some((memo_key, indexes)) = self.search_indexes_memo.get_mut() else {
122            return;
123        };
124        if *memo_key == current {
125            return;
126        }
127        if memo_key.schemas_epoch != current.schemas_epoch {
128            self.search_indexes_memo = OnceCell::new();
129            return;
130        }
131        let mut touched_mems: std::collections::HashSet<&str> = std::collections::HashSet::new();
132        for id in touched {
133            let Some(idx) = indexes.get_mut(id.mem()) else {
134                continue;
135            };
136            let result = match self.store.get(id) {
137                Some(entity) if !entity.stub => idx.index_entity(entity),
138                _ => idx.remove_entity(id),
139            };
140            if let Err(e) = result {
141                tracing::warn!(
142                    id = id.as_ref(),
143                    error = %e,
144                    "incremental index maintenance failed; dropping the memo for a full rebuild"
145                );
146                self.search_indexes_memo = OnceCell::new();
147                return;
148            }
149            touched_mems.insert(id.mem());
150        }
151        for (mem, idx) in indexes.iter_mut() {
152            if !touched_mems.contains(mem.as_str()) {
153                continue;
154            }
155            if let Err(e) = idx.commit() {
156                tracing::warn!(
157                    mem = mem.as_str(),
158                    error = %e,
159                    "incremental index commit failed; dropping the memo for a full rebuild"
160                );
161                self.search_indexes_memo = OnceCell::new();
162                return;
163            }
164        }
165        *memo_key = current;
166    }
167
168    /// No-op shim on `wasm32`, mirroring `invalidate_search_indexes`
169    /// so mutation paths call it unconditionally.
170    #[cfg(target_arch = "wasm32")]
171    pub(crate) fn maintain_search_indexes(&mut self, _touched: &[crate::EntityId]) {}
172
173    /// Unconditionally drop the search-index memo, regardless of its
174    /// generation. The forced variant exists for embedders that want
175    /// to release the index's memory in a long-lived process (or force
176    /// a from-scratch rebuild for verification); the generation-checked
177    /// [`Self::invalidate_search_indexes`] stays the mutation-path
178    /// hook.
179    pub fn drop_search_indexes(&mut self) {
180        #[cfg(not(target_arch = "wasm32"))]
181        {
182            self.search_indexes_memo = OnceCell::new();
183        }
184    }
185
186    pub fn invalidate_search_indexes(&mut self) {
187        #[cfg(not(target_arch = "wasm32"))]
188        {
189            // Same generation check as `invalidate_communities`: keep
190            // the memo when the store still sits at its generation
191            // (the batch-rollback case), clear otherwise.
192            if let Some((memo_key, _)) = self.search_indexes_memo.get()
193                && *memo_key == self.derived_key()
194            {
195                return;
196            }
197            self.search_indexes_memo = OnceCell::new();
198        }
199    }
200
201    /// Filter the in-memory store by metadata only (no text match).
202    #[cfg(not(target_arch = "wasm32"))]
203    pub fn list(&self, scope: &SearchScope) -> crate::ops::ListResult {
204        let fallback = engine_fallback_type();
205        crate::ops::search::list(&self.store, scope, fallback.as_ref(), &self.schemas)
206    }
207
208    /// Run a search against the lazily-built index map. Returns
209    /// [`EngineError::SearchUnavailable`] on `wasm32` targets — browser
210    /// consumers route search to the bridge; the local
211    /// engine never builds a tantivy index in WASM. Native targets get
212    /// the same shape as before, wrapped in `Ok`.
213    pub fn search(&self, scope: &SearchScope) -> Result<SearchResult, EngineError> {
214        // A mem filter naming a quarantined OR nonexistent mem refuses
215        // typed `UNKNOWN_MEM`, matching every other mem-naming surface. A
216        // success with 0 hits (the old nonexistent-mem behaviour, with a
217        // missing-index warning) is indistinguishable from a true empty
218        // result — the one thing a typed surface must never be.
219        if let Some(mem) = scope.mem.as_deref()
220            && (self.quarantine_reason(mem).is_some() || !self.mem_router.is_visible(mem))
221        {
222            return Err(self.unknown_mem_error(mem));
223        }
224        #[cfg(target_arch = "wasm32")]
225        {
226            let _ = scope;
227            return Err(EngineError::SearchUnavailable);
228        }
229        #[cfg(not(target_arch = "wasm32"))]
230        {
231            let fallback = engine_fallback_type();
232            Ok(crate::ops::search::search(
233                &self.store,
234                scope,
235                fallback.as_ref(),
236                self.search_indexes(),
237                &self.schemas,
238            ))
239        }
240    }
241
242    /// All mem-relative entity paths under `mem`. Delegates to
243    /// the backend's `list_entities`. Order is backend-defined.
244    pub fn list_entities(&self, mem: &str) -> Result<Vec<PathBuf>, EngineError> {
245        let m = self.find_mount(mem)?;
246        m.backend.list_entities().map_err(EngineError::Backend)
247    }
248
249    /// Raw bytes for a single entity (`Ok(None)` if absent).
250    pub fn read_entity(&self, mem: &str, rel_path: &Path) -> Result<Option<Vec<u8>>, EngineError> {
251        let m = self.find_mount(mem)?;
252        m.backend
253            .read_entity(rel_path)
254            .map_err(EngineError::Backend)
255    }
256
257    /// Provenance entries for `mem` since `cursor`. Cursor shape is
258    /// backend-specific (RFC-3339 timestamp for folder, commit SHA for
259    /// git-branch); `None` means "from the beginning".
260    pub fn read_provenance(
261        &self,
262        mem: &str,
263        cursor: Option<&str>,
264    ) -> Result<Vec<Provenance>, EngineError> {
265        let m = self.find_mount(mem)?;
266        m.backend
267            .read_provenance(cursor)
268            .map_err(EngineError::Backend)
269    }
270
271    /// Capability declared on the mount for `mem`. Surfaced for
272    /// callers that need to gate before dispatching a write — the
273    /// engine itself does not yet enforce capability (mutation paths
274    /// land in a later session).
275    pub fn capability(&self, mem: &str) -> Result<crate::workspace::MountCapability, EngineError> {
276        let m = self.find_mount(mem)?;
277        Ok(m.mount.capability)
278    }
279
280    /// Returns `true` when `from`'s source mem is mounted with
281    /// [`crate::workspace::MountCapability::ReadOnly`]. Returns
282    /// `false` for Write-Mems and for mems whose mount is absent
283    /// from the router (no mount → no ReadOnly assertion can be
284    /// made; the absence is treated as not-ReadOnly so consumers
285    /// don't trip on transient lookup misses).
286    ///
287    /// Plan body §"Single edge source in the store" specifies this
288    /// helper as the derived-on-demand alternative to adding a new
289    /// field on [`crate::store::Edge`]. Strict-invariant validators
290    /// and surfaces that want to highlight cross-mount references
291    /// call this rather than pattern-matching on a per-edge marker.
292    /// The information is fully derivable from the current mount
293    /// roster, so no new state needs to live on the edge itself.
294    pub fn edge_is_from_readonly(&self, from: &EntityId) -> bool {
295        match self.capability(from.mem()) {
296            Ok(crate::workspace::MountCapability::ReadOnly) => true,
297            Ok(crate::workspace::MountCapability::Write) | Err(_) => false,
298        }
299    }
300}