Skip to content

取消:请求、传播、确认与终态 ​

定义与边界 ​

取消是阻止或终止后续工作的协议,通常包含提交请求、传播意图、执行器响应、停止确认与最终状态。请求被接受和进程已经停止是不同事实。取消一个等待中的本地 Context 也不证明外部命令或第三方动作已经停止。

业务终态 CANCELED 需要明确完成条件,例如当前尝试停止、后续步骤不会再调度、必要资源已安全释放。已经发生的支付、邮件等副作用可能需要独立补偿,取消本身不会倒流时间。

问题:接口说取消成功,命令仍在运行 ​

API 把状态直接设为 CANCELED,再向离线 Worker 发取消消息。消息没送到,命令继续上传输出。页面既看不见进行中工作,也无法解释晚到结果。

先保存 CANCELING 与可靠取消意图,再由执行器确认,可以让中间状态和恢复依据可见。等待太久时仍需要预算、接管与人工核对政策。

原理:每个角色检查自己的事实 ​

控制端原子保存取消意图,并停止尚未开始的后续调度。传输端可靠投递到对应 Execution/Attempt。执行器校验身份和所有权,向运行句柄请求停止,等待有限时间并记录结果。控制端接受有效停止事实,按合法边推进终态。

反复收到相同取消请求应返回同一过程状态。取消与成功竞争时,按协议决定谁可以推进;旧 Attempt 的停止确认不能取消新 Attempt。结果与资源释放需要幂等保护。

最小例子:取消过程时间线 ​

text
教学过程:
10:00 API 提交 CancellationRequested → CANCELING
10:01 Worker 收到对应 A2 请求 → 发送停止信号
10:02 Worker 观察进程退出 → 保存停止事实与待上报事件
10:03 Server 接受 A2 的确认 → CANCELED,幂等释放占用

如果 10:01 Worker 已失去认领,不能只凭旧内存执行后更新当前状态。外部命令可能需要停止整个进程组,细节取决于执行环境。

逐步推演:三种竞争 ​

排队时取消:取消前尚无外部执行,条件更新阻止新认领。运行中取消:保存意图并等待停止事实。完成与取消同时到达:使用当前状态、版本与协议裁决,不靠最后一次写入获胜。

上传已完成但业务不再接受结果时,可保留隔离输出待清理;不可逆效果已经发生时记录补偿需求。把补偿也做成独立可靠操作,避免取消失败后再丢补偿。

方案比较 ​

立即设终态简单,但可能虚假停止;两阶段取消清晰可恢复,但用户需要理解“取消中”;强制终止能降低等待,却可能破坏未提交文件和外部状态,需要后续核对。

真实案例 ​

TDP 状态模型区分 CANCELING 与 CANCELED,Worker Runtime 是实际执行控制的观察入口。这里给出的时间线是教学设计,具体信号、进程管理和停止超时应继续依据当前执行器实现核对。

已核对的实现 · 本地代码快照

执行状态机及单调进度 backend · ee2fe9c8

server/internal/core/execution/domain/status.go · 第 22–79 行
符号:Transition / SetProgress · 核对日期 2026-10-10
来源与提交版本一致

var executionTransitions = map[ExecutionStatus]map[ExecutionStatus]struct{}{
	ExecutionCreated:   set(ExecutionQueued, ExecutionSucceeded, ExecutionFailed, ExecutionTimedOut, ExecutionCanceling, ExecutionCanceled),
	ExecutionQueued:    set(ExecutionRunning, ExecutionSucceeded, ExecutionFailed, ExecutionTimedOut, ExecutionCanceling, ExecutionCanceled),
	ExecutionRunning:   set(ExecutionSucceeded, ExecutionFailed, ExecutionTimedOut, ExecutionCanceling, ExecutionCanceled),
	ExecutionCanceling: set(ExecutionCanceled, ExecutionFailed, ExecutionTimedOut),
}

// Terminal 判断执行是否已经结束且不会再接受普通状态推进。
func (s ExecutionStatus) Terminal() bool {
	switch s {
	case ExecutionSucceeded, ExecutionFailed, ExecutionTimedOut, ExecutionCanceled:
		return true
	default:
		return false
	}
}

// Transition 按状态机推进执行,并统一维护开始时间、完成时间和版本号。
func (e *Execution) Transition(to ExecutionStatus, at time.Time) error {
	if e.Status == to {
		return nil
	}
	if _, ok := executionTransitions[e.Status][to]; !ok {
		return fmt.Errorf("execution transition %s -> %s is not allowed", e.Status, to)
	}
	if to == ExecutionRunning && e.StartedAt == nil {
		startedAt := at
		e.StartedAt = &startedAt
	}
	if to.Terminal() {
		completedAt := at
		e.CompletedAt = &completedAt
		if to == ExecutionSucceeded {
			e.Progress = 100
		}
	}
	e.Status = to
	e.Version++
	return nil
}

