Repository navigation
feat(scheduler): add structured script payloads, persistent state, concurrency cap, backoff, and dry-run - #7264
Conversation
…ncurrency cap, backoff, and dry-run
M4n5ter
left a comment
There was a problem hiding this comment.
English
Overall the architecture and test coverage here are clean and well-scoped — keeping persisted state in TaskPlan without new migrations, preserving prefix-cache determinism (append-only [Trigger context], sorted data, static tool schema), using ReadyIndex::ready_ids for oldest-due fairness, and moving Tail to VecDeque are all solid choices. I also ran the unit suites plus producer_reopen and upgrade_compat on Linux, and verified the 64 KiB MAKA_AUTOMATION_STATE path on Windows 11.
A few concrete issues and cleanups worth addressing before merge:
Issues to fix
-
Unify
test_scriptundermodeand avoid emitting a boolean JSON Schema ("state": true) (plugins/agent/native/src/owner/scheduler/tools.rs:28-77)- Adding
#[serde(untagged)] Script(ScriptAction)(withtag = "action") inside#[serde(tag = "mode")] enum Inputcauses Serde to discard variant-specific errors across allScheduledTaskvariants (create,list,pause,resume,delete, etc.). For example,{"request":{"mode":"create","title":"t"}}or{"request":{"mode":"list","extra":1}}now returns the opaque"data did not match any variant of untagged enum Input"instead of"missing field intentBody"/"unknown field extra", which hurts model self-correction on a 10-field tool schema. state: Option<Value>makesschemarsemit a boolean property schema ("properties": { ..., "state": true }), which is forwarded verbatim to Anthropic / OpenAI / OpenAI-compatible adapters (plugins/agent/model/src/adapters/request.rs,responses/request.rs,anthropic/schema.rs). No other builtin model tool emits a boolean subschema, and providers/gateways requiring schema objects underpropertiesreject"state": truewith HTTP 400 wheneverScheduledTaskis active (including every Bot turn).- Splitting the discriminator (
modevsaction) also produces ananyOfwrapping a nested single-variantoneOfand missesproducts/maka/workbench/app/toolNativeActivity.ts(switch (request?.mode)). - Suggested fix: Remove
ScriptActionand#[serde(untagged)], addTestScript { source: String, #[schemars(schema_with = ...)] state: Option<Value> }directly toenum Input(mode: "test_script"), givestatean object schema (e.g.{}or an explicit JSON value union), and handlecase 'test_script'intoolNativeActivity.ts.
- Adding
-
Backoff shift cap
.min(5)prevents intervals< 57sfrom reaching the 30-minute ceiling (plugins/agent/scheduler/engine/src/plan.rs:355-363)every_seconds.saturating_mul(1 << (self.consecutive_errors - 1).min(5)).min(every_seconds.max(1800))caps the multiplier at32×, so a failingevery_seconds = 1script tops out at32sforever (10s→320s,30s→960s) instead of1800s. Onlyevery_seconds >= 57reaches the 30-minute cap (which is why theevery_seconds = 60test didn't catch it).- Suggested fix: Use
1u32 << (self.consecutive_errors - 1).min(11)(2^11 = 2048 > 1800) so everyevery_seconds >= 1safely reachesevery_seconds.max(1800).
-
test_scriptswallows mid-run cancellation asOk({"ok": false, ...})(plugins/agent/native/src/owner/scheduler/scripts.rs:109-133)- Pre-spawn cancellation in
tools.rsreturnsErr(failed("Scheduled task cancelled")), matching other tools, but once insidetest_script, cancelling a running script turns"Script check cancelled"into a successful tool response (Ok({"ok": false, "error": "Script check cancelled", ...})). - Suggested fix: Check
if cancellation.is_cancelled() { return Err("Scheduled task cancelled".into()); }before buildingexecution.report(...).
- Pre-spawn cancellation in
-
Move
TestScripttool title intomaka_agent_facts::i18n::tool_title(plugins/agent/native/src/owner/scheduler/tools.rs:163-170)- All sibling
ScheduledTaskvariants usemaka_agent_facts::i18n::tool_title::*(12 locales), whereasInput::Script(_)hardcodes onlyzh-CN,zh-TW, and English inline (missingzh-HKand the other 9 locales).
- All sibling
Cleanups / polish
- Explicit
stdout_limitinstead of coupling toinput.is_some()(platform/process/src/process.rs:61-65): Deriving a 1 MiB stdout cap frominput.is_some()hides a scheduler-specific assumption insideplatform/process. Exposing an explicitstdout_limitoption onCommand(defaulting toTAIL_BYTES, raised explicitly byscripts.rs) makes the contract clear. - Deduplicate
dedupe_keyonScriptOutcome(plugins/agent/scheduler/engine/src/plan/script.rs:127-172):dedupe_keyis currently stored both onScriptOutcomeand cloned insideScriptOutcome.payload, allowing mismatched states in memory and forcing callers/tests to repeat the key. Keeping it in a single place removes the clone and makes mismatch unrepresentable. - Clear
script_statewhen editing away fromSchedule::Script(plugins/agent/scheduler/engine/src/plan/edit.rs:47-54): Changing a task's schedule fromScripttoCron/Interval/Once/Calendarresetscondition_matched,last_dedupe_key, andconsecutive_errors, but leaves up to 64 KiB of deadscript_statepersisted indefinitely (if !matches!(schedule, Schedule::Script { .. }) { next.script_state = None; }). - Test placement:
scheduler_dry_run_rejects_oversize_state_without_saving_a_taskcurrently lives inplugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rseven though this PR is independent of Discovery; moving it to a scheduler-focused test module (and optionally adding a direct test for the >1 MiBstdout_truncatedpartial-first-line drop path) would keep the suite tidy.
简体中文
整体架构和测试质量都很克制扎实——把状态收在 TaskPlan 里免了新 migration,前缀缓存保持确定性([Trigger context] 仅追加到新消息、data 排序后冻结、tool schema 静态),ReadyIndex::ready_ids 按最老到期排队的防饿死思路很干净,Tail 换成 VecDeque 也避免了 1 MiB 下的搬移开销。另外我也在 Linux 上实跑了单测、producer_reopen 和 upgrade_compat,并在 Windows 11 上验证了 64 KiB MAKA_AUTOMATION_STATE 透传。
合并前有几处具体问题和可打磨的点:
需要修复的问题
-
把
test_script统一收进mode,并避免输出 boolean JSON Schema ("state": true)(plugins/agent/native/src/owner/scheduler/tools.rs:28-77)- 在
#[serde(tag = "mode")] enum Input里塞入#[serde(untagged)] Script(ScriptAction)(带tag = "action")后,Serde 会吞掉ScheduledTask所有原有分支(create/list/pause/resume/delete)的字段级错误。例如{"request":{"mode":"create","title":"t"}}或{"request":{"mode":"list","extra":1}}都会退化成无信息的"data did not match any variant of untagged enum Input",不再提示missing field intentBody/unknown field extra,会影响模型在 10 字段工具上的自修正。 state: Option<Value>会让schemars生成 boolean property schema("properties": { ..., "state": true }),而plugins/agent/model/src/adapters/request.rs、responses/request.rs和anthropic/schema.rs都会原样透传给上游。全仓其它内置模型工具没有发出 boolean subschema 的先例,要求properties内必须为 schema object 的 provider / 网关会在ScheduledTask激活时(包括 Bot 每轮默认激活)直接 400 拒包。- 混用
mode和action两套 discriminator 还会把 schema 变成anyOf套单元素oneOf,并且绕过了products/maka/workbench/app/toolNativeActivity.ts的switch (request?.mode)渲染分支。 - 建议修法:删除
ScriptAction与#[serde(untagged)],直接在enum Input下新增TestScript { source: String, #[schemars(schema_with = ...)] state: Option<Value> }(走mode: "test_script"),为state加上返回 object schema(如{}或明确 JSON 类型anyOf)的schema_with,并在toolNativeActivity.ts补上case 'test_script'。
- 在
-
退避移位上限
.min(5)导致every_seconds < 57的脚本永远到不了 30 分钟封顶(plugins/agent/scheduler/engine/src/plan.rs:355-363)every_seconds.saturating_mul(1 << (self.consecutive_errors - 1).min(5)).min(every_seconds.max(1800))把倍率封死在32×,导致持续失败的every_seconds = 1脚本会永远卡在32s重试(10s→320s、30s→960s),只有every_seconds >= 57才会触达1800s(现有单测只测了60和3600,所以没暴露)。- 建议修法:改为
1u32 << (self.consecutive_errors - 1).min(11)(2^11 = 2048 > 1800),让任意every_seconds >= 1都能安全封顶到every_seconds.max(1800)。
-
test_script在运行中被取消时会把取消吞成Ok({"ok": false, ...})(plugins/agent/native/src/owner/scheduler/scripts.rs:109-133)tools.rs在启动前被取消会按惯例返回Err(failed("Scheduled task cancelled")),但进入test_script后一旦在运行中被取消,"Script check cancelled"会被包进execution.report(...)并以工具调用成功(Ok)返回。- 建议修法:在构造
execution.report(...)前先判断if cancellation.is_cancelled() { return Err("Scheduled task cancelled".into()); }。
-
把
TestScript工具标题迁入maka_agent_facts::i18n::tool_title(plugins/agent/native/src/owner/scheduler/tools.rs:163-170)- 同文件其余 5 个分支都走
maka_agent_facts::i18n::tool_title::*(12 语言),只有Input::Script(_)在代码里硬编码了zh-CN/zh-TW/英文(缺了zh-HK和其余 9 种语言)。
- 同文件其余 5 个分支都走
可顺手打磨的干净度细节
- 将
stdout_limit显式化,不要隐式绑定到input.is_some()(platform/process/src/process.rs:61-65):用是否传入 stdin 来决定是否把 stdout 上限放大到 1 MiB,会在底层platform/process埋下和调度器协议耦合的隐含行为;在Command上提供显式配置(默认TAIL_BYTES,由scripts.rs调大)更清晰。 - 消除
ScriptOutcome上重复存储的dedupe_key(plugins/agent/scheduler/engine/src/plan/script.rs:127-172):当前dedupe_key在ScriptOutcome顶层存一份,又 clone 进payload存一份,类型上允许两边不一致且测试构造也要重复传两次;收敛为单一来源即可消除 clone 与非法状态。 - 编辑任务切换为非脚本调度时清理
script_state(plugins/agent/scheduler/engine/src/plan/edit.rs:47-54):从Schedule::Script改成Cron/Interval/Once/Calendar时,已经清了condition_matched/last_dedupe_key/consecutive_errors,建议同步清掉script_state(if !matches!(schedule, Schedule::Script { .. }) { next.script_state = None; }),避免最多 64 KiB 死状态永久滞留。 - 测试归属与边界:
scheduler_dry_run_rejects_oversize_state_without_saving_a_task放在了plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs中,但本 PR 与 Discovery 无关,挪到 scheduler 测试模块更贴切;另外有余力可补一个覆盖 >1 MiBstdout_truncated丢弃残缺首行的边界用例。
…backoff, and tool errors - Unify ScheduledTask dry-run under mode: test_script, removing ScriptAction and #[serde(untagged)] so serde field errors stay specific and state emits an object JSON schema. - Localize TestScript tool title via maka_agent_facts::i18n::tool_title across base locales and project test_script arguments in Workbench toolNativeActivity. - Preserve ToolError (including CleanupUnconfirmed and Cancellation) on the test_script preview path instead of wrapping them into ok:false reports. - Replace implicit input.is_some() policy in platform/process with explicit Shell vs Protocol mode, and track stdout EOF separately from prefix overflow so incomplete reads cannot be parsed as valid trigger outcomes. - Fix short-interval script backoff to reach the 1800s cap using saturating_pow, deduplicate ScriptOutcome.dedupe_key, clear script_state when editing away from Schedule::Script, and make ScriptChecks slot release explicit.
There was a problem hiding this comment.
Pushed follow-up commit a6b8e08d27 addressing the review items (unified mode: "test_script" with object state schema, 11-locale tool_title, Workbench argument projection, explicit Shell/Protocol process mode and stdout EOF tracking, preserved ToolError on test_script, short-interval backoff cap via saturating_pow, deduplicated ScriptOutcome.dedupe_key, script_state cleanup on schedule change, and explicit ScriptChecks slot release). All local suites (maka-scheduler, maka-process, maka-agent-facts, maka-agent-native, producer_reopen, upgrade_compat, workbench presentation tests) and PR checks pass. LGTM!
Split PR Series (from overview #7200)
15 files, +998 / -100)7d916e8bc80056), tools, RPCs (35 files, +4,629 / -455)510e1c9ce50057), delta header, elastic stopping (32 files, +2,389 / -163)a340e5266c0058), Wander mode,preferences.md(37 files, +1,814 / -88)209b0857cd0059), PendingActions, WatchScope, WorkspaceMap (52 files, +7,655 / -720)acd5c7edee42 files, +4,609 / -281)bf3f7422c2Summary
Standalone scheduler enhancement split out from overview PR #7200 (independent of Proactive Discovery — can be reviewed and merged directly into
main).test_script): Allow dry-running scheduled scripts and validating state size limits before persisting a task.Verification
cargo test -p maka-scheduler— passedcargo test -p maka-process— passedcargo test -p maka-agent-native --lib scheduler_dry_run_rejects_oversize_state_without_saving_a_task— passedcargo test -p maka-cli --no-run --test producer_reopen --test upgrade_compat— built cleanlynode scripts/ci.mjs check format licenses migrations— passed