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; 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    /// Incrementally maintain the search-index memo for a known
96    /// touched-id set: replace or remove
97    /// exactly the touched documents in place and advance the memo's
98    /// key, instead of dropping the whole map. Semantics:
99    ///
100    /// - Memo empty → nothing to maintain; the next read builds fresh.
101    /// - Memo current (key matches) → no-op (rollback already landed).
102    /// - Schemas epoch moved → the index FIELD SET may have changed:
103    ///   the named, scoped fallback — drop the memo for a full
104    ///   rebuild. Never a silent widening: this is the one case the
105    ///   plan names (schema-shape change).
106    /// - Otherwise: per touched id, a real non-stub entity in the
107    ///   store is re-indexed (delete-then-add on the id term), and an
108    ///   absent or stub entry is removed — stubs stay excluded exactly
109    ///   as the bulk build excludes them. Touched mems' writers
110    ///   commit; any tantivy error falls back to dropping the memo
111    ///   (warn-logged), never to serving a stale index.
112    #[cfg(not(target_arch = "wasm32"))]
113    pub(crate) fn maintain_search_indexes(&mut self, touched: &[crate::EntityId]) {
114        let current = crate::engine::DerivedKey {
115            store_generation: self.store.generation(),
116            schemas_epoch: self.schemas_epoch,
117        };
118        let Some((memo_key, indexes)) = self.search_indexes_memo.get_mut() else {
119            return;
120        };
121        if *memo_key == current {
122            return;
123        }
124        if memo_key.schemas_epoch != current.schemas_epoch {
125            self.search_indexes_memo = OnceCell::new();
126            return;
127        }
128        let mut touched_mems: std::collections::HashSet<&str> = std::collections::HashSet::new();
129        for id in touched {
130            let Some(idx) = indexes.get_mut(id.mem()) else {
131                continue;
132            };
133            let result = match self.store.get(id) {
134                Some(entity) if !entity.stub => idx.index_entity(entity),
135                _ => idx.remove_entity(id),
136            };
137            if let Err(e) = result {
138                tracing::warn!(
139                    id = id.as_ref(),
140                    error = %e,
141                    "incremental index maintenance failed; dropping the memo for a full rebuild"
142                );
143                self.search_indexes_memo = OnceCell::new();
144                return;
145            }
146            touched_mems.insert(id.mem());
147        }
148        for (mem, idx) in indexes.iter_mut() {
149            if !touched_mems.contains(mem.as_str()) {
150                continue;
151            }
152            if let Err(e) = idx.commit() {
153                tracing::warn!(
154                    mem = mem.as_str(),
155                    error = %e,
156                    "incremental index commit failed; dropping the memo for a full rebuild"
157                );
158                self.search_indexes_memo = OnceCell::new();
159                return;
160            }
161        }
162        *memo_key = current;
163    }
164
165    /// No-op shim on `wasm32`, mirroring `invalidate_search_indexes`
166    /// so mutation paths call it unconditionally.
167    #[cfg(target_arch = "wasm32")]
168    pub(crate) fn maintain_search_indexes(&mut self, _touched: &[crate::EntityId]) {}
169
170    /// Unconditionally drop the search-index memo, regardless of its
171    /// generation. The forced variant exists for embedders that want
172    /// to release the index's memory in a long-lived process (or force
173    /// a from-scratch rebuild for verification); the generation-checked
174    /// [`Self::invalidate_search_indexes`] stays the mutation-path
175    /// hook.
176    pub fn drop_search_indexes(&mut self) {
177        #[cfg(not(target_arch = "wasm32"))]
178        {
179            self.search_indexes_memo = OnceCell::new();
180        }
181    }
182
183    pub fn invalidate_search_indexes(&mut self) {
184        #[cfg(not(target_arch = "wasm32"))]
185        {
186            // Same generation check as `invalidate_communities`: keep
187            // the memo when the store still sits at its generation
188            // (the batch-rollback case), clear otherwise.
189            if let Some((memo_key, _)) = self.search_indexes_memo.get()
190                && *memo_key == self.derived_key()
191            {
192                return;
193            }
194            self.search_indexes_memo = OnceCell::new();
195        }
196    }
197
198    /// Filter the in-memory store by metadata only (no text match).
199    #[cfg(not(target_arch = "wasm32"))]
200    pub fn list(&self, scope: &SearchScope) -> crate::ops::ListResult {
201        let fallback = engine_fallback_type();
202        crate::ops::search::list(&self.store, scope, fallback.as_ref(), &self.schemas)
203    }
204
205    /// Run a search against the lazily-built index map. Returns
206    /// [`EngineError::SearchUnavailable`] on `wasm32` targets — browser
207    /// consumers route search to the bridge; the local
208    /// engine never builds a tantivy index in WASM. Native targets get
209    /// the same shape as before, wrapped in `Ok`.
210    pub fn search(&self, scope: &SearchScope) -> Result<SearchResult, EngineError> {
211        // A mem filter naming a quarantined OR nonexistent mem refuses
212        // typed `UNKNOWN_MEM`, matching every other mem-naming surface. A
213        // success with 0 hits (the old nonexistent-mem behaviour, with a
214        // missing-index warning) is indistinguishable from a true empty
215        // result — the one thing a typed surface must never be.
216        if let Some(mem) = scope.mem.as_deref()
217            && (self.quarantine_reason(mem).is_some() || !self.mem_router.is_visible(mem))
218        {
219            return Err(self.unknown_mem_error(mem));
220        }
221        #[cfg(target_arch = "wasm32")]
222        {
223            let _ = scope;
224            return Err(EngineError::SearchUnavailable);
225        }
226        #[cfg(not(target_arch = "wasm32"))]
227        {
228            let fallback = engine_fallback_type();
229            Ok(crate::ops::search::search(
230                &self.store,
231                scope,
232                fallback.as_ref(),
233                self.search_indexes(),
234                &self.schemas,
235            ))
236        }
237    }
238
239    /// All mem-relative entity paths under `mem`. Delegates to
240    /// the backend's `list_entities`. Order is backend-defined.
241    pub fn list_entities(&self, mem: &str) -> Result<Vec<PathBuf>, EngineError> {
242        let m = self.find_mount(mem)?;
243        m.backend.list_entities().map_err(EngineError::Backend)
244    }
245
246    /// Raw bytes for a single entity (`Ok(None)` if absent).
247    pub fn read_entity(&self, mem: &str, rel_path: &Path) -> Result<Option<Vec<u8>>, EngineError> {
248        let m = self.find_mount(mem)?;
249        m.backend
250            .read_entity(rel_path)
251            .map_err(EngineError::Backend)
252    }
253
254    /// Provenance entries for `mem` since `cursor`. Cursor shape is
255    /// backend-specific (RFC-3339 timestamp for folder, commit SHA for
256    /// git-branch); `None` means "from the beginning".
257    pub fn read_provenance(
258        &self,
259        mem: &str,
260        cursor: Option<&str>,
261    ) -> Result<Vec<Provenance>, EngineError> {
262        let m = self.find_mount(mem)?;
263        m.backend
264            .read_provenance(cursor)
265            .map_err(EngineError::Backend)
266    }
267
268    /// Capability declared on the mount for `mem`. Surfaced for
269    /// callers that need to gate before dispatching a write — the
270    /// engine itself does not yet enforce capability (mutation paths
271    /// land in a later session).
272    pub fn capability(&self, mem: &str) -> Result<crate::workspace::MountCapability, EngineError> {
273        let m = self.find_mount(mem)?;
274        Ok(m.mount.capability)
275    }
276
277    /// Returns `true` when `from`'s source mem is mounted with
278    /// [`crate::workspace::MountCapability::ReadOnly`]. Returns
279    /// `false` for Write-Mems and for mems whose mount is absent
280    /// from the router (no mount → no ReadOnly assertion can be
281    /// made; the absence is treated as not-ReadOnly so consumers
282    /// don't trip on transient lookup misses).
283    ///
284    /// Plan body §"Single edge source in the store" specifies this
285    /// helper as the derived-on-demand alternative to adding a new
286    /// field on [`crate::store::Edge`]. Strict-invariant validators
287    /// and surfaces that want to highlight cross-mount references
288    /// call this rather than pattern-matching on a per-edge marker.
289    /// The information is fully derivable from the current mount
290    /// roster, so no new state needs to live on the edge itself.
291    pub fn edge_is_from_readonly(&self, from: &EntityId) -> bool {
292        match self.capability(from.mem()) {
293            Ok(crate::workspace::MountCapability::ReadOnly) => true,
294            Ok(crate::workspace::MountCapability::Write) | Err(_) => false,
295        }
296    }
297}