# 用法：
#   本文件是库模块，不直接运行。
#   父进程入口：python "src/main.py"
#
# 说明：
#   - 封装“创建/控制/终止/通信”的核心逻辑，UI 只调用这里提供的方法。
#   - 三种通信方式：
#       * pipe：标准 stdin/stdout 管道
#       * direct：相邻 Stage 使用 Unix domain socket（socketpair）点对点直连
#       * indirect：相邻 Stage 的数据先进入 mailboxd，再由 mailboxd 转发到下游
#   - 目标：代码尽量 KISS，同时保证演示稳定（无僵尸、可 stop/cont/term/kill）。

from __future__ import annotations

import os
import signal
import socket
import subprocess
import sys
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional

import procfs

from stage_registry import DATA_TYPE_ANY, StageSpec, get_stage_specs


MODE_PIPE = "pipe"
MODE_DIRECT = "direct"
MODE_INDIRECT = "indirect"
SUPPORTED_MODES = (MODE_PIPE, MODE_DIRECT, MODE_INDIRECT)


@dataclass
class StageInvocation:
    stage_id: str
    argv: list[str] = field(default_factory=list)
    enabled: bool = True


@dataclass
class ManagedProcess:
    name: str
    pid: int
    argv: list[str]
    popen: subprocess.Popen


