diff --git a/CHANGELOG.md b/CHANGELOG.md index dd88c58..c3dcb49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- 修复 `dyro line merge --into --push` 提前报完成和漏记远端锚点的问题;逐仓记录推送结果,失败可重试,中断后可对账并提示手动重推。0.7.17 已完成的操作不会补修;请重跑同一条 `dyro line merge --into --push`,再次推送并记录锚点。 - `dyro dispatch backends` 在 Grok CLI 只配置了 API key、`grok models` 未打印会话登录句时,也会识别为已认证;CLI 明确表示未登录时仍视为未认证。 - 修复 macOS 上 `/tmp` 与 `/private/tmp`(以及 `/var` 与 `/private/var`)路径写法不一致时,技能清单被误判过期、进程内状态锁重入死锁,以及蓝图加入与全局主目录路径对不齐的问题;旧版清单中的原写法仍可识别。 diff --git a/src/dyro/line_ops.py b/src/dyro/line_ops.py index 3c078c9..84044ff 100644 --- a/src/dyro/line_ops.py +++ b/src/dyro/line_ops.py @@ -236,7 +236,7 @@ def update_repo_phase( def finish_op(config: Config, op_id: str, *, phase: str) -> None: - """Close only reconciled operations; unknown/pending keeps blocking.""" + """Close reconciled operations, allowing report-only recovery of pushes.""" if phase not in TERMINAL_PHASES: raise ValidationError("操作终态必须是 completed 或 aborted") op = load_op(config, op_id) @@ -245,9 +245,16 @@ def finish_op(config: Config, op_id: str, *, phase: str) -> None: raise DyroError(f"操作已以 {op['phase']} 结束:{op_id}") return for repo_id, repo in op["repositories"].items(): + # Recovery may acknowledge an unknown idempotent push after the merge + # is reconciled. A missing push result must still keep the op open. if repo["phase"] == "unknown" or repo["outcome"] in {"", "pending", "unknown"} or any( - "result" not in step or step["result"].get("outcome") in {None, "", "pending", "unknown"} - for step in repo["steps"].values() + "result" not in step or step["result"].get("outcome") in {None, "", "pending"} + or (step["result"].get("outcome") == "unknown" and not ( + action == "push" and op["kind"] == "merge" + and op["effective_options"].get("push") + and repo["outcome"] in {"committed", "already_included"} + )) + for action, step in repo["steps"].items() ): raise DyroError(f"仓库尚未完成对账,不能结束操作:{op_id}/{repo_id}") op["phase"] = phase diff --git a/src/dyro/workspace.py b/src/dyro/workspace.py index b57d0c6..1cb2145 100644 --- a/src/dyro/workspace.py +++ b/src/dyro/workspace.py @@ -5,6 +5,7 @@ import os from pathlib import Path import re +import shlex import shutil import stat from typing import Iterable, Mapping @@ -1653,6 +1654,12 @@ def _ledger_successful_merge_repos( if op["phase"] not in TERMINAL_PHASES: update_repo_phase(config, op_id, repo_id, phase="unknown", outcome="unknown") raise DyroError(f"{repo_id}: already_included 核验失败;请 --recover 对账") + repo_extra = extra + if op["effective_options"].get("push"): + push_step = repo["steps"].get("push", {}) + repo_extra = dict( + extra or {}, pushed=push_step.get("result", {}).get("outcome") == "pushed" + ) _write_merge_ledger_row( config, subject_id=subject_id, @@ -1664,7 +1671,7 @@ def _ledger_successful_merge_repos( previous_head=original_head, result_head=result_head, outcome=outcome, - extra=extra, + extra=repo_extra, ) @@ -1843,7 +1850,7 @@ def _run_journaled_line_merge( source_id=source.id, plans=plans, target_storage=storage, - effective_options=effective_options, + effective_options=dict(effective_options, push=True) if push else effective_options, event_kind=event_kind, event_actor=event_actor, event_subject=event_subject, @@ -1874,29 +1881,60 @@ def _run_journaled_line_merge( ledger_extra or {}, pushed=push, changeset_id=_record_line_merge_changeset(config, target, repos), ) - _ledger_successful_merge_repos( - config, - op=op, - subject_id=ledger_subject_id, - branches=branches, - extra=ledger_extra, - ) - finish_op(config, op_id, phase="completed") if push: pushed: list[str] = [] - for plan in plans: + for index, plan in enumerate(plans): + push_head = _head_sha(plan.target) + record_repo_intent( + config, op_id, plan.repository, "push", + original_head=plan.original_head, target_sha=push_head, + branch=branches[plan.repository], remote="origin", + ) result = git(plan.target, "push", "origin", branches[plan.repository]) + if result.code == 0: + target = record_remote_anchor(config, target, plan.repository, plan.target) + record_repo_result( + config, op_id, plan.repository, "push", + outcome="pushed" if result.code == 0 else "push_failed", + new_tip=push_head if result.code == 0 else "", + error=result.stdout.strip() if result.code != 0 else "", + ) if result.code != 0: + for remaining in plans[index + 1:]: + record_repo_intent( + config, op_id, remaining.repository, "push", + original_head=remaining.original_head, target_sha=_head_sha(remaining.target), + branch=branches[remaining.repository], remote="origin", + ) + record_repo_result( + config, op_id, remaining.repository, "push", outcome="not_attempted", + ) _line_ledger( config, source.id, "push_failed", repository=plan.repository, pushed_repositories=pushed, error=result.stdout.strip(), - **dict(ledger_extra or {}), + **dict(ledger_extra or {}, pushed=False), + ) + _ledger_successful_merge_repos( + config, + op=load_op(config, op_id), + subject_id=ledger_subject_id, + branches=branches, + extra=ledger_extra, ) + finish_op(config, op_id, phase="completed") raise DyroError( f"推送 {plan.repository} 失败;本地合并已保留,已推送仓库:" f"{', '.join(pushed) or '-'}\n{result.stdout.strip()}" ) pushed.append(plan.repository) + _ledger_successful_merge_repos( + config, + op=load_op(config, op_id) if push else op, + subject_id=ledger_subject_id, + branches=branches, + extra=ledger_extra, + ) + finish_op(config, op_id, phase="completed") _append_merge_event_if_needed( config, op_id=op_id, @@ -2292,6 +2330,25 @@ def recover_line_merge( report = [f"对账操作 {op_id}(kind={op['kind']})"] outcomes: dict[str, str] = {} for repo_id in op["repos_ordered"]: + repo = op["repositories"][repo_id] + push_step = repo["steps"].get("push") + if push_step is not None or frozen.get("push"): + push_outcome = push_step.get("result", {}).get("outcome", "unknown") if push_step else "not_started" + if push_step is not None and "result" not in push_step and not terminal: + # The merge is reconciled separately; an idempotent push can be + # left explicitly unknown and retried manually after closing. + record_repo_result(config, op_id, repo_id, "push", outcome="unknown") + report.append(f"{repo_id}: push {push_outcome}") + if push_outcome != "pushed": + report.append( + " 手动:重新执行 dyro line merge " + f"{shlex.quote(str(op['manifest_snapshot']['source']))} --into " + f"{shlex.quote(str(op['manifest_snapshot']['target']))} --push" + ) + if push_step is not None: + path = shlex.quote(str(repo["snapshot"]["path"])) + branch = shlex.quote(str(push_step["intent"]["branch"])) + report.append(f" 手动:git -C {path} push origin {branch}") outcomes[repo_id] = ( op["repositories"][repo_id]["outcome"] if terminal else _reconcile_merge_repo(config, op, repo_id, report=report) diff --git a/tests/test_line_merge_cross.py b/tests/test_line_merge_cross.py index a916c8e..7c11167 100644 --- a/tests/test_line_merge_cross.py +++ b/tests/test_line_merge_cross.py @@ -4,6 +4,7 @@ import io import json from contextlib import contextmanager, redirect_stdout +from dataclasses import replace from pathlib import Path import subprocess from unittest.mock import patch @@ -45,8 +46,8 @@ def _commit_text(worktree: Path, filename: str, content: str, message: str) -> s class CrossLineMergeTests(WorkspaceCase): - def _enable_web(self): - web = self.root / "repositories/web" + def _enable_web(self, repo_id="web"): + web = self.root / f"repositories/{repo_id}" web.mkdir(parents=True) shell("git", "init", "-b", "main", cwd=web) shell("git", "config", "user.name", "Test User", cwd=web) @@ -57,7 +58,7 @@ def _enable_web(self): config_path = self.root / "dyro.toml" config_path.write_text( config_path.read_text(encoding="utf-8") - + '\n[repositories.web]\npath = "repositories/web"\nmount = "clients/web"\n', + + f'\n[repositories.{repo_id}]\npath = "repositories/{repo_id}"\nmount = "clients/{repo_id}"\n', encoding="utf-8", ) return load(self.root), web @@ -752,6 +753,165 @@ def crash_after_probe(plans): events = read_events_fail_closed(config) self.assertTrue(any(e["kind"] == "merge" and e["facts"].get("op_id") for e in events)) + def _push_parent_child(self, *, three_repos=False): + config, _ = self._enable_web() + if three_repos: + config, _ = self._enable_web("worker") + for repo in config.repositories: + publish_origin_branch(self.root / config.repositories[repo].path, "feat/alpha") + parent = create_line(config, line_id="alpha", branch="feat/alpha", base="main") + child = workspace.spawn_line(config, parent.id, "child") + for repo in child.repositories: + _commit_text(line_repository_path(config, child, repo), "child.txt", repo, "child") + return replace(config, policy=replace(config.policy, allow_push=True)), parent, child + + def test_into_push_journals_before_push_and_completes_after_anchors(self) -> None: + config, parent, child = self._push_parent_child() + original_git = workspace.git + original_finish = workspace.finish_op + pushed = [] + + def observe_push(repo, *args, **kwargs): + if args == ("push", "origin", parent.branch): + op = line_ops.find_unfinished_op(config, parent.id) + self.assertIsNotNone(op) + repo_id = next(r for r in parent.repositories + if line_repository_path(config, parent, r) == repo) + step = op["repositories"][repo_id]["steps"]["push"] + self.assertEqual(step["intent"]["target_sha"], workspace._head_sha(repo)) + self.assertNotIn("result", step) + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), set(pushed)) + self.assertFalse(config.ledger_file.exists() and '"pushed": true' in config.ledger_file.read_text()) + pushed.append(repo_id) + return original_git(repo, *args, **kwargs) + + def observe_finish(config, op_id, *, phase): + op = line_ops.load_op(config, op_id) + self.assertEqual(pushed, ["api", "web"]) + for repo_id in pushed: + self.assertEqual(op["repositories"][repo_id]["steps"]["push"]["result"]["outcome"], "pushed") + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), set(pushed)) + return original_finish(config, op_id, phase=phase) + + with patch.object(workspace, "git", side_effect=observe_push), \ + patch.object(workspace, "finish_op", side_effect=observe_finish): + workspace.merge_line(config, child.id, parent.id, push=True) + op_path = next((self.root / ".dyro/ops").glob("*.json")) + op = line_ops.load_op(config, op_path.stem) + self.assertEqual(op["phase"], "completed") + anchors = workspace.get_line(config, parent.id).remote_anchors + self.assertEqual(anchors, {r: workspace._head_sha(line_repository_path(config, parent, r)) + for r in parent.repositories}) + self.assertIn("schema_version = 4", (config.lines_state_dir / "alpha.toml").read_text()) + rows = [json.loads(row) for row in config.ledger_file.read_text().splitlines()] + self.assertEqual({r["repository"] for r in rows if r.get("pushed")}, {"api", "web"}) + events = read_events_fail_closed(config) + self.assertEqual(len([e for e in events if e["facts"].get("op_id") == op["op_id"]]), 1) + + def test_into_push_failure_keeps_anchor_and_can_rerun(self) -> None: + config, parent, child = self._push_parent_child(three_repos=True) + original_git = workspace.git + + def fail_second_push(repo, *args, **kwargs): + if args == ("push", "origin", parent.branch): + self.assertNotEqual(repo, line_repository_path(config, parent, "worker")) + if repo == line_repository_path(config, parent, "web") and args == ("push", "origin", parent.branch): + return Result(("git", *args), 1, "rejected") + return original_git(repo, *args, **kwargs) + + with patch.object(workspace, "git", side_effect=fail_second_push): + with self.assertRaisesRegex(DyroError, "推送 web 失败;本地合并已保留,已推送仓库:api\nrejected"): + workspace.merge_line(config, child.id, parent.id, push=True) + op_path = next((self.root / ".dyro/ops").glob("*.json")) + op = line_ops.load_op(config, op_path.stem) + self.assertEqual(op["phase"], "completed") + self.assertIsNone(line_ops.find_unfinished_op(config, parent.id)) + self.assertEqual(op["repositories"]["api"]["steps"]["push"]["result"]["outcome"], "pushed") + self.assertEqual(op["repositories"]["web"]["steps"]["push"]["result"]["outcome"], "push_failed") + worker_step = op["repositories"]["worker"]["steps"]["push"] + self.assertEqual(worker_step["intent"]["branch"], parent.branch) + self.assertEqual(worker_step["intent"]["target_sha"], workspace._head_sha(line_repository_path(config, parent, "worker"))) + self.assertEqual(worker_step["result"]["outcome"], "not_attempted") + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), {"api"}) + rows = [json.loads(row) for row in config.ledger_file.read_text().splitlines()] + success_rows = [r for r in rows if r["phase"] == "line_merge" and r.get("op_id") == op["op_id"]] + self.assertEqual(len(success_rows), 3) + self.assertEqual({r["repository"]: r["pushed"] for r in success_rows}, + {"api": True, "web": False, "worker": False}) + self.assertEqual({r["outcome"] for r in success_rows}, {"committed"}) + self.assertEqual([r["pushed_repositories"] for r in rows if r["phase"] == "push_failed"], [["api"]]) + self.assertFalse(any(e["facts"].get("op_id") == op["op_id"] for e in read_events_fail_closed(config))) + workspace.merge_line(config, child.id, parent.id, push=True) + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), {"api", "web", "worker"}) + retry = next(line_ops.load_op(config, p.stem) for p in op_path.parent.glob("*.json") if p != op_path) + self.assertEqual(retry["phase"], "completed") + self.assertEqual({r["outcome"] for r in retry["repositories"].values()}, {"already_included"}) + + def _assert_into_push_crash_recovery(self, *, after_push: bool, after_anchor: bool = False) -> None: + config, parent, child = self._push_parent_child() + original_git = workspace.git + original_anchor = workspace.record_remote_anchor + + def crash_second_push(repo, *args, **kwargs): + if not after_anchor and repo == line_repository_path(config, parent, "web") and args == ("push", "origin", parent.branch): + if after_push: + self.assertEqual(original_git(repo, *args, **kwargs).code, 0) + raise SystemExit("power loss during push") + return original_git(repo, *args, **kwargs) + + def crash_second_anchor(config, line, repo_id, path): + updated = original_anchor(config, line, repo_id, path) + if after_anchor and repo_id == "web": + raise SystemExit("power loss after anchor") + return updated + + with patch.object(workspace, "git", side_effect=crash_second_push), \ + patch.object(workspace, "record_remote_anchor", side_effect=crash_second_anchor): + with self.assertRaises(SystemExit): + workspace.merge_line(config, child.id, parent.id, push=True) + op = line_ops.find_unfinished_op(config, parent.id) + self.assertIsNotNone(op) + self.assertNotIn("result", op["repositories"]["web"]["steps"]["push"]) + with self.assertRaisesRegex(DyroError, "未完成操作"): + workspace.merge_line(config, child.id, parent.id, push=True) + expected_anchors = {"api", "web"} if after_anchor else {"api"} + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), expected_anchors) + manifest_before = (config.lines_state_dir / "alpha.toml").read_bytes() + + def read_only_git(repo, *args, **kwargs): + self.assertIn(args[0], {"rev-parse", "merge-base"}) + return original_git(repo, *args, **kwargs) + + output = io.StringIO() + with patch.object(workspace, "git", side_effect=read_only_git), \ + patch.object(workspace, "record_remote_anchor", side_effect=AssertionError("recover wrote anchor")), \ + redirect_stdout(output): + recovered = recover_line_merge(config, parent.id, op_id=op["op_id"]) + self.assertEqual(set(recovered.outcomes.values()), {"committed"}) + self.assertIn("web: push unknown", output.getvalue()) + self.assertIn(f"dyro line merge {child.id} --into {parent.id} --push", output.getvalue()) + self.assertIn(f"git -C {line_repository_path(config, parent, 'web')} push origin {parent.branch}", output.getvalue()) + self.assertIsNone(line_ops.find_unfinished_op(config, parent.id)) + closed = line_ops.load_op(config, op["op_id"]) + self.assertEqual(closed["phase"], "completed") + self.assertEqual(closed["repositories"]["web"]["steps"]["push"]["result"]["outcome"], "unknown") + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), expected_anchors) + self.assertEqual((config.lines_state_dir / "alpha.toml").read_bytes(), manifest_before) + rows = [json.loads(row) for row in config.ledger_file.read_text().splitlines()] + self.assertEqual({r["repository"]: r["pushed"] for r in rows if r.get("op_id") == op["op_id"]}, + {"api": True, "web": False}) + workspace.merge_line(config, child.id, parent.id, push=True) + self.assertEqual(set(workspace.get_line(config, parent.id).remote_anchors), {"api", "web"}) + + def test_into_push_intent_without_result_recovers_without_git_write(self) -> None: + self._assert_into_push_crash_recovery(after_push=False) + + def test_into_push_death_after_git_success_still_reports_unknown(self) -> None: + self._assert_into_push_crash_recovery(after_push=True) + + def test_into_push_death_after_anchor_still_reports_unknown(self) -> None: + self._assert_into_push_crash_recovery(after_push=True, after_anchor=True) + def test_merge_into_base_has_no_allow_partial_option_or_help(self) -> None: from dyro.cli import build_parser diff --git a/tests/test_line_ops.py b/tests/test_line_ops.py index e2fca9a..a088af7 100644 --- a/tests/test_line_ops.py +++ b/tests/test_line_ops.py @@ -161,6 +161,53 @@ def test_confirmed_result_cannot_be_overwritten(self) -> None: line_ops.record_repo_result(self.config, op_id, "api", "save", outcome=replacement, new_tip="changed") self.assertEqual(line_ops.op_path(self.config, op_id).read_bytes(), before) + def test_only_reconciled_merge_can_close_acknowledged_unknown_push(self) -> None: + for kind, requested, outcome, can_close in ( + ("merge", True, "committed", True), + ("merge", True, "already_included", True), + ("merge", True, "unknown", False), + ("merge", False, "committed", False), + ("retire", True, "committed", False), + ): + with self.subTest(kind=kind, requested=requested, outcome=outcome): + op_id = self._create_op(kind=kind, effective_options={"push": requested})["op_id"] + self._finish_repos(op_id, outcome=outcome) + line_ops.record_repo_intent( + self.config, op_id, "api", "merge", original_head="old", target_sha="new" + ) + line_ops.record_repo_result(self.config, op_id, "api", "merge", outcome="committed", new_tip="new") + line_ops.record_repo_intent( + self.config, op_id, "api", "push", original_head="old", target_sha="new" + ) + with self.assertRaisesRegex(DyroError, "对账"): + line_ops.finish_op(self.config, op_id, phase="completed") + line_ops.record_repo_result(self.config, op_id, "api", "push", outcome="unknown") + if can_close: + line_ops.finish_op(self.config, op_id, phase="completed") + else: + with self.assertRaisesRegex(DyroError, "对账"): + line_ops.finish_op(self.config, op_id, phase="completed") + + def test_unknown_push_does_not_allow_unreconciled_merge_to_close(self) -> None: + for merge_outcome in (None, "unknown"): + with self.subTest(merge_outcome=merge_outcome): + op_id = self._create_op(kind="merge", effective_options={"push": True})["op_id"] + self._finish_repos(op_id, outcome="committed") + line_ops.record_repo_intent( + self.config, op_id, "api", "push", original_head="old", target_sha="new" + ) + line_ops.record_repo_result(self.config, op_id, "api", "push", outcome="unknown") + line_ops.record_repo_intent( + self.config, op_id, "api", "merge", original_head="old", target_sha="new" + ) + if merge_outcome is not None: + line_ops.record_repo_result(self.config, op_id, "api", "merge", outcome=merge_outcome) + before = line_ops.op_path(self.config, op_id).read_bytes() + for phase in ("completed", "aborted"): + with self.assertRaisesRegex(DyroError, "对账"): + line_ops.finish_op(self.config, op_id, phase=phase) + self.assertEqual(line_ops.op_path(self.config, op_id).read_bytes(), before) + def test_unfinished_selection_and_block_include_subject_and_recovery(self) -> None: self.assertIsNone(line_ops.find_unfinished_op(self.config, "alpha")) first = self._create_op(op_id="first")