Skip to main content

oak_core/sqlite/
refs_inspect.rs

1//! Local ref evidence from ONE pinned SQLite read transaction (fb-460).
2//!
3//! `current_branch`, every branch row, every branch head, parent inheritance,
4//! the legacy `metadata.head` pointer and the effective HEAD are all read
5//! inside the deferred read transaction `open_read_only` starts, so they can
6//! never mix two states. Nothing is written, migrated or hydrated.
7use super::file_inspect::{
8    bounded_metadata_text, database, failure, require_read_only, Checked, Failure, InspectionStatus,
9};
10use super::SqliteRepository;
11use crate::{Hash, OakError, Result};
12use rusqlite::Connection;
13use serde::Serialize;
14use std::collections::{BTreeMap, HashSet};
15
16pub const DEFAULT_REFS_MAX_BRANCHES: u64 = 1_000;
17pub const MAX_REFS_MAX_BRANCHES: u64 = 100_000;
18const REFERENCE_BYTES: i64 = 64 * 1024;
19const PARENT_HOPS: usize = 128;
20
21#[derive(Debug, Serialize)]
22pub struct RefsInspection {
23    pub snapshot: RefsSnapshot,
24    /// `metadata.current_branch`; `None` (or empty) means detached.
25    pub current_branch: Option<String>,
26    pub attached: bool,
27    /// Legacy `metadata.head` pointer. Authoritative only when detached.
28    pub legacy_head: Option<String>,
29    pub effective_head: EffectiveHead,
30    pub branches: Vec<BranchRef>,
31    /// Distinct names across `branches` rows and `branch_heads` rows.
32    pub branch_count: u64,
33    pub branches_truncated: bool,
34    pub max_branches: u64,
35    /// Every inconsistency observed in this snapshot. Empty means the refs
36    /// agree with each other, not that they agree with any remote.
37    pub disagreements: Vec<RefDisagreement>,
38}
39
40#[derive(Debug, Serialize)]
41pub struct RefsSnapshot {
42    pub source: &'static str,
43    pub single_read_transaction: bool,
44}
45
46#[derive(Debug, Serialize)]
47pub struct EffectiveHead {
48    pub commit: Option<String>,
49    /// `current_branch_head`, `parent_inheritance`, `detached_legacy_head`,
50    /// or `absent`.
51    pub source: &'static str,
52    /// Branches walked from `current_branch` to the branch owning the head.
53    #[serde(skip_serializing_if = "Vec::is_empty")]
54    pub branch_chain: Vec<String>,
55    pub status: InspectionStatus,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub reason: Option<String>,
58    /// Whether the effective head's commit row exists locally.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub commit_present: Option<bool>,
61}
62
63#[derive(Debug, Serialize)]
64pub struct BranchRef {
65    pub name: String,
66    /// False for head-only names such as the local copy of `main`.
67    pub has_branch_row: bool,
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub status: Option<String>,
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub parent_branch: Option<String>,
72    /// This branch's own `branch_heads` row.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub head: Option<String>,
75    /// Own head, else the first ancestor head found through `parent_branch`.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub effective_head: Option<String>,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub inherited_from: Option<String>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub head_commit_present: Option<bool>,
82    pub current: bool,
83}
84
85#[derive(Debug, Serialize)]
86pub struct RefDisagreement {
87    pub kind: &'static str,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub branch: Option<String>,
90    pub detail: String,
91}
92
93impl SqliteRepository {
94    /// Read every local ref in one pinned snapshot. Requires `open_read_only`.
95    pub fn inspect_refs(&self, max_branches: u64) -> Result<RefsInspection> {
96        if max_branches == 0 || max_branches > MAX_REFS_MAX_BRANCHES {
97            return Err(OakError::InvalidArgument(format!(
98                "--max-branches must be between 1 and {MAX_REFS_MAX_BRANCHES}"
99            )));
100        }
101        let conn = self.conn.lock().unwrap();
102        require_read_only(&conn, "refs inspection")?;
103        inspect(&conn, max_branches).map_err(|Failure(status, reason)| {
104            OakError::Database(format!("refs inspection {status:?}: {reason}"))
105        })
106    }
107}
108
109fn inspect(conn: &Connection, max_branches: u64) -> Checked<RefsInspection> {
110    let mut disagreements = Vec::new();
111    let current_branch = bounded_metadata_text(conn, "current_branch", "current branch metadata")?;
112    let attached = current_branch
113        .as_deref()
114        .is_some_and(|name| !name.is_empty());
115    let legacy_head = bounded_metadata_text(conn, "head", "legacy HEAD metadata")?;
116
117    // name -> (row?, status, parent) ; heads name -> head
118    let mut rows: BTreeMap<String, (Option<String>, Option<String>)> = BTreeMap::new();
119    let mut oversized = 0u64;
120    {
121        let mut stmt = conn
122            .prepare(
123                "SELECT CASE WHEN length(CAST(name AS BLOB))<=?1 THEN name END, \
124                 CASE WHEN length(CAST(status AS BLOB))<=?1 THEN status END, \
125                 CASE WHEN parent_branch IS NULL OR length(CAST(parent_branch AS BLOB))<=?1 \
126                 THEN parent_branch END, \
127                 parent_branch IS NOT NULL AND length(CAST(parent_branch AS BLOB))>?1 \
128                 FROM branches",
129            )
130            .map_err(database)?;
131        let mut query = stmt.query([REFERENCE_BYTES]).map_err(database)?;
132        while let Some(row) = query.next().map_err(database)? {
133            let name: Option<String> = row.get(0).map_err(database)?;
134            let Some(name) = name else {
135                oversized += 1;
136                continue;
137            };
138            if row.get::<_, bool>(3).map_err(database)? {
139                disagreements.push(RefDisagreement {
140                    kind: "oversized_reference",
141                    branch: Some(name.clone()),
142                    detail: "parent_branch exceeds the 64 KiB reference budget".into(),
143                });
144            }
145            rows.insert(
146                name,
147                (row.get(1).map_err(database)?, row.get(2).map_err(database)?),
148            );
149        }
150    }
151    let mut heads: BTreeMap<String, String> = BTreeMap::new();
152    {
153        let mut stmt = conn
154            .prepare(
155                "SELECT CASE WHEN length(CAST(branch_name AS BLOB))<=?1 THEN branch_name END, \
156                 CASE WHEN length(CAST(head_hash AS BLOB))<=?1 THEN head_hash END \
157                 FROM branch_heads",
158            )
159            .map_err(database)?;
160        let mut query = stmt.query([REFERENCE_BYTES]).map_err(database)?;
161        while let Some(row) = query.next().map_err(database)? {
162            let name: Option<String> = row.get(0).map_err(database)?;
163            let head: Option<String> = row.get(1).map_err(database)?;
164            match (name, head) {
165                (Some(name), Some(head)) => {
166                    heads.insert(name, head);
167                }
168                (Some(name), None) => disagreements.push(RefDisagreement {
169                    kind: "oversized_reference",
170                    branch: Some(name),
171                    detail: "branch head exceeds the 64 KiB reference budget".into(),
172                }),
173                (None, _) => oversized += 1,
174            }
175        }
176    }
177    if oversized > 0 {
178        disagreements.push(RefDisagreement {
179            kind: "oversized_reference",
180            branch: None,
181            detail: format!(
182                "{oversized} branch name(s) exceed the 64 KiB reference budget and are omitted"
183            ),
184        });
185    }
186
187    let commit_present = |hash: &str| -> Checked<Option<bool>> {
188        if Hash::from_hex(hash).is_err() || hash.len() != 64 {
189            return Ok(None);
190        }
191        conn.query_row(
192            "SELECT EXISTS(SELECT 1 FROM commits WHERE hash=?1)",
193            [hash],
194            |r| r.get::<_, bool>(0),
195        )
196        .map(Some)
197        .map_err(database)
198    };
199    // Effective head of one branch through parent inheritance; the chain
200    // lists every branch visited, ending at the owner of the head.
201    let resolve =
202        |start: &str| -> std::result::Result<(Option<String>, Vec<String>), &'static str> {
203            let mut seen = HashSet::new();
204            let mut chain = Vec::new();
205            let mut branch = start.to_string();
206            for _ in 0..PARENT_HOPS {
207                if !seen.insert(branch.clone()) {
208                    return Err("parent_cycle");
209                }
210                chain.push(branch.clone());
211                if let Some(head) = heads.get(&branch) {
212                    return Ok((Some(head.clone()), chain));
213                }
214                match rows.get(&branch).and_then(|(_, parent)| parent.clone()) {
215                    Some(parent) => branch = parent,
216                    None => return Ok((None, chain)),
217                }
218            }
219            Err("parent_chain_budget")
220        };
221
222    let mut names: Vec<&String> = rows.keys().chain(heads.keys()).collect();
223    names.sort();
224    names.dedup();
225    let branch_count = names.len() as u64;
226    let branches_truncated = branch_count > max_branches;
227    let mut branches = Vec::new();
228    for name in names.iter().take(max_branches as usize) {
229        let row = rows.get(*name);
230        let head = heads.get(*name).cloned();
231        let mut entry = BranchRef {
232            name: (*name).clone(),
233            has_branch_row: row.is_some(),
234            status: row.and_then(|(status, _)| status.clone()),
235            parent_branch: row.and_then(|(_, parent)| parent.clone()),
236            head: head.clone(),
237            effective_head: None,
238            inherited_from: None,
239            head_commit_present: None,
240            current: attached && current_branch.as_deref() == Some(name.as_str()),
241        };
242        match resolve(name) {
243            Ok((effective, chain)) => {
244                if head.is_none() && effective.is_some() {
245                    entry.inherited_from = chain.last().cloned();
246                }
247                entry.effective_head = effective;
248            }
249            Err(kind) => disagreements.push(RefDisagreement {
250                kind,
251                branch: Some((*name).clone()),
252                detail: "parent_branch chain never reaches a head".into(),
253            }),
254        }
255        if let Some(head) = head.as_deref() {
256            if Hash::from_hex(head).is_err() || head.len() != 64 {
257                disagreements.push(RefDisagreement {
258                    kind: "malformed_head",
259                    branch: Some((*name).clone()),
260                    detail: "branch head is not a 64-character hexadecimal commit hash".into(),
261                });
262            }
263            entry.head_commit_present = commit_present(head)?;
264            if entry.head_commit_present == Some(false) {
265                disagreements.push(RefDisagreement {
266                    kind: "head_commit_missing",
267                    branch: Some((*name).clone()),
268                    detail: format!("branch head {head} has no local commit row"),
269                });
270            }
271        }
272        if let Some(parent) = entry.parent_branch.as_deref() {
273            if parent != "main" && !rows.contains_key(parent) && !heads.contains_key(parent) {
274                disagreements.push(RefDisagreement {
275                    kind: "dangling_parent",
276                    branch: Some((*name).clone()),
277                    detail: format!("parent_branch '{parent}' has no local branch or head row"),
278                });
279            }
280        }
281        branches.push(entry);
282    }
283
284    let mut effective = EffectiveHead {
285        commit: None,
286        source: "absent",
287        branch_chain: Vec::new(),
288        status: InspectionStatus::Verified,
289        reason: None,
290        commit_present: None,
291    };
292    if attached {
293        let current = current_branch.clone().unwrap_or_default();
294        if !rows.contains_key(&current) && !heads.contains_key(&current) {
295            disagreements.push(RefDisagreement {
296                kind: "current_branch_unknown",
297                branch: Some(current.clone()),
298                detail: "current_branch names a branch with no local branch or head row".into(),
299            });
300        }
301        match resolve(&current) {
302            Ok((Some(commit), chain)) => {
303                effective.source = if chain.len() == 1 {
304                    "current_branch_head"
305                } else {
306                    "parent_inheritance"
307                };
308                effective.commit = Some(commit);
309                effective.branch_chain = chain;
310            }
311            Ok((None, chain)) => {
312                effective.status = InspectionStatus::ObjectMissing;
313                effective.reason = Some("HEAD is absent".into());
314                effective.branch_chain = chain;
315            }
316            Err(kind) => {
317                let Failure(status, reason) = if kind == "parent_cycle" {
318                    failure(
319                        InspectionStatus::Corrupt,
320                        "HEAD branch parent chain contains a cycle",
321                    )
322                } else {
323                    failure(
324                        InspectionStatus::BudgetExceeded,
325                        "HEAD parent chain exceeds 128-hop verification budget",
326                    )
327                };
328                effective.status = status;
329                effective.reason = Some(reason);
330            }
331        }
332        if let (Some(legacy), Some(commit)) = (legacy_head.as_deref(), effective.commit.as_deref())
333        {
334            if legacy != commit {
335                disagreements.push(RefDisagreement {
336                    kind: "legacy_head_differs",
337                    branch: Some(current.clone()),
338                    detail: format!(
339                        "metadata.head {legacy} differs from the effective HEAD {commit}; the branch head wins while attached"
340                    ),
341                });
342            }
343        }
344    } else if let Some(legacy) = legacy_head.clone() {
345        effective.source = "detached_legacy_head";
346        effective.commit = Some(legacy);
347    } else {
348        effective.status = InspectionStatus::ObjectMissing;
349        effective.reason = Some("HEAD is absent".into());
350    }
351    if let Some(commit) = effective.commit.as_deref() {
352        if Hash::from_hex(commit).is_err() || commit.len() != 64 {
353            effective.status = InspectionStatus::Corrupt;
354            effective.reason =
355                Some("effective HEAD is not a 64-character hexadecimal commit hash".into());
356        } else {
357            effective.commit_present = commit_present(commit)?;
358            if effective.commit_present == Some(false) {
359                effective.status = InspectionStatus::ObjectMissing;
360                effective.reason = Some(format!("effective HEAD {commit} has no local commit row"));
361            }
362        }
363    }
364
365    Ok(RefsInspection {
366        snapshot: RefsSnapshot {
367            source: "local_sqlite_snapshot",
368            single_read_transaction: true,
369        },
370        current_branch: current_branch.filter(|name| !name.is_empty()),
371        attached,
372        legacy_head,
373        effective_head: effective,
374        branches,
375        branch_count,
376        branches_truncated,
377        max_branches,
378        disagreements,
379    })
380}