Skip to content

feat(scheduler): add structured script payloads, persistent state, concurrency cap, backoff, and dry-run - #7264

Merged
M4n5ter merged 2 commits into
apache:mainfrom
sunrioa:feat/scheduler-stateful-scripts
Nov 25, 2026
Merged

M4n5ter merged 2 commits into
apache:mainfrom
sunrioa:feat/scheduler-stateful-scripts

Conversation

@sunrioa

@sunrioa sunrioa commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Split PR Series (from overview #7200)

Order PR Status Scope Incremental Commit
Independent #7264 ← this PR Ready Independent — Scheduler stateful script runtime (15 files, +998 / -100) 7d916e8bc8
1/5 #7265 Ready Discovery 1/5 — Core Dossiers schema (0056), tools, RPCs (35 files, +4,629 / -455) 510e1c9ce5
2/5 (on 1/5) #7266 Draft Discovery 2/5 — ChangeTracker (0057), delta header, elastic stopping (32 files, +2,389 / -163) a340e5266c
3/5 (on 2/5) #7267 Draft Discovery 3/5 — Staging sandbox (0058), Wander mode, preferences.md (37 files, +1,814 / -88) 209b0857cd
4/5 (on 3/5) #7268 Draft Discovery 4/5 — WatchRunner (0059), PendingActions, WatchScope, WorkspaceMap (52 files, +7,655 / -720) acd5c7edee
5/5 (on 4/5) #7269 Draft Discovery 5/5 — Pure Frontend Workbench UI & 12-locale i18n (42 files, +4,609 / -281) bf3f7422c2

Review tip for stacked Draft PRs (2/5–5/5): Because cross-fork PRs target main, click the Incremental Commit link above to review only that PR's isolated diff until its predecessor is merged and rebased.


Summary

Standalone scheduler enhancement split out from overview PR #7200 (independent of Proactive Discovery — can be reviewed and merged directly into main).

  • Structured script payloads & persistent state: Support JSON script payloads and bounded persistent state (64 KiB JSON cap) across scheduled script runs.
  • Concurrency cap & retry backoff: Cap concurrent scheduled script executions and apply bounded backoff on repeated failures.
  • Dry-run preview (test_script): Allow dry-running scheduled scripts and validating state size limits before persisting a task.
  • Process tail & compatibility: Capture bounded script output tails and cover reopen/upgrade compatibility.

Verification

  • cargo test -p maka-scheduler — passed
  • cargo test -p maka-process — passed
  • cargo test -p maka-agent-native --lib scheduler_dry_run_rejects_oversize_state_without_saving_a_task — passed
  • cargo test -p maka-cli --no-run --test producer_reopen --test upgrade_compat — built cleanly
  • node scripts/ci.mjs check format licenses migrations — passed

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Unify test_script under mode and avoid emitting a boolean JSON Schema ("state": true) (plugins/agent/native/src/owner/scheduler/tools.rs:28-77)

    • Adding #[serde(untagged)] Script(ScriptAction) (with tag = "action") inside #[serde(tag = "mode")] enum Input causes Serde to discard variant-specific errors across all ScheduledTask variants (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> makes schemars emit 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 under properties reject "state": true with HTTP 400 whenever ScheduledTask is active (including every Bot turn).
    • Splitting the discriminator (mode vs action) also produces an anyOf wrapping a nested single-variant oneOf and misses products/maka/workbench/app/toolNativeActivity.ts (switch (request?.mode)).
    • Suggested fix: Remove ScriptAction and #[serde(untagged)], add TestScript { source: String, #[schemars(schema_with = ...)] state: Option<Value> } directly to enum Input (mode: "test_script"), give state an object schema (e.g. {} or an explicit JSON value union), and handle case 'test_script' in toolNativeActivity.ts.
  2. Backoff shift cap .min(5) prevents intervals < 57s from 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 at 32×, so a failing every_seconds = 1 script tops out at 32s forever (10s → 320s, 30s → 960s) instead of 1800s. Only every_seconds >= 57 reaches the 30-minute cap (which is why the every_seconds = 60 test didn't catch it).
    • Suggested fix: Use 1u32 << (self.consecutive_errors - 1).min(11) (2^11 = 2048 > 1800) so every every_seconds >= 1 safely reaches every_seconds.max(1800).
  3. test_script swallows mid-run cancellation as Ok({"ok": false, ...}) (plugins/agent/native/src/owner/scheduler/scripts.rs:109-133)

    • Pre-spawn cancellation in tools.rs returns Err(failed("Scheduled task cancelled")), matching other tools, but once inside test_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 building execution.report(...).
  4. Move TestScript tool title into maka_agent_facts::i18n::tool_title (plugins/agent/native/src/owner/scheduler/tools.rs:163-170)

    • All sibling ScheduledTask variants use maka_agent_facts::i18n::tool_title::* (12 locales), whereas Input::Script(_) hardcodes only zh-CN, zh-TW, and English inline (missing zh-HK and the other 9 locales).

Cleanups / polish

  • Explicit stdout_limit instead of coupling to input.is_some() (platform/process/src/process.rs:61-65): Deriving a 1 MiB stdout cap from input.is_some() hides a scheduler-specific assumption inside platform/process. Exposing an explicit stdout_limit option on Command (defaulting to TAIL_BYTES, raised explicitly by scripts.rs) makes the contract clear.
  • Deduplicate dedupe_key on ScriptOutcome (plugins/agent/scheduler/engine/src/plan/script.rs:127-172): dedupe_key is currently stored both on ScriptOutcome and cloned inside ScriptOutcome.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_state when editing away from Schedule::Script (plugins/agent/scheduler/engine/src/plan/edit.rs:47-54): Changing a task's schedule from Script to Cron/Interval/Once/Calendar resets condition_matched, last_dedupe_key, and consecutive_errors, but leaves up to 64 KiB of dead script_state persisted indefinitely (if !matches!(schedule, Schedule::Script { .. }) { next.script_state = None; }).
  • Test placement: scheduler_dry_run_rejects_oversize_state_without_saving_a_task currently lives in plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs even though this PR is independent of Discovery; moving it to a scheduler-focused test module (and optionally adding a direct test for the >1 MiB stdout_truncated partial-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 透传。

合并前有几处具体问题和可打磨的点:

需要修复的问题

  1. 把 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'。
  2. 退避移位上限 .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)。
  3. 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()); }。
  4. 把 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 种语言)。

可顺手打磨的干净度细节

  • 将 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 MiB stdout_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.

@M4n5ter M4n5ter left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

@M4n5ter
M4n5ter merged commit 78cc3ec into apache:main Nov 25, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/XL Under 2500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants