Skip to content

feat(cron): stream schedule sources with durable source identity - #112387

Merged
steipete merged 17 commits into
mainfrom
claude/cron-stream-identity-land
Jul 21, 2026
Merged

steipete merged 17 commits into
mainfrom
claude/cron-stream-identity-land

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Related: #110950

Supersedes #112189. This replacement carries the same reviewed Track D diff on a fresh PR and branch identity because scheduled preflight jobs on the original PR remained permanently unassigned while newer repository runs completed, and repeated ClawSweeper review leases expired without a result. No product scope changed during the replacement.

What Problem This Solves

Track D of the automation-unification program (#110950): stream schedule sources — a gateway-supervised long-lived command whose stdout/stderr lines fire a cron job as batched events. The original branch was deferred after four autoreview rounds (8–11) kept surfacing lifecycle races in the admission token design.

Root cause of those races: one counter served two contradictory purposes. The watcher's per-process restart generation was persisted as the cron admission token, so

  • an in-place child restart/backoff retired its own just-flushed final batch (legitimate work dropped under load), while
  • a disable→re-enable or A→B→A schedule edit could re-admit a stale queued batch during the async stop window (the store still carried the old token until the watcher's serialized stop persisted).

Why This Change Was Made

This PR is the redesign rather than another patch. It separates the two concepts:

  • streamSourceIdentity (persisted, cron-store-owned): an opaque UUID naming one logical source. It is created in createJob, rotated inside the same store transaction as any mutation that changes source ownership (finalizeUpdatedJob: schedule-key change, enable/disable flip; applyTriggerRunResult: trigger.once auto-disable), and rotated via a new compare-and-swap retireExternalStreamSource op for teardowns that have no job mutation (removal, shutdown, trust/cron disable). It is stable across supervised child restarts, so a batch flushed by an exiting child still admits.
  • Watcher process generation (in-memory only): fences stale child callbacks (stdout/stderr, quiet/stable/rate timers, drains). Obsolete-generation callbacks are now inert instead of mutating counters; a rate-timer epoch prevents an old timer from clearing its replacement.

Admission (cron.run preflight → locked reservation → post-admission activation → execution snapshot) now requires schedule key and identity together; a key without an identity is rejected instead of treated as optional. Owner state/failure persistence is identity-guarded, so a retired owner cannot write terminal state onto a re-created same-key job. Batch runs no longer pass the watcher's cached payload as an override — cron.run snapshots the persisted payload under its admission lock, so a committed payload edit takes effect for the very next batch. The identity is reported in the protocol job state but intentionally absent from the writable patch schema.

Adjacent watcher defects found during the redesign are fixed in the same boundary:

  • mode: "match" regexes now run against raw source text; the [truncated] marker is rendered only after matching, so a marker-anchored pattern can no longer be triggered by truncation itself (and a literal [truncated] from the source still matches). Matching is chunking-independent: a complete line split across pipe callbacks matches exactly like the same line in one callback, and a line exceeding the bounded raw-intake cap (4× maxBatchBytes) is an unprovable prefix — never matched — regardless of how its fragments arrived.
  • A stop-timeout failure now sets the live restartExhausted mirror before persisting, so a later successful shutdown stop preserves the terminal streamStatus: "error" diagnostic instead of overwriting it with stopped.
  • stopAll is a true barrier: shutdown waits for every owner teardown to settle before surfacing the first failure, instead of resolving while sibling teardowns are still in flight.
  • EOF never promotes a retained prefix into a match after its continuation was dropped; a stop requested during asynchronous exit drains wins before failure accounting; and a failed shutdown drain can be retried instead of being memoized forever.

The 1,7xx-line watcher is split into cron-stream-job-owner.ts (lifecycle), cron-stream-output.ts (buffering/batching/firing), and cron-stream-watchers.ts (registry/reconcile), all under the max-lines budget with no new suppressions. Retired cron.triggers.minIntervalMs config references were dropped in favor of the built-in 30s floor (test seams inject smaller intervals).

User Impact

Operators get stream schedules (--stream-command, --stream-mode, --stream-match, batching bounds) gated behind cron.triggers.enabled, with correct behavior across source restarts, schedule edits, disable/re-enable cycles, and gateway shutdown: no stale batch can fire after its source was retired, and no legitimate batch is dropped because its child restarted. Docs updated (docs/automation/cron-jobs.md).

Evidence

  • Watcher + output modules on the rebased head: node scripts/run-vitest.mjs src/gateway/cron-stream-watchers.test.ts src/gateway/cron-stream-output.test.ts src/gateway/cron-stream-output.interleavings.test.ts — 62 tests green, including dropped-continuation EOF, stop-during-exit-drain, identity replacement, A→B→A rejection, truncation, and stop-barrier regressions.
  • Gateway/service focused proof on the rebased head: src/gateway/server-cron.test.ts — 55 tests green; stream trigger/validation/admission files — 33 tests green. The earlier full cron + gateway-server sweep covered 141 files / 1,581 tests.
  • Protocol schema: identity reported in CronJobStateSchema, rejected in the writable patch schema (src/cron/cron-protocol-schema.test.ts).
  • tsgo --noEmit clean; oxlint clean including max-lines (no new suppressions); oxfmt applied.
  • Remote build (Blacksmith Testbox) green on the redesign tree: run 29800447322 (pnpm build, startup-size budget passing at 302.5KiB). Later commits are in-module edits and tests only — no new prod modules, packaging, or lazy-boundary changes.
  • Structured autoreview: the original eight-cycle Codex review was followed by fresh full-branch and targeted reviews after rebasing. Every accepted finding received a regression; the final 326 KB full-branch pass exited clean with no accepted/actionable findings (patch is correct, 0.82).

steipete added 17 commits July 21, 2026 08:36
Add gated argv stream schedules with bounded line batching and trigger.streamBatch composition.

Reuse the gateway ProcessSupervisor for source ownership, deterministic teardown, capped restart backoff, and schedule-key guarded batch execution. Expose additive protocol, CLI, tool, UI, docs, and generated snapshot surfaces without storage DDL.

Contract: stream schedules are event-driven, require cron.triggers.enabled, reject command payloads, and retain at most one bounded pending batch.
Thread an invalidatable per-owner source-generation token (ownerNonce.generation)
through cron.run admission alongside the schedule key. A batch handed to cron.run
under one source epoch can wait behind another run while its owner is stopped; a
disable→re-enable or A→B→A edit leaves the schedule key unchanged, so the key
check alone would admit the retired epoch's batch. The token is persisted in
job.state on every lifecycle write and compared at every admission site plus the
executeJobCore guard, so a stale epoch's batch is skipped.

Also fix direct stream-job mutations recording the wrong lifecycle status when
global cron is off but triggers are on: extract resolveStreamStopReason so the
direct path reports the remediable cron-disabled state like reconcile does.
- Persist the retired source generation before draining stop teardown, so a
  batch queued behind another cron run cannot gain admission during the up-to-10s
  in-flight-batch wait (server-cron routed stop path).
- Add streamSourceGeneration to the closed gateway response schema (excluded from
  the writable patch schema) so a running stream job passes strict result
  validation without letting callers spoof source identity.
- Close the mutation-epoch ABA: track an eviction epoch so a snapshotted absent-0
  is trusted as unchanged only when no LRU eviction happened during the await.
Split the conflated restart-generation/admission token into two concepts:
a persisted streamSourceIdentity owned by cron store mutations (rotates on
enable/disable, source replacement, once-trigger auto-disable, and explicit
retirement; stable across supervised child restarts) and a watcher-local
process generation used only to fence stale child callbacks. Admission now
requires schedule key + identity together at every window, closing the
A-to-B-to-A and restart-flush races from review rounds 8-11.

Also: match-mode regexes now see raw source text (the [truncated] marker is
applied after matching), stop-timeout failures set the live restartExhausted
mirror so shutdown preserves the terminal diagnostic, and the watcher is
split into owner/output/registry modules under the max-lines budget.
An exit queued ahead of a requested stop no longer counts toward restart
exhaustion (the synchronous stop fence owns it), overlapping cron.stop and
stopAndDrain share one memoized shutdown drain instead of double-stopping
every owner, raw output intake is bounded at 4x the batch cap so normal
64 KiB pipe reads stop losing complete lines to OS chunk boundaries, and
persisted-shape quarantine coverage for unsafe match expressions is pinned.
…entity

Disposing an obsolete owner while a start replaces it is not a durable
removal; a retiring stop there rotated the live job's identity and stranded
the replacement behind the CAS ownership guard. Also align the docs with the
implemented match semantics: complete lines match on full text past the
batch cap, only intake-cut prefixes are unmatchable.
Partial lines are retained up to the raw-intake bound rather than the
delivery cap, so a complete over-cap line matches identically whether it
arrives in one callback or several; only a line the intake bound itself cut
remains an unprovable prefix. Reconcile also contains schedule-replacement
stop failures per job, matching the other stop branches.
…r stopAll

- enforce the 4x raw-intake per-line cap while assembling split callbacks,
  so an oversized line stays an unprovable prefix regardless of chunking
- stop passing the watcher-cached payload as a cron.run override; the run
  snapshots the persisted payload under its admission lock
- stopAll waits for every owner stop to settle before surfacing failures
- split cron-stream-output interleaving tests into their own file (max-lines)
…ion routes

A cron.list snapshot captured across the reconcile await could be applied
after a direct add/update route already started the owner, stopping it as
removed and retiring its live identity. A mutation revision bumped at every
direct route start invalidates the stale snapshot; reconcile re-lists
(bounded) instead of applying it.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Jul 21, 2026
@steipete
steipete marked this pull request as ready for review July 21, 2026 18:34
@steipete
steipete requested a review from a team as a code owner July 21, 2026 18:34
@clawsweeper

clawsweeper Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: feat(cron): stream schedule sources with durable source identity This is item 1/1 in the current shard. Shard 0/1.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@steipete
steipete merged commit 98742bc into main Jul 21, 2026
286 of 303 checks passed
@steipete
steipete deleted the claude/cron-stream-identity-land branch July 21, 2026 22:01
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 22, 2026
…nclaw#112387)

* feat(cron): stream schedule sources (supervised command stdout)

Add gated argv stream schedules with bounded line batching and trigger.streamBatch composition.

Reuse the gateway ProcessSupervisor for source ownership, deterministic teardown, capped restart backoff, and schedule-key guarded batch execution. Expose additive protocol, CLI, tool, UI, docs, and generated snapshot surfaces without storage DDL.

Contract: stream schedules are event-driven, require cron.triggers.enabled, reject command payloads, and retain at most one bounded pending batch.

* fix(cron): reject retired stream source epochs at run admission

Thread an invalidatable per-owner source-generation token (ownerNonce.generation)
through cron.run admission alongside the schedule key. A batch handed to cron.run
under one source epoch can wait behind another run while its owner is stopped; a
disable→re-enable or A→B→A edit leaves the schedule key unchanged, so the key
check alone would admit the retired epoch's batch. The token is persisted in
job.state on every lifecycle write and compared at every admission site plus the
executeJobCore guard, so a stale epoch's batch is skipped.

Also fix direct stream-job mutations recording the wrong lifecycle status when
global cron is off but triggers are on: extract resolveStreamStopReason so the
direct path reports the remediable cron-disabled state like reconcile does.

* fix(cron): close stream admission windows from round-10 review

- Persist the retired source generation before draining stop teardown, so a
  batch queued behind another cron run cannot gain admission during the up-to-10s
  in-flight-batch wait (server-cron routed stop path).
- Add streamSourceGeneration to the closed gateway response schema (excluded from
  the writable patch schema) so a running stream job passes strict result
  validation without letting callers spoof source identity.
- Close the mutation-epoch ABA: track an eviction epoch so a snapshotted absent-0
  is trusted as unchanged only when no LRU eviction happened during the await.

* refactor(cron): stream sources own a durable logical identity

Split the conflated restart-generation/admission token into two concepts:
a persisted streamSourceIdentity owned by cron store mutations (rotates on
enable/disable, source replacement, once-trigger auto-disable, and explicit
retirement; stable across supervised child restarts) and a watcher-local
process generation used only to fence stale child callbacks. Admission now
requires schedule key + identity together at every window, closing the
A-to-B-to-A and restart-flush races from review rounds 8-11.

Also: match-mode regexes now see raw source text (the [truncated] marker is
applied after matching), stop-timeout failures set the live restartExhausted
mirror so shutdown preserves the terminal diagnostic, and the watcher is
split into owner/output/registry modules under the max-lines budget.

* fix(cron): harden stream teardown and intake from round-4 review

An exit queued ahead of a requested stop no longer counts toward restart
exhaustion (the synchronous stop fence owns it), overlapping cron.stop and
stopAndDrain share one memoized shutdown drain instead of double-stopping
every owner, raw output intake is bounded at 4x the batch cap so normal
64 KiB pipe reads stop losing complete lines to OS chunk boundaries, and
persisted-shape quarantine coverage for unsafe match expressions is pinned.

* fix(cron): keep watcher-internal owner disposal from retiring live identity

Disposing an obsolete owner while a start replaces it is not a durable
removal; a retiring stop there rotated the live job's identity and stranded
the replacement behind the CAS ownership guard. Also align the docs with the
implemented match semantics: complete lines match on full text past the
batch cap, only intake-cut prefixes are unmatchable.

* fix(cron): make oversized-line matching independent of pipe chunking

Partial lines are retained up to the raw-intake bound rather than the
delivery cap, so a complete over-cap line matches identically whether it
arrives in one callback or several; only a line the intake bound itself cut
remains an unprovable prefix. Reconcile also contains schedule-replacement
stop failures per job, matching the other stop branches.

* fix(cron): bound assembled lines, drop stale payload override, barrier stopAll

- enforce the 4x raw-intake per-line cap while assembling split callbacks,
  so an oversized line stays an unprovable prefix regardless of chunking
- stop passing the watcher-cached payload as a cron.run override; the run
  snapshots the persisted payload under its admission lock
- stopAll waits for every owner stop to settle before surfacing failures
- split cron-stream-output interleaving tests into their own file (max-lines)

* fix(cron): address first full-CI round (lint, knip, schema test, unused param)

* chore(cron): refresh codex prompt snapshots for stream schedule schema

* fix(cron): keep the first clean line after an intake drop ending at a newline

* fix(cron): fence stream reconcile list snapshots against direct mutation routes

A cron.list snapshot captured across the reconcile await could be applied
after a direct add/update route already started the owner, stopping it as
removed and retiring its live identity. A mutation revision bumped at every
direct route start invalidates the stale snapshot; reconcile re-lists
(bounded) instead of applying it.

* style(cron): format stream owner imports

* fix(cron): discard severed stream prefixes at EOF

* fix(cron): retry failed stream shutdown drains

* fix(cron): honor stream stop fence after output drain

* chore(cron): refresh landing checks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant