Version control for agents

Commit 888f73cb

888f73cb5460Mergedfrom mrmrs-a8681f

mrmrs · 1 month ago · 1 file · ~1 modified

Description

serve: honour depth on GET /pull (hosted-parity shallow clone)

Problem: local oak serve ignored ?depth= on GET /api/{owner}/{repo}/pull. oak clone --shallow (cli/src/commands/repo.rs, request_clone_pull sends depth=1, plus branch_name with --branch) downloaded the full history over loopback while still printing "Shallow clone (recent history only)". Shallow-clone behaviour, notably the ancestor backfill on first parent refresh, could not be reproduced or benchmarked locally.

Contract (matched to hosted oak/oakspace @ fb0288e9, crates/oak-web/src/server/api/repos.rs):

  • depth > 0 returns the newest depth commits on the first-parent (parent_hash) chain from the target head. Commits are returned oldest first, and the chain stops at a missing commit (shallow_clone_commits, ~L77-107; pull dispatch ~L7658-7672).
  • Target: the branch_name head when given (a branch with no head yields no commits), else the default branch (shallow_clone_head ~L68; local uses its existing default_branch_name).
  • since is ignored on the shallow path, as hosted does. depth=0 or unset leaves the response unchanged.
  • Trees and blobs are those reachable from the returned commits only, which uses the same assembly loop. The branch list, head, and the published-closure filter are unchanged.

Evidence:

  • RED: new serve tests pull_depth_returns_newest_first_parent_commits_like_hosted and pull_depth_with_branch_name_walks_from_that_branch_head failed before the fix (depth=1 returned all 5 commits) and pass after it. All 74 serve lib tests pass. Integration suites pass: integrity_clone, clone_receipt, pull, push, sparse, agent_json, zero_byte_blobs, metadata_sync_outcomes, review_missing_ancestry.
  • Real binaries on loopback, 1000-commit merge-history fixture (c1000-s1), installed 0.103.0 client:
    • Before: clone --shallow stored 1000 commits (6.6 MB), and switch -c made 0 /commits/info calls.
    • After: clone --shallow stores 1 commit (374 blobs, 75 trees, 0.51 MB). switch -c x prints "linked 999 ancestor commit(s)" with 1000 POST /commits/info (42 MB), which reproduces the hosted backfill.
  • Full clone unchanged: on the same data dir, old and new serve return a byte-identical sha256 for /pull, ?depth=0, ?branch_name=main and ?branch_name=main&depth=0. A full-clone row count is 1000 commits / 981 blobs / 2873 trees on both.
  • fmt and cargo clippy --workspace --all-targets -- -D warnings are clean.

Limitations and non-goals:

  • Local serve still has no bounded integrity preflight or integrity_snapshot / selected_branch support, so --allow-legacy-scope is still required for a scoped clone. That is a separate protocol surface, not part of this change.
  • Local serve also still lacks hosted's since divergence and force checks, and its non-shallow clone returns rows by branch_name rather than the reachable set. Both behaviours pre-date this change and are unchanged.

Details

Commit
888f73cb5460
Parent
21f9b7e2c180
Merge parent
acd622f8c8e8

cli/src/commands/serve.rsmodifiedView file

