Skip to content

Commit 44e1b09

Browse files
genednaclaude
andcommitted
v0.40.5: ImportRepo atomic detach primitive (FU-16, #27)
- Attach payload gains `op: AttachOp` (attach by default, omitted when serialized, so existing rows and fingerprints are unchanged); a detach row reuses the attach kind with `detach_operation_id`, a domain-separated sha256 of repo_id and canonical path. - B3 detach, inside the attach savepoint: FOR UPDATE on the repository's own git_repo row, a bounded child check that excludes same-identity alias rows (IMPORT_REPO_HAS_CHILDREN otherwise), removal of the mount only when this repository owns it and the path is strictly below import_dir (emptied parents pruned, the import root keeps a .gitkeep whose blob row rides the transaction), a framed `Remove ImportRepo <P>` root commit under the shared root CAS, deletion of import_refs and git_repo, and the in-transaction audit row (import_repo.remove, phase detached) plus the cleanup-ledger row keyed by the queue row id. - tree_ops::remove_import_leaf; has_branch_ref_in_txn replaces the unbounded branch listing in the legacy-mount rule (attach too). - import_repo::detach_import_repo re-checks Done replays and resolves the cleanup id to a ledger row; a #[doc(hidden)] integration-test hook is re-exported as import_repo_ops. No product entry yet (FU-17/FU-20). - trunk-push.md documents `op` and the detach branch. Plan: docs/plan/plan-20260923.md (FU-16; DEFER-FU-25..28). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Eli Ma <eli@patch.sh>
1 parent 22299f1 commit 44e1b09

10 files changed

Lines changed: 1940 additions & 21 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "mega2"
3-
version = "0.40.4"
3+
version = "0.40.5"
44
edition = "2024"
55
# Two [[bin]] targets exist; keep `cargo run -p mega2` unambiguous.
66
default-run = "mega2"

‎docs/plan/plan-20260923.md‎

Lines changed: 27 additions & 9 deletions
Large diffs are not rendered by default.

‎docs/refactoring/trunk-push.md‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,7 @@ C 段移出临界区(硬约束 7)后,文件路径索引变为最终一致
405405
- 空 pack 且 `old_id != new_id`:对象全部已持久化,`n` 按基线距离计算(可 > 0),B3 N 分支据此快进落地。
406406
- merge:`{cl_link}`(CL 状态仍在库中可查,无需快照)。
407407
- attach:`{repo 上下文, 完整命令描述符}`——**分支 create/update/delete 的完整列表**(`import_repo.rs:450-475/550-573` 应用的是完整快照,仅存仓库上下文无法在崩溃后重放分支级变更)。操作标识为**确定性导出**而非调用方令牌:attach 由 receive-pack 自动触发(`protocol/mod.rs:175-216` 构造 `ImportRepo`,`RefCommand` 无请求 id,`import_refs.rs:50-59`;git 重试也无法携带令牌),故 `operation_id = hash(仓库标识 ‖ 规范化命令描述符)`——git 重试发送相同命令序列,导出值自然一致,收养/回放由此闭合。
408+
- **`op`:attach 或 detach**([`plan-20260923.md`](../plan/plan-20260923.md) ADR-FU-09 第 1–3 条,FU-16):载荷的可选字段 `op` 取 `attach`(缺省;FU-16 之前写入的行都没有该字段,反序列化为 `attach`,attach 行序列化时也省略它,与既有行逐字节一致)或 `detach`。detach 行复用 `kind = attach`,载荷只含 `{repo_id, repo_path, commands: [], op: "detach"}`,操作标识为域分离的 `sha256("import_repo.detach\0" ‖ repo_id ‖ "\0" ‖ 规范路径)`,与任何 attach 标识不同;同一仓库重复 detach 按 `(kind, path, operation_id)` 回放 `Done`,重新导入得到新 `repo_id`、因而是新标识。
408409

409410
执行逻辑仍由调用方在 B3 内按 kind 分派(ADR-TP-04 的同步模型);载荷的持久化使崩溃后的两种恢复路径成为可能:行仍活跃(`Queued/Running`)时重试**收养**(1.11);行已被 reaper 终态化(`Failed`,无继任)时重试**以原行持久化载荷新建队列行**——描述符完全可执行,无需原连接。这是 ADR-TP-04「同步阻塞、真实结果」的直接推论。
410411

@@ -807,7 +808,8 @@ B3. 执行轮次(单事务;B3 首句是 fencing,见下)
807808
808809
kind = attach:
809810
-- operation_id 为内容寻址指纹(hash(仓库标识 ‖ 命令描述符))。
810-
-- 仅含分支命令的 attach 到达本分支(纯删除式 attach 不入队)。
811+
-- **`op = attach`(缺省)**:分支命令批到达本分支;只含删除的批同样入队、只做 ref CAS
812+
-- (FU-13 起,plan-20260923 ADR-FU-08 第 1 条)。
811813
-- **目标路径、其严格非根祖先、或其任何已物化后代 → 拒绝**:
812814
-- attach 只更新根 ref 与对象,不更新 `main@P`、祖先 main 行、
813815
-- 也不推进/墓碑化后代 main 行(`attach_to_monorepo_parent_in_txn`
@@ -823,6 +825,19 @@ B3. 执行轮次(单事务;B3 首句是 fencing,见下)
823825
-- 报错可诊断:「目标路径或其祖先已物化,内容变更请经 CL 管线
824826
-- (review)或先解除物化」。目标与严格非根祖先全程无 main 行才是
825827
-- attach 的正常前提(reaper 的 I3 语义按此定义,1.6)
828+
-- **`op = detach`(FU-16,ADR-FU-09 第 2、3 条)**:SAVEPOINT 内先
829+
-- `SELECT … FROM git_repo WHERE id = $1 FOR UPDATE` 锁住仓库自身行,
830+
-- 行不存在或其规范路径不等于载荷路径 → 无写 `Done`;再查子仓
831+
-- (`repo_path LIKE escape_like(P) || '/%'`,排除规范形式等于 P 的
832+
-- 行,ADR-FU-10 第 3 条),有 → `IMPORT_REPO_HAS_CHILDREN` 终态
833+
-- `Failed`、无写;叶子属本仓库(有挂载来源记录,或 `.gitkeep`-only
834+
-- 且仓库有分支)时从根树移除叶子、剪掉 `import_dir` 之下因此变空的
835+
-- 父目录(`import_dir` 本身变空时留 `.gitkeep`),合成
836+
-- `Remove ImportRepo <P>` 根 commit 并做同一根 CAS;普通目录、文件
837+
-- 或缺失的叶子不动根树;随后删 `import_refs` 与 `git_repo` 行、同事务
838+
-- 写 `import_repo.remove` / `phase: "detached"` 审计与 `state =
839+
-- detached` 清理台账行(主键 = 本队列行 id)。对象行留给锁外清扫
840+
-- (FU-17)。任一步出错整轮回滚、行终态化 `Failed`。
826841
-- 准备(根快照读取、树拼装、根 commit 合成)必须在锁内、
827842
-- 即本分支内进行:队列等待期间根可能已被前序轮次推进,
828843
-- 入队时预计算的快照一律作废(1.9)

‎src/ceres/api_service/tree_ops.rs‎

Lines changed: 138 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,57 @@ pub fn is_gitkeep_only(tree: &Tree) -> bool {
111111
)
112112
}
113113

114+
/// New trees for removing an ImportRepo leaf (plan-20260923 ADR-FU-09 item 2).
115+
///
116+
/// `chain` runs from the root tree down to the leaf's parent, and `names[i]`
117+
/// is the entry of `chain[i]` that leads one level down (the last one is the
118+
/// leaf). Directories strictly below `chain[floor]`, the import root, that
119+
/// become empty are removed as well; the import root itself keeps a
120+
/// `.gitkeep` instead of becoming empty. Returns the new trees, root last,
121+
/// and the `.gitkeep` blob the caller must store when one was added.
122+
pub fn remove_import_leaf(
123+
chain: &[Tree],
124+
names: &[&str],
125+
floor: usize,
126+
) -> Result<(Vec<Tree>, Option<Blob>), MegaError> {
127+
if chain.is_empty() || chain.len() != names.len() || floor >= chain.len() {
128+
return Err(MegaError::Other("invalid ImportRepo leaf chain".into()));
129+
}
130+
let mut trees = Vec::with_capacity(chain.len());
131+
let mut gitkeep = None;
132+
let mut child = None;
133+
for (idx, (tree, name)) in chain.iter().zip(names).enumerate().rev() {
134+
let mut items = tree.tree_items.clone();
135+
let pos = items
136+
.iter()
137+
.position(|item| item.name == *name)
138+
.ok_or_else(|| MegaError::Other(format!("tree entry {name:?} not found")))?;
139+
match child {
140+
Some(id) => items[pos].id = id,
141+
None => {
142+
items.remove(pos);
143+
}
144+
}
145+
if items.is_empty() {
146+
if idx > floor {
147+
child = None;
148+
continue;
149+
}
150+
let blob = generate_git_keep_with_timestamp();
151+
items.push(TreeItem {
152+
mode: TreeItemMode::Blob,
153+
id: blob.id,
154+
name: String::from(".gitkeep"),
155+
});
156+
gitkeep = Some(blob);
157+
}
158+
let tree = Tree::from_tree_items(items).map_err(|e| MegaError::Other(e.to_string()))?;
159+
child = Some(tree.id);
160+
trees.push(tree);
161+
}
162+
Ok((trees, gitkeep))
163+
}
164+
114165
/// Searches for a tree in the Git repository by its path, creating intermediate trees if necessary,
115166
/// and returns the trees involved in the update process.
116167
///
@@ -509,7 +560,7 @@ mod tests {
509560

510561
use git_internal::internal::object::tree::{TreeItem, TreeItemMode};
511562

512-
use super::{search_and_create_tree, search_tree_for_update_or_create};
563+
use super::{remove_import_leaf, search_and_create_tree, search_tree_for_update_or_create};
513564
use crate::{
514565
ceres::api_service::{
515566
cache::GitObjectCache,
@@ -525,6 +576,92 @@ mod tests {
525576
},
526577
};
527578

579+
fn dir(items: Vec<(&str, git_internal::internal::object::tree::Tree)>) -> super::Tree {
580+
super::Tree::from_tree_items(
581+
items
582+
.into_iter()
583+
.map(|(name, tree)| TreeItem {
584+
mode: TreeItemMode::Tree,
585+
id: tree.id,
586+
name: name.to_owned(),
587+
})
588+
.collect(),
589+
)
590+
.unwrap()
591+
}
592+
593+
fn file(name: &str) -> super::Tree {
594+
let blob = generate_git_keep_with_timestamp();
595+
super::Tree::from_tree_items(vec![TreeItem {
596+
mode: TreeItemMode::Blob,
597+
id: blob.id,
598+
name: name.to_owned(),
599+
}])
600+
.unwrap()
601+
}
602+
603+
#[test]
604+
fn fu16_remove_import_leaf_prunes_below_the_import_root() {
605+
// /third-party/org/repo with a sibling /project: removing repo empties
606+
// org (pruned) and then /third-party, which keeps a `.gitkeep`.
607+
let repo = file("README");
608+
let org = dir(vec![("repo", repo)]);
609+
let third_party = dir(vec![("org", org.clone())]);
610+
let root = dir(vec![
611+
("project", file("main.rs")),
612+
("third-party", third_party.clone()),
613+
]);
614+
let (trees, gitkeep) = remove_import_leaf(
615+
&[root.clone(), third_party.clone(), org.clone()],
616+
&["third-party", "org", "repo"],
617+
1,
618+
)
619+
.unwrap();
620+
let gitkeep = gitkeep.expect("the emptied import root keeps a .gitkeep");
621+
assert_eq!(trees.len(), 2, "org is pruned, not rewritten");
622+
assert_eq!(trees[0].tree_items.len(), 1);
623+
assert_eq!(trees[0].tree_items[0].name, ".gitkeep");
624+
assert_eq!(trees[0].tree_items[0].id, gitkeep.id);
625+
let new_root = trees.last().unwrap();
626+
assert_eq!(new_root.tree_items.len(), 2);
627+
let project = new_root
628+
.tree_items
629+
.iter()
630+
.find(|i| i.name == "project")
631+
.unwrap();
632+
assert_eq!(project.id, root.tree_items[0].id, "siblings are kept");
633+
assert_eq!(
634+
new_root
635+
.tree_items
636+
.iter()
637+
.find(|i| i.name == "third-party")
638+
.unwrap()
639+
.id,
640+
trees[0].id
641+
);
642+
643+
// A sibling under org keeps org, and no `.gitkeep` is added.
644+
let org = dir(vec![("repo", file("README")), ("other", file("LICENSE"))]);
645+
let third_party = dir(vec![("org", org.clone())]);
646+
let root = dir(vec![("third-party", third_party.clone())]);
647+
let (trees, gitkeep) = remove_import_leaf(
648+
&[root, third_party, org],
649+
&["third-party", "org", "repo"],
650+
1,
651+
)
652+
.unwrap();
653+
assert!(gitkeep.is_none());
654+
assert_eq!(trees.len(), 3);
655+
assert_eq!(
656+
trees[0]
657+
.tree_items
658+
.iter()
659+
.map(|i| i.name.as_str())
660+
.collect::<Vec<_>>(),
661+
["other"]
662+
);
663+
}
664+
528665
/// Regression coverage for mega@f5d22b9 (#2152): `search_and_create_tree`
529666
/// returns the placeholder `.gitkeep` blob so callers can persist it together
530667
/// with the new trees; the leaf tree must reference exactly that blob.

0 commit comments

Comments
 (0)