// SetProgress 仅允许运行中的执行单调增加 0 到 100 的进度。
func (e *Execution) SetProgress(progress int16) error {
	if e.Status != ExecutionRunning {
		return fmt.Errorf("cannot update progress while execution is %s", e.Status)
	}
	if progress < e.Progress || progress > 100 {
		return fmt.Errorf("progress must be monotonic and between %d and 100", e.Progress)
	}
	e.Progress = progress
	e.Version++
	return nil
}

// StepStatus 表示工作流步骤从等待依赖到完成的生命周期状态。
type StepStatus string

const (

片段展示核对时的源码;完整文件指纹用于检测后续变化。这里的路径用于定位,不要求手机访问源码仓库。

Worker 的依赖与运行状态 backend · 3069db92

worker/internal/core/execution/application/runtime.go · 第 48–100 行
符号:Runtime · 核对日期 2026-10-10
来源与提交版本一致

// Runtime 是 Worker 的长期运行应用:注册会话、恢复本地状态、消费命令并可靠上报事件。
type Runtime struct {
	registration       Registration
	control            ControlPlane
	commands           CommandStream
	store              LocalStore
	capabilityExecutor CapabilityExecutor
	ids                executionports.IDGenerator
	observer           executionports.Observation
	now                func() time.Time
	retryInitial       time.Duration
	outboxWake         chan struct{}                 // 合并事件发送唤醒,可靠数据始终保存在本地数据库。
	outboxDrain        chan chan error               // 请求发送器完成一轮发送并返回结果。
	admissionMu        sync.Mutex                    // 串行化本地容量检查与尝试接收。
	activeMu           sync.Mutex                    // 保护正在执行的协程及其取消函数。
	active             map[string]context.CancelFunc // 本进程持有的运行中尝试。
	canceled           map[string]bool               // 记录当前会话已收到的取消。
	draining           bool                          // 当前进程的排空状态,持久标记用于重启恢复。
	resourceInventory  func() executiondomain.NodeInventory
	resourceUsage      func(context.Context) executiondomain.ResourceUsage
}

func New(registration Registration, control ControlPlane, commands CommandStream, store LocalStore, capabilityExecutor CapabilityExecutor, ids executionports.IDGenerator, observer executionports.Observation) (*Runtime, error) {
	if registration.InstanceID == "" || registration.Name == "" || registration.NodeID == "" {
		return nil, executiondomain.Wrap(
			executiondomain.Invalid,
			"Worker 注册信息缺少实例、名称或 Node",
			errors.New("worker instance ID, name, and node ID are required"),
		)
	}
	if registration.Inventory.CPU.CapacityMillis < 1 {
		return nil, executiondomain.Wrap(
			executiondomain.Invalid,
			"Worker CPU 资源采集不可用",
			errors.New("worker CPU inventory is required"),
		)
	}
	if control == nil || commands == nil || store == nil || capabilityExecutor == nil || ids == nil || observer == nil {
		return nil, errors.New("control plane, command stream, local store, capability, ID generator, and observer are required")
	}
	return &Runtime{
		registration:       registration,
		control:            control,
		commands:           commands,
		store:              store,
		capabilityExecutor: capabilityExecutor,
		ids:                ids,
		observer:           observer,
		now:                time.Now,
		retryInitial:       time.Second,
		outboxWake:         make(chan struct{}, 1),
		outboxDrain:        make(chan chan error),
		active:             make(map[string]context.CancelFunc),

片段展示核对时的源码;完整文件指纹用于检测后续变化。这里的路径用于定位,不要求手机访问源码仓库。

失败与边界 ​

资源已释放但旧进程仍使用资源,会导致真实超占用。不能仅凭取消意图立即把所有共享资源当空闲。网络分区与未知执行结果需要保守或受控接管政策,并使用 Fencing 或隔离输出来限制旧持有者。

迁移练习与参考答案 ​

练习:取消短信发送任务时,供应商已经接受请求但尚未确认送达,能保证用户收不到短信吗?

参考答案:除非供应商支持且确认取消,否则不能保证。记录取消意图与远端状态,查询或接收后续确认;已发送则保留事实,业务可以停止后续短信但不能抹去已发生效果。页面应表达准确状态。

延伸阅读 ​

结果未知、Fencing 和 Attempt分别解释这条协议的失败边界。

理解原理 · 分析取舍 · 用真实代码检验