@@ -2089,9 +2089,32 @@
20892089 .await
20902090 }
20912091
2092+/// The newest `depth` commits reachable from `branch`'s head through
2093+/// `parent_hash` only, returned oldest first so the client writes the head
2094+/// last. Mirrors hosted oakspace `shallow_clone_commits`: the oldest commit's
2095+/// parent may dangle (the shallow boundary), and a branch without a head
2096+/// yields nothing.
2097+fn shallow_commits(repo: &SqliteRepository, branch: &str, depth: u32) -> Result<Vec<Commit>> {
2098+ let mut walked = Vec::new();
2099+ let mut current = repo.get_branch_head(branch)?;
2100+ while let Some(hash) = current {
2101+ if walked.len() as u64 >= u64::from(depth) {
2102+ break;
2103+ }
2104+ let Some(commit) = repo.get_commit(&hash)? else {
2105+ break;
2106+ };
2107+ current = commit.parent_hash.clone();
2108+ walked.push(commit);
2109+ }
2110+ walked.reverse();
2111+ Ok(walked)
2112+}
2113+
20922114 /// `GET /api/{owner}/{name}/pull` — return commits (+ reachable trees/blobs and
20932115 /// branch heads) on the requested branch since `?since=`. Clone (no
2094-/// `branch_name`) defaults to the repo's default branch.
2116+/// `branch_name`) defaults to the repo's default branch. `?depth=N` (N > 0)
2117+/// returns only the newest N first-parent commits instead (shallow clone).
20952118 async fn pull(
20962119 State(state): State<ServeState>,
20972120 AxPath((owner, name)): AxPath<(String, String)>,
@@ -2108,9 +2131,14 @@
21082131
21092132 let since = query.since.as_ref().map(|s| Hash(s.clone()));
21102133 let published = published_object_closure(&repo)?;
2111- let mut commits = match &target {
2112- Some(b) => repo.get_commits_since(b, since.as_ref())?,
2113- None => Vec::new(),
2134+ // Shallow clone (`oak clone --shallow` sends `depth=1`): mirror hosted
2135+ // `shallow_clone_commits` — the newest `depth` commits on the target
2136+ // branch's first-parent chain, oldest first, ignoring `since`. `0`
2137+ // means "no limit", same as unset.
2138+ let mut commits = match (query.depth.filter(|depth| *depth > 0), &target) {
2139+ (Some(depth), Some(b)) => shallow_commits(&repo, b, depth)?,
2140+ (None, Some(b)) => repo.get_commits_since(b, since.as_ref())?,
2141+ (_, None) => Vec::new(),
21142142 };
21152143 commits.retain(|commit| published.commits.contains(commit.hash.as_str()));
21162144
@@ -5762,4 +5790,171 @@
57625790 "a metadata-only close must not move the branch head"
57635791 );
57645792 }
5793+
5794+ /// Seed `oak/oak` with a first-parent `main` chain of `len` commits (each
5795+ /// commit's tree holds only its own `f{i}.txt`), a `side` branch commit
5796+ /// merged into the last `main` commit, and a `feature` branch forked from
5797+ /// `main`'s head with `feature_len` commits. Returns (main chain oldest
5798+ /// first, side commit, feature chain oldest first).
5799+ fn seed_history(root: &Path, len: usize, feature_len: usize) -> (Vec<Hash>, Hash, Vec<Hash>) {
5800+ let repo = open_for_write(root, "oak", "oak").unwrap();
5801+ repo.store_branch(&Branch::new("main".to_string(), None, None))
5802+ .unwrap();
5803+ repo.store_branch(&Branch::new(
5804+ "side".to_string(),
5805+ None,
5806+ Some("main".to_string()),
5807+ ))
5808+ .unwrap();
5809+ repo.store_branch(&Branch::new(
5810+ "feature".to_string(),
5811+ None,
5812+ Some("main".to_string()),
5813+ ))
5814+ .unwrap();
5815+ let base = Utc::now() - chrono::Duration::hours(1);
5816+ let mut tick = 0i64;
5817+ let mut commit_on =
5818+ |branch: &str, file: &str, parent: Option<Hash>, merge_parent: Option<Hash>| {
5819+ let blob = repo
5820+ .put_blob(format!("{file} content").into_bytes())
5821+ .unwrap();
5822+ let manifest = repo
5823+ .put_manifest(vec![oak_core::ManifestEntry {
5824+ path: file.to_string(),
5825+ blob_hash: blob,
5826+ mode: oak_core::FileMode::Regular,
5827+ }])
5828+ .unwrap();
5829+ tick += 1;
5830+ let commit = Commit::with_timestamp(
5831+ branch.to_string(),
5832+ parent,
5833+ merge_parent,
5834+ manifest,
5835+ "tester".to_string(),
5836+ None,
5837+ Vec::new(),
5838+ base + chrono::Duration::seconds(tick),
5839+ )
5840+ .unwrap();
5841+ repo.store_commit(&commit).unwrap();
5842+ commit.hash
5843+ };
5844+ let mut main = Vec::new();
5845+ let mut side = None;
5846+ for i in 0..len {
5847+ let parent = main.last().cloned();
5848+ if i + 1 == len {
5849+ side = Some(commit_on("side", "side.txt", main.first().cloned(), None));
5850+ }
5851+ let merge_parent = if i + 1 == len { side.clone() } else { None };
5852+ main.push(commit_on(
5853+ "main",
5854+ &format!("f{i}.txt"),
5855+ parent,
5856+ merge_parent,
5857+ ));
5858+ }
5859+ let mut feature = Vec::new();
5860+ for i in 0..feature_len {
5861+ let parent = feature.last().or(main.last()).cloned();
5862+ feature.push(commit_on("feature", &format!("feat{i}.txt"), parent, None));
5863+ }
5864+ let side = side.unwrap();
5865+ repo.set_branch_head("main", main.last().unwrap()).unwrap();
5866+ repo.set_branch_head("side", &side).unwrap();
5867+ if let Some(head) = feature.last() {
5868+ repo.set_branch_head("feature", head).unwrap();
5869+ }
5870+ repo.set_head(main.last().unwrap()).unwrap();
5871+ (main, side, feature)
5872+ }
5873+
5874+ async fn pull_query(base: &str, query: &str) -> PullResponse {
5875+ let response = test_client()
5876+ .get(format!("{base}/api/oak/oak/pull{query}"))
5877+ .send()
5878+ .await
5879+ .unwrap();
5880+ assert_eq!(response.status(), StatusCode::OK, "pull{query}");
5881+ response.json().await.unwrap()
5882+ }
5883+
5884+ fn pulled_hashes(response: &PullResponse) -> Vec<String> {
5885+ response.commits.iter().map(|c| c.hash.clone()).collect()
5886+ }
5887+
5888+ fn hex(hashes: &[Hash]) -> Vec<String> {
5889+ hashes.iter().map(Hash::to_string).collect()
5890+ }
5891+
5892+ /// Hosted parity (oakspace `repos.rs` `shallow_clone_commits`): `depth=N`
5893+ /// returns the newest N commits of the first-parent chain from the target
5894+ /// head, oldest first, with only those commits' trees and blobs.
5895+ #[tokio::test(flavor = "current_thread")]
5896+ async fn pull_depth_returns_newest_first_parent_commits_like_hosted() {
5897+ let temp = tempfile::TempDir::new().unwrap();
5898+ let root = temp.path().to_path_buf();
5899+ let (main, side, _) = seed_history(&root, 5, 0);
5900+ let base = spawn_server(root).await;
5901+
5902+ let full = pull_query(&base, "").await;
5903+ assert_eq!(full.commits.len(), 5, "full clone returns the main chain");
5904+
5905+ let shallow = pull_query(&base, "?depth=1").await;
5906+ assert_eq!(pulled_hashes(&shallow), hex(&main[4..]));
5907+ assert_eq!(shallow.head.as_deref(), Some(main[4].to_string().as_str()));
5908+ let blob_count = shallow.blobs.len();
5909+ assert_eq!(
5910+ blob_count, 1,
5911+ "a depth-1 response carries only the head snapshot's blobs"
5912+ );
5913+ assert!(
5914+ shallow.branches.iter().any(|b| b.name == "main"),
5915+ "branch metadata is unchanged by depth"
5916+ );
5917+
5918+ // First-parent walk: the merged-in side commit is never included,
5919+ // and the result stays oldest-first so the head is written last.
5920+ let two = pull_query(&base, "?depth=2").await;
5921+ assert_eq!(pulled_hashes(&two), hex(&main[3..]));
5922+ assert!(!pulled_hashes(&two).contains(&side.to_string()));
5923+
5924+ // Deeper than history: the whole first-parent chain, nothing more.
5925+ let deep = pull_query(&base, "?depth=50").await;
5926+ assert_eq!(pulled_hashes(&deep), hex(&main));
5927+
5928+ // depth=0 is "no limit" — identical to an unset depth.
5929+ let zero = pull_query(&base, "?depth=0").await;
5930+ assert_eq!(pulled_hashes(&zero), pulled_hashes(&full));
5931+ assert_eq!(zero.blobs.len(), full.blobs.len());
5932+ assert_eq!(zero.trees.len(), full.trees.len());
5933+
5934+ // Hosted ignores `since` on the shallow path.
5935+ let since = pull_query(&base, &format!("?depth=1&since={}", main[4])).await;
5936+ assert_eq!(pulled_hashes(&since), hex(&main[4..]));
5937+ }
5938+
5939+ /// Hosted parity: a branch-selected shallow clone (`oak clone --shallow
5940+ /// --branch B` sends `depth=1&branch_name=B`) walks from that branch's
5941+ /// head, following the first parent across the fork into its parent.
5942+ #[tokio::test(flavor = "current_thread")]
5943+ async fn pull_depth_with_branch_name_walks_from_that_branch_head() {
5944+ let temp = tempfile::TempDir::new().unwrap();
5945+ let root = temp.path().to_path_buf();
5946+ let (main, _, feature) = seed_history(&root, 3, 2);
5947+ let base = spawn_server(root).await;
5948+
5949+ let one = pull_query(&base, "?depth=1&branch_name=feature").await;
5950+ assert_eq!(pulled_hashes(&one), hex(&feature[1..]));
5951+
5952+ let three = pull_query(&base, "?depth=3&branch_name=feature").await;
5953+ let mut expected = hex(&main[2..]);
5954+ expected.extend(hex(&feature));
5955+ assert_eq!(pulled_hashes(&three), expected);
5956+
5957+ let missing = pull_query(&base, "?depth=1&branch_name=nope").await;
5958+ assert!(missing.commits.is_empty());
5959+ }
57655960 }