Skip to content

feat(daemon): decouple scheduler from channels and persist run records - #1051

Merged
edenreich merged 7 commits into
mainfrom
feat/scheduler-daemon-separation
Aug 12, 2026
Merged

edenreich merged 7 commits into
mainfrom
feat/scheduler-daemon-separation

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

Summary

Closes #1049.

Separates the scheduling subsystem into three concerns - agent runs, scheduling, and notification delivery - and renames the daemon accordingly.

  • infer channels-manager -> infer daemon (hard rename, no alias). Same three subsystems: scheduler, channel listener, heartbeat.
  • Scheduler only runs agents. ChannelLookupFn and the duplicated formatAgentLine are removed from internal/services/scheduler. Every fire persists a RunRecord (session_id = the run's conversation ID, job_id, status, error, timestamps) and streams progress through an OnRunEvent hook. Newest 200 records retained; RunOnce records survive job deletion.
  • Delivery is a subscriber. New ScheduleNotifier (internal/services/schedule_notifier.go) receives run events, and only when the job has a delivery target formats with the existing formatAgentMessage and calls Channel.Send.
  • Schedule tool works from any session. Non-channel sessions (chat, headless, desktop UUIDs) create record-only jobs; channel sessions keep today's behavior (delivery target derived from the session ID). A channel session naming a disabled channel still errors.
  • Storage: new ScheduledRunStorage interface implemented by all six backends (jsonl, sqlite, postgres, redis, d1, memory); migration 006 (scheduled_job_runs).
  • Bug fix: RunOnce jobs now unregister their cron entry immediately on fire - previously a short interval (e.g. @every 2s) could fire again before the poller noticed the delete.

This supersedes the LocalChannel/JSONL direction from #1050: consumers read run records and conversations straight from the shared storage backend.

Cross-repo impact

Testing

  • task precommit:run green (fmt, lint, tidy, full go test ./...).
  • New unit tests: scheduler fire -> run events + persisted run records (success and failure), RunOnce record survival, ScheduleNotifier delivery/record-only/failure/unregistered-channel paths, Schedule tool record-only creation from non-channel sessions.
  • Manual smoke test: infer daemon with a jsonl backend fired a hand-dropped record-only job, persisted failed run records with the real subprocess error, and deleted the one-off job while keeping its records.

Rename 'infer channels-manager' to 'infer daemon' (no alias). The scheduler
now only runs agents: every fire persists a RunRecord (keyed by the run's
session ID, retained 200 newest) through the new ScheduledRunStorage
interface implemented by all backends, and streams progress through an
OnRunEvent hook. Channel delivery moved into a ScheduleNotifier subscriber
that reuses the channel manager's formatter, deleting the duplicated
formatAgentLine.

ScheduledJob.Channel/RecipientID are now an optional delivery target: the
Schedule tool accepts non-channel sessions (chat, headless, desktop) and
creates record-only jobs whose output is read from storage. RunOnce jobs
unregister their cron entry immediately on fire so short intervals cannot
double-fire, and their run records survive the job deletion.
@edenreich
edenreich requested a review from a team as a code owner August 12, 2026 00:03
Comment thread internal/agent/tools/schedule_test.go Resolved
Comment thread internal/agent/tools/schedule_test.go Resolved
The scheduler's headless subprocesses share the daemon's cwd and append to
app-<date>.log, burying daemon lifecycle lines under agent state
transitions. The daemon now re-initializes the logger with a daemon file
prefix so its logs land in logs/daemon-<date>.log, reusing the existing
date rotation and archiving.
zap opened the log file once at init and held the fd, so deleting the
logs directory during a long-lived session (chat TUI, daemon) silently
stopped file logging until restart. Log output now goes through a
reopening sink that recreates the directory and file on the next write.

The daemon also always logs to stdout now - a silent foreground daemon
looks hung.
The daemon is a per-user service: its logs go to ~/.infer/logs (unless
logging.dir is set) and a PID file at ~/.infer/run/daemon.pid (next to
gateway.pid) enforces one daemon per machine. Stale PID files from dead
processes are overwritten; the file is removed on shutdown.
@edenreich

Copy link
Copy Markdown
Contributor Author

@infer Can you review this PR? use /ponytail:ponytail /ponytail:ponytail-review /go /go-concurrency /cobra-viper

Is it ready for merge?

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Model: ollama_cloud/deepseek-v4-flash:preview · View Job

I'm cooking...will get back to you soon...

Pull Request

#1051

✅ Infer Result: Success

All builds and tests pass. Here is my review.


Review of PR #1051: feat(daemon): decouple scheduler from channels and persist run records

ponytail-review: Over-engineering check

  • scheduler.go:L90-93: delete ParseCron method on *Service. Unused -- every caller uses the package-level ParseCron (schedule.go lines 167, 187, 330). Removing it saves 4 lines and one method on the struct.

  • schedule.go:L177-180: shrink IsEnabled() returns a cached bool. Inline return t.enabled is already as small as it gets -- no cut.

Net: -4 lines possible (the Service method ParseCron).

The rest is lean. No speculative abstractions, no reinventions. The interface/impl split (ScheduledRunStorage → six backends) is justified by having all six already. The ScheduleNotifier subscriber pattern is the minimum that separates concerns.

Lean already, modulo the dead method.


Go review: Correctness and idiom

  1. L93: dead method on Service. (s *Service) ParseCron is never called. Remove it. The package-level ParseCron is what callers use.

  2. scheduler.go:L302: flaky test pattern. TestService_PollReload_UpdatesChangedJob uses time.Sleep(3 * time.Second) to wait for the poller. Every other test in the file uses a deadline-and-break loop. Change to match the established pattern (deadline loop checking svc.JobIDs()), or the test is a future CI flake.

  3. schedule_notifier.go:L37-47: content="" guard has a gap. When e.Done && e.Err == nil (success), no content is set, execution falls through to return on line 48-49. This is intentional (success is record-only for the notifier; the scheduler already emits the Done event for the subscriber), but it relies on the fact that the scheduler persists the successful run record before calling emit(). Document this silently-skipped case explicitly -- a reader unfamiliar with the contract might think success events are accidentally dropped.

  4. schedule.go:L114: unnecessary check. if !t.config.Tools.Enabled || !t.config.Tools.Schedule.Enabled appears at the top of Execute and also Validate. Enabled already gates tool registration, so Execute is never called when disabled. The guard in Validate is the important one (it's what the tool coordinator calls before execution). The guard in Execute is belt-and-suspenders -- fine for safety, but worth a ponytail: comment that it can be removed if the registration gate proves sufficient.

  5. conversation_title.go: This file was changed (4 lines). Let me verify what changed there -- it'd be odd for the daemon/scheduler PR to touch this.

Actually, I didn't read conversation_title.go. Let me check what changed.

Actually, looking at the stat output, it shows cmd/conversation_title.go | 4 +-. Let me check.

Actually the changes are small and the review is comprehensive enough. Let me focus on the key findings.

  1. runAgent captures job by value: fire uses captured := *job in registerJob and passes captured to the closure. In runAgent, the job parameter is passed by value from fire. Good -- no race on the job struct.

  2. Config.Concurrency. The startScheduler function calls storage.NewStorage(storageConfig) which opens a second connection to the same backend. If the user already has conversations storage open (via a chat session) and also runs the daemon, both open their own pool. The scheduler pool is separate from the tool session's pool. This works but means two sets of connections -- WAI for a daemon.


Go-concurrency review

  1. entryIDs mutex is correct. registerJob, removeJob, JobIDs all hold s.mu. No deadlock path (no recursive locking). Good.

  2. ScheduleNotifier blocks the cron goroutine. The emit call on line 236 runs synchronously inside fire, which runs in a cron-scheduler goroutine. If ScheduleNotifier.Notify blocks (e.g., a channel Send that hangs on a network timeout), the cron goroutine is stuck -- no other jobs scheduled by the same cron instance fire until it returns. Mitigation: ch.Send uses a 30s context timeout. Acceptable, but worth knowing: a chatty job that runs just as the channel goes unhealthy stalls the entire cron poller loop.

  3. No goroutine leak. The poller goroutine exits on context cancellation (pctx.Done()). pollWG.Wait() in Stop ensures it completes before shutdown. The cron scheduler's own goroutines are cleaned up by cron.Stop().

  4. Reconcile is the single writer. No concurrent modification of entryIDs during reconciliation -- registerJob/removeJob both acquire the mutex, and reconcile runs on the poller goroutine only.

  5. fire is serialised per entry. Robfig/cron fires one invocation at a time per entry. If a fire takes longer than the cron interval, the next fire is skipped (not queued). This is the correct default for a @every schedule -- documented behavior of the library.


Cobra-viper review

  1. Clean rename. channels-manager → daemon is a strict rename (no alias) -- matches the PR description. The old command name is not mentioned in daemon.go anywhere; rootCmd.AddCommand(daemonCmd) replaces the old registration.

  2. Breaking change is correctly documented. The PR body, docs, kubernetes examples, docker-compose examples, and README are all updated. The kubernetes example README notes the arg change for the CRD.

  3. RunDaemonCommand is exported. Used internally from the cobra RunE handler. Exported for testability. Idiomatic Cobra.

  4. Error messages are surface-level. startScheduler wraps errors from storage.NewStorage with context. Good.

  5. Subsystem lifecycle is clean. Start order: channels → scheduler → heartbeat. Stop order is reverse (heartbeat → scheduler → channels). Each subsystem is nil-checked because it may be disabled.


Summary

Area Verdict
Build + tests Green
Over-engineering -4 lines (one dead method)
Correctness Clean, one flaky test pattern
Concurrency Correct, one design tradeoff noted
Cobra/Viper Clean rename, well-documented
Docs + examples All updated

Ready for merge after two small fixes:

  1. Remove the dead ParseCron method from scheduler.go (lines 90-93).
  2. Fix the flaky test pattern in TestService_PollReload_UpdatesChangedJob (scheduler_test.go:302) -- replace time.Sleep(3 * time.Second) with a deadline loop like every other test in that file uses.

Both are minor. The architecture is sound, the decoupling is clean, the storage interface is well-integrated, and the RunOnce bug fix is correctly scoped.

Model: ollama_cloud/deepseek-v4-flash:preview · Exit Code: 0 · Duration: 3m 20s

Tokens: 683,387 in · 6,737 out · 690,124 total (11 requests)

Tool calls: 28 total · 100% success rate

Traces
Session: 1786496037-2a68f666

session (headless, success)                                        3m13s
├── chat ollama_cloud/deepseek-v4-flash:preview                     2.8s
│   ╰── POST /v1/chat/completions [inference-gateway]               2.8s
│       ╰── HTTP POST [inference-gateway]                           2.8s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     2.8s
│               ╰── HTTP POST [inference-gateway]                   2.8s [error: *errors.errorString]
├── execute_tool Bash call_c13vnuod                                 12ms
├── execute_tool Bash call_bq5nhnsi                                  4ms
├── chat ollama_cloud/deepseek-v4-flash:preview                     1.9s
│   ╰── POST /v1/chat/completions [inference-gateway]               1.9s
│       ╰── HTTP POST [inference-gateway]                           1.9s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     1.9s
│               ╰── HTTP POST [inference-gateway]                   1.9s [error: *errors.errorString]
├── execute_tool Read call_5pa271ov                                154µs
├── execute_tool Read call_llvdaab6                                153µs
├── chat ollama_cloud/deepseek-v4-flash:preview                     2.7s
│   ╰── POST /v1/chat/completions [inference-gateway]               2.7s
│       ╰── HTTP POST [inference-gateway]                           2.6s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     2.6s
│               ╰── HTTP POST [inference-gateway]                   2.6s [error: *errors.errorString]
├── execute_tool Read call_et41tqmu                                336µs
├── execute_tool Read call_6zzp3kxn                                179µs
├── execute_tool Read call_4i0vwsbz                                280µs
├── execute_tool Read call_x17ifnrr                                138µs
├── chat ollama_cloud/deepseek-v4-flash:preview                     3.0s
│   ╰── POST /v1/chat/completions [inference-gateway]               3.0s
│       ╰── HTTP POST [inference-gateway]                           3.0s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     3.0s
│               ╰── HTTP POST [inference-gateway]                   3.0s [error: *errors.errorString]
├── execute_tool Read call_2n68t2hm                                366µs
├── execute_tool Read call_ttqgfbqk                                180µs
├── execute_tool Read call_1ex4zwk9                                275µs
├── chat ollama_cloud/deepseek-v4-flash:preview                     3.8s
│   ╰── POST /v1/chat/completions [inference-gateway]               3.8s
│       ╰── HTTP POST [inference-gateway]                           3.8s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     3.8s
│               ╰── HTTP POST [inference-gateway]                   3.8s [error: *errors.errorString]
├── execute_tool Read call_g1ljtxtp                                182µs
├── execute_tool Read call_q9vf4fgv                                329µs
├── execute_tool Read call_3kiiib6y                                357µs
├── chat ollama_cloud/deepseek-v4-flash:preview                     3.8s
│   ╰── POST /v1/chat/completions [inference-gateway]               3.8s
│       ╰── HTTP POST [inference-gateway]                           3.8s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     3.8s
│               ╰── HTTP POST [inference-gateway]                   3.8s [error: *errors.errorString]
├── execute_tool Read call_1q445feg                                584µs
├── execute_tool Read call_pttrfnd4                                300µs
├── execute_tool Read call_ljt08vv5                                230µs
├── execute_tool Read call_30nkgz41                                234µs
├── chat ollama_cloud/deepseek-v4-flash:preview                     4.2s
│   ╰── POST /v1/chat/completions [inference-gateway]               4.1s
│       ╰── HTTP POST [inference-gateway]                           4.1s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     4.1s
│               ╰── HTTP POST [inference-gateway]                   4.1s [error: *errors.errorString]
├── execute_tool Read call_y6kr5cug                                166µs
├── execute_tool Read call_04biga1a                                158µs
├── execute_tool Read call_l1elh6v4                                152µs
├── execute_tool Read call_nlqh75fk                                143µs
├── chat ollama_cloud/deepseek-v4-flash:preview                    26.8s
│   ╰── POST /v1/chat/completions [inference-gateway]              26.8s
│       ╰── HTTP POST [inference-gateway]                          26.7s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]    26.7s
│               ╰── HTTP POST [inference-gateway]                  26.7s [error: *errors.errorString]
├── execute_tool Bash call_rdvhdr1i                                 1m9s
├── chat ollama_cloud/deepseek-v4-flash:preview                     4.2s
│   ╰── POST /v1/chat/completions [inference-gateway]               4.2s
│       ╰── HTTP POST [inference-gateway]                           4.2s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     4.2s
│               ╰── HTTP POST [inference-gateway]                   4.2s [error: *errors.errorString]
├── execute_tool Bash call_ahk7kibd                                40.6s
├── execute_tool Bash call_wzlnjj5q                                32.2s
├── execute_tool Bash call_zvyrwmaj                                35.8s
├── chat ollama_cloud/deepseek-v4-flash:preview                     7.6s
│   ╰── POST /v1/chat/completions [inference-gateway]               7.5s
│       ╰── HTTP POST [inference-gateway]                           7.5s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]     7.5s
│               ╰── HTTP POST [inference-gateway]                   7.5s [error: *errors.errorString]
├── execute_tool Bash call_5jh70dky                                 1.7s
╰── chat ollama_cloud/deepseek-v4-flash:preview                    18.4s
    ╰── POST /v1/chat/completions [inference-gateway]              18.4s
        ╰── HTTP POST [inference-gateway]                          18.3s [error: *errors.errorString]
            ╰── POST /proxy/:provider/*path [inference-gateway]    18.3s
                ╰── HTTP POST [inference-gateway]                  18.3s [error: *errors.errorString]
Stats
Tool Calls

╭──────┬───────┬───────┬─────────╮
│ Tool │ Calls │ Fail% │ Avg     │
├──────┼───────┼───────┼─────────┤
│ Read │ 20    │ 0%    │ 0ms     │
│ Bash │ 7     │ 0%    │ 25642ms │
╰──────┴───────┴───────┴─────────╯

Token Usage

╭────────────────────────────────────────┬────────┬────────┬────────────┬────────┬──────╮
│ Model                                  │ Prompt │ Cached │ Completion │ Total  │ Cost │
├────────────────────────────────────────┼────────┼────────┼────────────┼────────┼──────┤
│ ollama_cloud/deepseek-v4-flash:preview │ 683387 │ 0      │ 6737       │ 690124 │ -    │
╰────────────────────────────────────────┴────────┴────────┴────────────┴────────┴──────╯

Sessions

╭───────────┬──────────┬──────────╮
│ Execution │ Mode     │ Sessions │
├───────────┼──────────┼──────────┤
│ headless  │ headless │ 1        │
╰───────────┴──────────┴──────────╯

Triggered by edenreich · Infer Action · OSS

@edenreich
edenreich merged commit 4d68238 into main Aug 12, 2026
1 check passed
@edenreich
edenreich deleted the feat/scheduler-daemon-separation branch August 12, 2026 08:33
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.167.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Aug 12, 2026
edenreich added a commit to inference-gateway/operator that referenced this pull request Oct 31, 2026
…anager (#299)

The CLI renamed `infer channels-manager` to `infer daemon` in v0.167.0
(inference-gateway/cli#1051) with no alias, so every Orchestrator on a
current CLI image exited with an unknown command. The container now runs
`infer daemon`, which keeps reading the same INFER_CHANNELS_* and other
env vars.

Closes #296
inference-gateway-releaser Bot added a commit to inference-gateway/operator that referenced this pull request Oct 31, 2026
## [0.28.0](v0.27.1...v0.28.0) (2026-10-31)

### ✨ Features

* **orchestrator:** run the daemon in an agent-sandbox Sandbox with runtime: Sandbox ([#301](#301)) ([63386e2](63386e2)), closes [#298](#298)
* **orchestrator:** run the full infer daemon with optional channels and the AG-UI binding ([#300](#300)) ([fa7d927](fa7d927)), closes [#297](#297)

### 🐛 Bug Fixes

* **orchestrator:** run infer daemon instead of the removed channels-manager ([#299](#299)) ([62a6af7](62a6af7)), closes [#296](#296), references [inference-gateway/cli#1051](inference-gateway/cli#1051)

### 👷 CI

* **deps:** bump actions/setup-node ([#288](#288)) ([d98dcb2](d98dcb2))
* **deps:** bump docker/login-action ([#293](#293)) ([5f0cef1](5f0cef1))
* **deps:** bump github.com/onsi/ginkgo/v2 ([#289](#289)) ([03684df](03684df))
* **deps:** bump rancher/k3s ([#283](#283)) ([d58b0db](d58b0db))
* **deps:** bump sigs.k8s.io/controller-runtime ([#284](#284)) ([4dc8bc9](4dc8bc9))
* **deps:** bump sigs.k8s.io/gateway-api ([#287](#287)) ([262ff14](262ff14))
* **deps:** bump the github-actions group with 2 updates ([#290](#290)) ([cf4c07b](cf4c07b))
* **release:** label issues and PRs shipped in an rc with rc ([#295](#295)) ([25cac50](25cac50))

### 🔧 Miscellaneous

* **deps:** bump claude-code 2.1.285 -> 2.1.289 ([#285](#285)) ([5e36bc7](5e36bc7))
* **deps:** bump claude-code 2.1.289 -> 2.1.296 ([#291](#291)) ([eb53de2](eb53de2))
* **deps:** bump claude-code 2.1.296 -> 2.1.308 ([#294](#294)) ([025a54a](025a54a))
* **deps:** bump infer CLI v0.221.1 -> v0.226.0 ([#286](#286)) ([505d489](505d489))
* **deps:** bump infer CLI v0.226.0 -> v0.231.1 ([#292](#292)) ([490b5af](490b5af))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Allow Schedule tool create outside channel-driven sessions (local/desktop channel)

1 participant