@dataclass
class PipelineRun:
    mode: str
    invocations: list[StageInvocation]
    started_at: float
    input_path: Path
    output_path: Path
    log_path: Path
    processes: list[ManagedProcess]
    mailbox: Optional[ManagedProcess]
    _log_file: Optional[object]
    _output_thread: Optional[threading.Thread]
    _output_bytes: bytearray
    _output_done: threading.Event

    def is_finished(self) -> bool:
        # 所有进程都退出，且输出已读完。
        all_exited = all(p.popen.poll() is not None for p in self.processes)
        mailbox_exited = True
        if self.mailbox is not None:
            mailbox_exited = self.mailbox.popen.poll() is not None
        return all_exited and mailbox_exited and self._output_done.is_set()

    def _all_processes_exited(self) -> bool:
        all_exited = all(p.popen.poll() is not None for p in self.processes)
        if not all_exited:
            return False
        if self.mailbox is not None and self.mailbox.popen.poll() is None:
            return False
        return True

    def output_text(self) -> str:
        return self._output_bytes.decode("utf-8", errors="replace")

    def poll(self) -> None:
        # 触发 poll 更新 returncode（UI 展示更实时）
        for p in self.processes:
            p.popen.poll()
        if self.mailbox is not None:
            self.mailbox.popen.poll()
        if self.is_finished() and self._log_file is not None:
            try:
                self._log_file.close()
            except Exception:
                pass
            self._log_file = None

    def send_signal_all(self, sig: int) -> None:
        for p in self.processes:
            try:
                os.kill(p.pid, sig)
            except ProcessLookupError:
                pass
        if self.mailbox is not None:
            try:
                os.kill(self.mailbox.pid, sig)
            except ProcessLookupError:
                pass

    def terminate_all(self, timeout_seconds: float = 2.0) -> None:
        """
        终止整条流水线并尽力回收资源（避免僵尸）。
        策略：TERM -> 等待 -> KILL -> wait 回收 -> 关闭管道/日志。
        """
        self.send_signal_all(signal.SIGTERM)

        deadline = time.time() + max(0.0, float(timeout_seconds))
        while time.time() < deadline:
            self.poll()
            if self._all_processes_exited():
                break
            time.sleep(0.05)

        # 若仍存活则强杀
        for p in self.processes:
            if p.popen.poll() is None:
                try:
                    os.kill(p.pid, signal.SIGKILL)
                except ProcessLookupError:
                    pass
        if self.mailbox is not None and self.mailbox.popen.poll() is None:
            try:
                os.kill(self.mailbox.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass

        # 关闭本进程持有的管道端，帮助输出线程/子进程及时结束。
        for p in self.processes:
            for stream in (p.popen.stdin, p.popen.stdout):
                if stream is None:
                    continue
                try:
                    stream.close()
                except Exception:
                    pass

        # wait() 回收（循环多次，尽量不留僵尸）
        popens = [p.popen for p in self.processes]
        if self.mailbox is not None:
            popens.append(self.mailbox.popen)

        for _ in range(20):
            all_done = True
            for popen in popens:
                if popen.poll() is None:
                    all_done = False
                    try:
                        popen.wait(timeout=0.1)
                    except subprocess.TimeoutExpired:
                        pass
            if all_done:
                break

        # 尝试等待输出线程结束（不会无限阻塞）
        if self._output_thread is not None and self._output_thread.is_alive():
            self._output_thread.join(timeout=0.5)
        self._output_done.set()

        if self._log_file is not None:
            try:
                self._log_file.close()
            except Exception:
                pass
            self._log_file = None


def _ensure_flag_value(argv: list[str], flag: str, value: str) -> list[str]:
    """
    确保 argv 中存在 `flag value`；若已存在则覆盖其 value。
    """
    if flag in argv:
        idx = argv.index(flag)
        if idx + 1 < len(argv):
            argv[idx + 1] = value
        else:
            argv.append(value)
        return argv
    argv.extend([flag, value])
    return argv


def _validate_chain(invocations: list[StageInvocation], specs: dict[str, StageSpec]) -> tuple[bool, str]:
    active = [x for x in invocations if x.enabled]
    if not active:
        return False, "流水线为空（没有启用任何 Stage）"

    # 首个 Stage 必须是 source（input_type=None）。
    first = active[0]
    if first.stage_id not in specs:
        return False, f"未知 Stage：{first.stage_id}"
    if specs[first.stage_id].input_type is not None:
        return False, f"首个 Stage 必须是 source（不接受输入），当前：{first.stage_id}"

    current_type = specs[first.stage_id].output_type
    for inv in active[1:]:
        if inv.stage_id not in specs:
            return False, f"未知 Stage：{inv.stage_id}"
        spec = specs[inv.stage_id]
        if spec.input_type not in (DATA_TYPE_ANY, current_type):
            return (
                False,
                f"类型不兼容：{inv.stage_id} 需要 {spec.input_type}，但上游输出为 {current_type}",
            )
        # 允许 debug.delay 这种“* -> *”
        if spec.output_type != DATA_TYPE_ANY:
            current_type = spec.output_type
    return True, "OK"


def validate_chain(invocations: list[StageInvocation]) -> tuple[bool, str]:
    """
    UI/外部调用的校验入口：检查 Stage ID 存在性与数据类型兼容性。
    """
    specs = get_stage_specs()
    return _validate_chain(invocations, specs)


def _build_stage_commands(
    invocations: list[StageInvocation],
    specs: dict[str, StageSpec],
    input_path: Path,
    output_path: Path,
    default_topn: int,
) -> list[tuple[str, list[str]]]:
    commands: list[tuple[str, list[str]]] = []
    for inv in invocations:
        if not inv.enabled:
            continue
        spec = specs[inv.stage_id]
        script_path = str((Path(__file__).resolve().parent / spec.script).resolve())
        argv = list(inv.argv)

        # 父进程注入运行所需参数（保持 Stage 脚本通用性）。
        if inv.stage_id == "source.file":
            argv = _ensure_flag_value(argv, "--path", str(input_path))
        if inv.stage_id == "report.text":
            argv = _ensure_flag_value(argv, "--output", str(output_path))
            if "--topn" not in argv:
                argv.extend(["--topn", str(default_topn)])

        cmd = [sys.executable, script_path, *argv]
        commands.append((inv.stage_id, cmd))
    return commands


def _timestamp_for_filename() -> str:
    # 仅到秒会导致“短时间多次运行”文件名冲突，这里追加纳秒字段以保证唯一性。
    now_ns = time.time_ns()
    sec = now_ns // 1_000_000_000
    nsec = now_ns % 1_000_000_000
    return time.strftime("%Y%m%d_%H%M%S", time.localtime(sec)) + f"_{nsec:09d}"


def make_report_path(outputs_dir: Path) -> Path:
    return outputs_dir / f"report_{_timestamp_for_filename()}.txt"


def make_run_log_path(outputs_dir: Path) -> Path:
    return outputs_dir / f"run_{_timestamp_for_filename()}.log"


def _start_output_reader(stdout_pipe, buffer: bytearray, done: threading.Event) -> threading.Thread:
    def run() -> None:
        try:
            while True:
                chunk = stdout_pipe.read(64 * 1024)
                if not chunk:
                    break
                buffer.extend(chunk)
        finally:
            try:
                stdout_pipe.close()
            except Exception:
                pass
            done.set()

    t = threading.Thread(target=run, name="pipeline-output-reader", daemon=True)
    t.start()
    return t


def start_pipeline(
    invocations: list[StageInvocation],
    mode: str,
    input_path: Path,
    outputs_dir: Path,
    default_topn: int = 20,
) -> tuple[Optional[PipelineRun], str]:
    """
    启动一条流水线。
    返回 (PipelineRun|None, message)。失败时 PipelineRun 为 None。
    """
    if mode not in SUPPORTED_MODES:
        return None, f"不支持的通信方式：{mode}"

    specs = get_stage_specs()
    ok, msg = _validate_chain(invocations, specs)
    if not ok:
        return None, msg

    outputs_dir.mkdir(parents=True, exist_ok=True)
    output_path = make_report_path(outputs_dir)
    log_path = make_run_log_path(outputs_dir)

    started_at = time.time()
    cmd_list = _build_stage_commands(invocations, specs, input_path, output_path, default_topn)
    if not cmd_list:
        return None, "流水线为空（没有启用任何 Stage）"

    # 子进程统一设置：避免 stdout 缓冲导致的“管道卡住”。
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "1"

    # 子进程 stderr 重定向到日志文件，避免打乱交互菜单输出。
    log_file = open(log_path, "a", encoding="utf-8", errors="replace")

    processes: list[ManagedProcess] = []
    mailbox: Optional[ManagedProcess] = None

    output_bytes = bytearray()
    output_done = threading.Event()
    output_thread: Optional[threading.Thread] = None

    sockets_to_close: list[socket.socket] = []

    try:
        if mode == MODE_PIPE:
            prev_stdout = None
            prev_popen = None
            for idx, (stage_id, cmd) in enumerate(cmd_list):
                is_last = idx == (len(cmd_list) - 1)
                stdin = prev_stdout if prev_stdout is not None else subprocess.DEVNULL
                stdout = subprocess.PIPE
                p = subprocess.Popen(
                    cmd,
                    stdin=stdin,
                    stdout=stdout,
                    stderr=log_file,
                    env=env,
                    close_fds=True,
                )
                processes.append(
                    ManagedProcess(name=stage_id, pid=p.pid, argv=cmd, popen=p)
                )
                if prev_stdout is not None:
                    try:
                        prev_stdout.close()
                    except Exception:
                        pass
                prev_popen = p
                prev_stdout = p.stdout
                if is_last and p.stdout is not None:
                    output_thread = _start_output_reader(p.stdout, output_bytes, output_done)

        elif mode == MODE_DIRECT:
            stdin_spec: list[object] = [subprocess.DEVNULL] * len(cmd_list)
            stdout_spec: list[object] = [None] * len(cmd_list)
            stdout_spec[-1] = subprocess.PIPE

            for i in range(len(cmd_list) - 1):
                left, right = socket.socketpair()
                sockets_to_close.extend([left, right])
                stdout_spec[i] = left.fileno()
                stdin_spec[i + 1] = right.fileno()

            for i, (stage_id, cmd) in enumerate(cmd_list):
                p = subprocess.Popen(
                    cmd,
                    stdin=stdin_spec[i],
                    stdout=stdout_spec[i],
                    stderr=log_file,
                    env=env,
                    close_fds=True,
                )
                processes.append(
                    ManagedProcess(name=stage_id, pid=p.pid, argv=cmd, popen=p)
                )

            # 读取最后一个 Stage 的 stdout（pipe），避免阻塞。
            last_stdout = processes[-1].popen.stdout
            if last_stdout is not None:
                output_thread = _start_output_reader(last_stdout, output_bytes, output_done)

        elif mode == MODE_INDIRECT:
            stdin_spec = [subprocess.DEVNULL] * len(cmd_list)
            stdout_spec = [None] * len(cmd_list)
            stdout_spec[-1] = subprocess.PIPE

            mailbox_routes: list[tuple[int, int]] = []
            mailbox_fds: set[int] = set()

            for i in range(len(cmd_list) - 1):
                # Stage_i(stdout) -> mailbox(in_fd)
                stage_out, mailbox_in = socket.socketpair()
                # mailbox(out_fd) -> Stage_{i+1}(stdin)
                mailbox_out, stage_in = socket.socketpair()

                sockets_to_close.extend([stage_out, mailbox_in, mailbox_out, stage_in])

                stdout_spec[i] = stage_out.fileno()
                stdin_spec[i + 1] = stage_in.fileno()

                in_fd = mailbox_in.fileno()
                out_fd = mailbox_out.fileno()
                mailbox_routes.append((in_fd, out_fd))
                mailbox_fds.add(in_fd)
                mailbox_fds.add(out_fd)

            mailbox_script = str((Path(__file__).resolve().parent / "mailboxd.py").resolve())
            mailbox_cmd: list[str] = [sys.executable, mailbox_script]
            for in_fd, out_fd in mailbox_routes:
                mailbox_cmd.extend(["--route", f"{in_fd}:{out_fd}"])

            mailbox_p = subprocess.Popen(
                mailbox_cmd,
                stdin=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL,
                stderr=log_file,
                env=env,
                close_fds=True,
                pass_fds=tuple(sorted(mailbox_fds)),
            )
            mailbox = ManagedProcess(
                name="mailboxd",
                pid=mailbox_p.pid,
                argv=mailbox_cmd,
                popen=mailbox_p,
            )

            for i, (stage_id, cmd) in enumerate(cmd_list):
                p = subprocess.Popen(
                    cmd,
                    stdin=stdin_spec[i],
                    stdout=stdout_spec[i],
                    stderr=log_file,
                    env=env,
                    close_fds=True,
                )
                processes.append(
                    ManagedProcess(name=stage_id, pid=p.pid, argv=cmd, popen=p)
                )

            last_stdout = processes[-1].popen.stdout
            if last_stdout is not None:
                output_thread = _start_output_reader(last_stdout, output_bytes, output_done)

        else:
            return None, f"未实现的通信方式：{mode}"

    except FileNotFoundError as exc:
        # 例如 python 找不到（极少见），或脚本路径错误。
        try:
            log_file.close()
        except Exception:
            pass
        return None, f"启动失败：{exc}"
    except Exception as exc:
        # 任意异常都需要尽力清理子进程，避免遗留。
        for s in sockets_to_close:
            try:
                s.close()
            except Exception:
                pass
        for p in processes:
            try:
                os.kill(p.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
        if mailbox is not None:
            try:
                os.kill(mailbox.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
        try:
            log_file.close()
        except Exception:
            pass
        return None, f"启动异常：{exc}"
    finally:
        # 父进程关闭所有 socket 端，保证 EOF 能正确传播。
        for s in sockets_to_close:
            try:
                s.close()
            except Exception:
                pass

    run = PipelineRun(
        mode=mode,
        invocations=[StageInvocation(x.stage_id, list(x.argv), x.enabled) for x in invocations],
        started_at=started_at,
        input_path=input_path,
        output_path=output_path,
        log_path=log_path,
        processes=processes,
        mailbox=mailbox,
        _log_file=log_file,
        _output_thread=output_thread,
        _output_bytes=output_bytes,
        _output_done=output_done,
    )
    return run, "OK"


@dataclass(frozen=True)
class StepRunPaths:
    run_id: str
    steps_dir: Path
    report_path: Path
    log_path: Path


@dataclass(frozen=True)
class StepStageResult:
    step_index: int
    stage_id: str
    argv: list[str]
    pid: int
    mailbox_pid: Optional[int]
    returncode: int
    started_at: float
    finished_at: float
    output_path: Path
    output_preview: list[str]
    proc_info: Optional[procfs.ProcInfo]


OnStageStarted = Callable[[str, int, Optional[procfs.ProcInfo], Optional[int]], None]
OnStageRunning = Callable[[str, int, Optional[int]], None]


def prepare_step_run(outputs_dir: Path) -> StepRunPaths:
    """
    为“逐 Stage 单步运行”准备输出路径（同一 run_id 下便于归档/展示）。
    """
    outputs_dir.mkdir(parents=True, exist_ok=True)
    run_id = _timestamp_for_filename()
    steps_dir = outputs_dir / f"steps_{run_id}"
    steps_dir.mkdir(parents=True, exist_ok=True)
    report_path = outputs_dir / f"report_{run_id}.txt"
    log_path = outputs_dir / f"run_{run_id}.log"
    return StepRunPaths(run_id=run_id, steps_dir=steps_dir, report_path=report_path, log_path=log_path)


def _safe_name_for_filename(raw: str) -> str:
    out: list[str] = []
    for ch in raw:
        if ch.isalnum() or ch in ("-", "_"):
            out.append(ch)
        else:
            out.append("_")
    name = "".join(out).strip("_")
    return name or "stage"


def make_step_output_path(steps_dir: Path, step_index: int, stage_id: str) -> Path:
    safe_id = _safe_name_for_filename(stage_id)
    return steps_dir / f"{step_index:02d}_{safe_id}.txt"


def _read_preview_lines(path: Path, limit: int) -> list[str]:
    lines: list[str] = []
    if limit <= 0:
        return lines
    try:
        with path.open("r", encoding="utf-8", errors="replace") as f:
            for _ in range(limit):
                raw = f.readline()
                if not raw:
                    break
                lines.append(raw.rstrip("\n"))
    except OSError:
        # 预览失败不应阻断流程（例如权限/编码问题等）。
        return []
    return lines


def _start_pipe_writer(stdin_pipe, input_path: Path) -> None:
    try:
        with input_path.open("rb") as f:
            while True:
                chunk = f.read(64 * 1024)
                if not chunk:
                    break
                try:
                    stdin_pipe.write(chunk)
                    stdin_pipe.flush()
                except BrokenPipeError:
                    return
                except InterruptedError:
                    continue
                except OSError:
                    return
    finally:
        try:
            stdin_pipe.close()
        except Exception:
            pass


def _start_socket_writer(sock: socket.socket, input_path: Path) -> None:
    try:
        with input_path.open("rb") as f:
            while True:
                chunk = f.read(64 * 1024)
                if not chunk:
                    break
                view = memoryview(chunk)
                while view:
                    try:
                        n = os.write(sock.fileno(), view)
                    except BrokenPipeError:
                        return
                    except InterruptedError:
                        continue
                    except OSError:
                        return
                    view = view[n:]
    finally:
        try:
            sock.close()
        except Exception:
            pass


def _start_output_to_file_reader(reader, output_file, done: threading.Event) -> threading.Thread:
    def run() -> None:
        try:
            while True:
                chunk = reader.read(64 * 1024)
                if not chunk:
                    break
                output_file.write(chunk)
        finally:
            try:
                reader.close()
            except Exception:
                pass
            done.set()

    t = threading.Thread(target=run, name="step-output-reader", daemon=True)
    t.start()
    return t


def _start_socket_output_to_file_reader(
    sock: socket.socket, output_file, done: threading.Event
) -> threading.Thread:
    def run() -> None:
        try:
            while True:
                try:
                    chunk = os.read(sock.fileno(), 64 * 1024)
                except InterruptedError:
                    continue
                except OSError:
                    break
                if not chunk:
                    break
                output_file.write(chunk)
        finally:
            try:
                sock.close()
            except Exception:
                pass
            done.set()

    t = threading.Thread(target=run, name="step-socket-output-reader", daemon=True)
    t.start()
    return t


def _try_read_proc_info(pid: int) -> Optional[procfs.ProcInfo]:
    # Stage 很可能很快退出，这里做一次轻量重试，尽量拿到 /proc 快照。
    info = procfs.read_proc_info(pid)
    if info is not None:
        return info
    time.sleep(0.02)
    return procfs.read_proc_info(pid)


def run_stage_step(
    *,
    step_index: int,
    invocation: StageInvocation,
    mode: str,
    input_path: Path,
    stdin_path: Optional[Path],
    output_path: Path,
    report_path: Path,
    log_path: Path,
    default_topn: int,
    preview_lines: int,
    on_started: Optional[OnStageStarted] = None,
    on_running: Optional[OnStageRunning] = None,
) -> tuple[Optional[StepStageResult], str]:
    """
    单步执行一个 Stage（启动子进程 -> 传输输入 -> 等待退出 -> 收集输出/预览）。

    通信方式定义为：父进程 <-> 当前 Stage 子进程（pipe/direct/indirect）。
    """
    if mode not in SUPPORTED_MODES:
        return None, f"不支持的通信方式：{mode}"
    if not invocation.enabled:
        return None, "Stage 未启用"

    specs = get_stage_specs()
    if invocation.stage_id not in specs:
        return None, f"未知 Stage：{invocation.stage_id}"

    spec = specs[invocation.stage_id]
    if spec.input_type is None:
        stdin_path = None
    else:
        if stdin_path is None:
            return None, f"{invocation.stage_id} 需要上游输入，但 stdin_path 为空"
        if not stdin_path.exists() or not stdin_path.is_file():
            return None, f"上游输出不存在或不是文件：{stdin_path}"

    output_path.parent.mkdir(parents=True, exist_ok=True)

    cmd_list = _build_stage_commands([invocation], specs, input_path, report_path, default_topn)
    if not cmd_list:
        return None, "Stage 命令为空"
    stage_id, cmd = cmd_list[0]

    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "1"

    started_at = time.time()
    finished_at: float
    mailbox_pid: Optional[int] = None
    mailbox_p: Optional[subprocess.Popen] = None
    p: Optional[subprocess.Popen] = None
    proc_info: Optional[procfs.ProcInfo] = None
    rc: Optional[int] = None
    sockets_to_close: list[socket.socket] = []
    stdin_thread: Optional[threading.Thread] = None
    stdin_done = threading.Event()

    def _terminate_and_wait(popen: Optional[subprocess.Popen]) -> None:
        if popen is None:
            return
        if popen.poll() is not None:
            return
        try:
            popen.terminate()
        except Exception:
            pass
        try:
            popen.wait(timeout=1.0)
            return
        except subprocess.TimeoutExpired:
            pass
        try:
            popen.kill()
        except Exception:
            pass
        try:
            popen.wait(timeout=1.0)
        except subprocess.TimeoutExpired:
            pass

    def _start_stdin_sender(send_func: Callable[[], None]) -> None:
        nonlocal stdin_thread

        def run() -> None:
            try:
                send_func()
            finally:
                stdin_done.set()

        stdin_thread = threading.Thread(target=run, name="step-stdin-writer", daemon=True)
        stdin_thread.start()

    try:
        with open(log_path, "a", encoding="utf-8", errors="replace") as log_file, open(
            output_path, "wb", buffering=0
        ) as out_file:
            output_done = threading.Event()
            output_thread: Optional[threading.Thread] = None

            if mode == MODE_PIPE:
                stdin_spec = subprocess.DEVNULL if stdin_path is None else subprocess.PIPE
                p = subprocess.Popen(
                    cmd,
                    stdin=stdin_spec,
                    stdout=subprocess.PIPE,
                    stderr=log_file,
                    env=env,
                    close_fds=True,
                )
                proc_info = _try_read_proc_info(p.pid)
                if on_started is not None:
                    on_started(stage_id, p.pid, proc_info, None)

                if p.stdout is None:
                    _terminate_and_wait(p)
                    return None, "Stage stdout 未就绪"
                output_thread = _start_output_to_file_reader(p.stdout, out_file, output_done)

                if stdin_path is not None:
                    assert p.stdin is not None
                    _start_stdin_sender(lambda: _start_pipe_writer(p.stdin, stdin_path))

                if on_running is not None:
                    on_running(stage_id, p.pid, None)

                rc = p.wait()
                output_thread.join()
                stdin_done.wait(timeout=2.0)

            elif mode == MODE_DIRECT:
                stdout_parent, stdout_child = socket.socketpair()
                sockets_to_close.extend([stdout_parent, stdout_child])

                stdin_parent: Optional[socket.socket] = None
                stdin_child: Optional[socket.socket] = None

                try:
                    if stdin_path is None:
                        stdin_spec = subprocess.DEVNULL
                    else:
                        stdin_parent, stdin_child = socket.socketpair()
                        sockets_to_close.extend([stdin_parent, stdin_child])
                        stdin_spec = stdin_child.fileno()

                    p = subprocess.Popen(
                        cmd,
                        stdin=stdin_spec,
                        stdout=stdout_child.fileno(),
                        stderr=log_file,
                        env=env,
                        close_fds=True,
                    )
                finally:
                    # 父进程必须关闭子进程端，确保 EOF 能正确传播。
                    try:
                        stdout_child.close()
                    except Exception:
                        pass
                    if stdin_child is not None:
                        try:
                            stdin_child.close()
                        except Exception:
                            pass

                proc_info = _try_read_proc_info(p.pid)
                if on_started is not None:
                    on_started(stage_id, p.pid, proc_info, None)

                output_thread = _start_socket_output_to_file_reader(stdout_parent, out_file, output_done)
                if stdin_path is not None and stdin_parent is not None:
                    _start_stdin_sender(lambda: _start_socket_writer(stdin_parent, stdin_path))

                if on_running is not None:
                    on_running(stage_id, p.pid, None)

                rc = p.wait()
                output_thread.join()
                stdin_done.wait(timeout=2.0)

            elif mode == MODE_INDIRECT:
                # 输入：parent -> mailboxd -> stage（可选）
                parent_out: Optional[socket.socket] = None
                mailbox_in1: Optional[socket.socket] = None
                mailbox_out1: Optional[socket.socket] = None
                stage_in: Optional[socket.socket] = None

                # 输出：stage -> mailboxd -> parent（必选）
                stage_out: Optional[socket.socket] = None
                mailbox_in2: Optional[socket.socket] = None
                mailbox_out2: Optional[socket.socket] = None
                parent_in: Optional[socket.socket] = None

                mailbox_fds: set[int] = set()
                mailbox_cmd: list[str]

                try:
                    routes: list[tuple[int, int]] = []

                    if stdin_path is not None:
                        parent_out, mailbox_in1 = socket.socketpair()
                        mailbox_out1, stage_in = socket.socketpair()
                        sockets_to_close.extend([parent_out, mailbox_in1, mailbox_out1, stage_in])

                        routes.append((mailbox_in1.fileno(), mailbox_out1.fileno()))
                        mailbox_fds.add(mailbox_in1.fileno())
                        mailbox_fds.add(mailbox_out1.fileno())

                    stage_out, mailbox_in2 = socket.socketpair()
                    mailbox_out2, parent_in = socket.socketpair()
                    sockets_to_close.extend([stage_out, mailbox_in2, mailbox_out2, parent_in])

                    routes.append((mailbox_in2.fileno(), mailbox_out2.fileno()))
                    mailbox_fds.add(mailbox_in2.fileno())
                    mailbox_fds.add(mailbox_out2.fileno())

                    mailbox_script = str((Path(__file__).resolve().parent / "mailboxd.py").resolve())
                    mailbox_cmd = [sys.executable, mailbox_script]
                    for in_fd, out_fd in routes:
                        mailbox_cmd.extend(["--route", f"{in_fd}:{out_fd}"])

                    mailbox_p = subprocess.Popen(
                        mailbox_cmd,
                        stdin=subprocess.DEVNULL,
                        stdout=subprocess.DEVNULL,
                        stderr=log_file,
                        env=env,
                        close_fds=True,
                        pass_fds=tuple(sorted(mailbox_fds)),
                    )
                    mailbox_pid = mailbox_p.pid

                    # stage stdin/stdout
                    stdin_spec = subprocess.DEVNULL if stdin_path is None else stage_in.fileno()  # type: ignore[union-attr]
                    p = subprocess.Popen(
                        cmd,
                        stdin=stdin_spec,
                        stdout=stage_out.fileno(),  # type: ignore[union-attr]
                        stderr=log_file,
                        env=env,
                        close_fds=True,
                    )
                finally:
                    # 父进程关闭“邮箱端”和“子进程端”，避免 EOF 被额外引用阻塞。
                    for s in (mailbox_in1, mailbox_out1, mailbox_in2, mailbox_out2, stage_in, stage_out):
                        if s is None:
                            continue
                        try:
                            s.close()
                        except Exception:
                            pass

                assert p is not None
                proc_info = _try_read_proc_info(p.pid)
                if on_started is not None:
                    on_started(stage_id, p.pid, proc_info, mailbox_pid)

                assert parent_in is not None
                output_thread = _start_socket_output_to_file_reader(parent_in, out_file, output_done)

                if stdin_path is not None and parent_out is not None:
                    _start_stdin_sender(lambda: _start_socket_writer(parent_out, stdin_path))

                if on_running is not None:
                    on_running(stage_id, p.pid, mailbox_pid)

                rc = p.wait()
                output_thread.join()
                stdin_done.wait(timeout=2.0)

                _terminate_and_wait(mailbox_p)

            else:
                return None, f"未实现的通信方式：{mode}"

            finished_at = time.time()

    except Exception as exc:
        _terminate_and_wait(p)
        _terminate_and_wait(mailbox_p)
        for s in sockets_to_close:
            try:
                s.close()
            except Exception:
                pass
        return None, f"单步运行异常：{exc}"
    finally:
        for s in sockets_to_close:
            try:
                s.close()
            except Exception:
                pass

    if rc is None or p is None:
        return None, "单步运行失败：未获取退出码"

    preview = _read_preview_lines(output_path, preview_lines)
    result = StepStageResult(
        step_index=step_index,
        stage_id=stage_id,
        argv=cmd,
        pid=p.pid,
        mailbox_pid=mailbox_pid,
        returncode=rc,
        started_at=started_at,
        finished_at=finished_at,
        output_path=output_path,
        output_preview=preview,
        proc_info=proc_info,
    )
    if rc != 0:
        return result, f"Stage 退出码非 0：{rc}"
    return result, "OK"
