Repository navigation
Conversation
Greptile SummaryThis PR introduces a first-class daily maintenance window for role isolation across the cron scheduler and heartbeat runner. When Key observations:
Confidence Score: 4/5Safe to merge after addressing the Date.now() vs now inconsistency in replayDeferredRuns and ideally adding a deferred queue cap; the cron-side changes and schema validation are solid. The core phase resolver, cron durable deferral, FIFO replay, and config schema are all well-implemented with targeted tests. The three flagged issues are P2: one is a test-reliability inconsistency (Date.now() vs now), one is a latent resource concern for long maintenance windows with high targeted-wake rates (unbounded queue), and one is a minor agent-ID fallback gap. None breaks the primary maintenance-window use case in production. src/infra/heartbeat-runner.ts — replayDeferredRuns and enqueueDeferredRun unbounded growth; src/cron/service/ops.ts — resolveJobAgentId fallback gap.
|
| Filename | Overview |
|---|---|
| src/infra/maintenance-phase.ts | New core module implementing phase resolution and agent allowlist checks; cross-midnight window arithmetic, timezone fallback chain, and the execution-decision function are all correctly implemented. |
| src/cron/service/timer.ts | Adds maintenance gating, durable deferred counters, and FIFO replay into the scheduler tick; logic is sound, though resolveJobAgentId in ops.ts is inconsistent with the DEFAULT_AGENT_ID fallback used here. |
| src/infra/heartbeat-runner.ts | In-memory deferred queue for heartbeat maintenance gating works correctly for interval wakes, but targeted wakes have no queue-size cap and the maintenance check inside replayDeferredRuns calls Date.now() instead of the passed now parameter, breaking fake-timer tests. |
| src/cron/service/ops.ts | Adds maintenance diagnostics to cron.status and a pre-flight maintenance block to cron.run; resolveJobAgentId lacks the DEFAULT_AGENT_ID fallback that timer.ts uses, causing a minor inconsistency for jobs without an explicit agent ID. |
| src/config/zod-schema.ts | Maintenance window schema added with correct superRefine cross-field validation (enabled → window required, start ≠ end, 24:00 only on end, IANA timezone probe). |
| src/gateway/config-reload-plan.ts | New cron.maintenance rule triggers both restart-cron and restart-heartbeat; ordering before the generic cron rule is correct so it takes precedence. |
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/infra/heartbeat-runner.ts
Line: 1043
Comment:
**`replayDeferredRuns` ignores its `now` parameter for the maintenance check**
Inside `replayDeferredRuns`, the `now` parameter is only used for `advanceAgentSchedule`, but the maintenance-phase gate calls `Date.now()` directly:
```typescript
if (!isMaintenanceAllowedForAgent(agent.agentId, Date.now())) {
```
This is inconsistent with the function signature and makes the replay loop untestable with fake timers — the deferred-replay scheduler tests (`heartbeat-runner.scheduler.test.ts`) rely on `vi.setSystemTime` to control time, but the guard inside `replayDeferredRuns` will always read the real wall clock.
```suggestion
if (!isMaintenanceAllowedForAgent(agent.agentId, now)) {
```
Using `now` here keeps the entire tick consistent and makes the function testable via `vi.setSystemTime`.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/infra/heartbeat-runner.ts
Line: 1028-1034
Comment:
**Unbounded deferred run queue for targeted heartbeat wakes**
For *targeted* wakes (`requestedSessionKey` / `requestedAgentId` path) every blocked wake unconditionally appends an entry to `agent.deferredRuns`. In the interval path each blocked due-tick advances the schedule, so queue growth is naturally capped to one entry per interval period. Targeted wakes have no such bound — anything calling `requestHeartbeatNow` repeatedly during the maintenance window (a cron job that fires many times, a webhook, repeated UI triggers) will grow the queue without limit. After the window ends, all queued entries replay serially, potentially causing a burst on the agent.
Consider adding a per-agent deferred queue cap in `enqueueDeferredRun` (e.g., drop the oldest entry when the queue exceeds a reasonable limit, or deduplicate entries with the same `sessionKey` before pushing).
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/cron/service/ops.ts
Line: 50-53
Comment:
**`resolveJobAgentId` in `ops.ts` lacks the `DEFAULT_AGENT_ID` fallback present in `timer.ts`**
`timer.ts` defines:
```typescript
function resolveCronJobAgentId(state: CronServiceState, job: CronJob): string {
return normalizeAgentId(job.agentId ?? state.deps.defaultAgentId ?? DEFAULT_AGENT_ID);
}
```
`ops.ts` defines:
```typescript
function resolveJobAgentId(state: CronServiceState, job: CronJob): string {
const fallback = normalizeAgentId(state.deps.defaultAgentId);
return normalizeAgentId(job.agentId) || fallback;
}
```
When both `job.agentId` and `state.deps.defaultAgentId` are absent, `ops.ts` resolves to an empty/falsy string while `timer.ts` falls back to `DEFAULT_AGENT_ID`. `resolveMaintenanceExecutionDecision` treats a falsy agent as never being a maintenance agent (`isMaintenanceAgent = false`). In maintenance-phase a job whose timer would be gated via `DEFAULT_AGENT_ID` would be blocked in manual runs with `"maintenance-blocked"` even though the scheduler wouldn't gate it the same way.
```suggestion
function resolveJobAgentId(state: CronServiceState, job: CronJob): string {
return normalizeAgentId(job.agentId ?? state.deps.defaultAgentId ?? DEFAULT_AGENT_ID);
}
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "feat(cron): add maintenance window role ..." | Re-trigger Greptile
| const errMsg = formatErrorMessage(err); | ||
| log.error(`heartbeat runner: runOnce threw unexpectedly: ${errMsg}`, { error: errMsg }); | ||
| return { status: "failed", reason: errMsg }; | ||
| } |
There was a problem hiding this comment.
replayDeferredRuns ignores its now parameter for the maintenance check
Inside replayDeferredRuns, the now parameter is only used for advanceAgentSchedule, but the maintenance-phase gate calls Date.now() directly:
if (!isMaintenanceAllowedForAgent(agent.agentId, Date.now())) {This is inconsistent with the function signature and makes the replay loop untestable with fake timers — the deferred-replay scheduler tests (heartbeat-runner.scheduler.test.ts) rely on vi.setSystemTime to control time, but the guard inside replayDeferredRuns will always read the real wall clock.
| } | |
| if (!isMaintenanceAllowedForAgent(agent.agentId, now)) { |
Using now here keeps the entire tick consistent and makes the function testable via vi.setSystemTime.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/heartbeat-runner.ts
Line: 1043
Comment:
**`replayDeferredRuns` ignores its `now` parameter for the maintenance check**
Inside `replayDeferredRuns`, the `now` parameter is only used for `advanceAgentSchedule`, but the maintenance-phase gate calls `Date.now()` directly:
```typescript
if (!isMaintenanceAllowedForAgent(agent.agentId, Date.now())) {
```
This is inconsistent with the function signature and makes the replay loop untestable with fake timers — the deferred-replay scheduler tests (`heartbeat-runner.scheduler.test.ts`) rely on `vi.setSystemTime` to control time, but the guard inside `replayDeferredRuns` will always read the real wall clock.
```suggestion
if (!isMaintenanceAllowedForAgent(agent.agentId, now)) {
```
Using `now` here keeps the entire tick consistent and makes the function testable via `vi.setSystemTime`.
How can I resolve this? If you propose a fix, please make it concise.| sessionKey?: string; | ||
| }): Promise<HeartbeatRunResult> => { | ||
| try { | ||
| return await runOnce({ | ||
| cfg: state.cfg, | ||
| agentId: params.agent.agentId, | ||
| heartbeat: params.agent.heartbeat, |
There was a problem hiding this comment.
Unbounded deferred run queue for targeted heartbeat wakes
For targeted wakes (requestedSessionKey / requestedAgentId path) every blocked wake unconditionally appends an entry to agent.deferredRuns. In the interval path each blocked due-tick advances the schedule, so queue growth is naturally capped to one entry per interval period. Targeted wakes have no such bound — anything calling requestHeartbeatNow repeatedly during the maintenance window (a cron job that fires many times, a webhook, repeated UI triggers) will grow the queue without limit. After the window ends, all queued entries replay serially, potentially causing a burst on the agent.
Consider adding a per-agent deferred queue cap in enqueueDeferredRun (e.g., drop the oldest entry when the queue exceeds a reasonable limit, or deduplicate entries with the same sessionKey before pushing).
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/heartbeat-runner.ts
Line: 1028-1034
Comment:
**Unbounded deferred run queue for targeted heartbeat wakes**
For *targeted* wakes (`requestedSessionKey` / `requestedAgentId` path) every blocked wake unconditionally appends an entry to `agent.deferredRuns`. In the interval path each blocked due-tick advances the schedule, so queue growth is naturally capped to one entry per interval period. Targeted wakes have no such bound — anything calling `requestHeartbeatNow` repeatedly during the maintenance window (a cron job that fires many times, a webhook, repeated UI triggers) will grow the queue without limit. After the window ends, all queued entries replay serially, potentially causing a burst on the agent.
Consider adding a per-agent deferred queue cap in `enqueueDeferredRun` (e.g., drop the oldest entry when the queue exceeds a reasonable limit, or deduplicate entries with the same `sessionKey` before pushing).
How can I resolve this? If you propose a fix, please make it concise.| nextOffset: number | null; | ||
| }; | ||
|
|
||
| function resolveJobAgentId(state: CronServiceState, job: CronJob): string { |
There was a problem hiding this comment.
resolveJobAgentId in ops.ts lacks the DEFAULT_AGENT_ID fallback present in timer.ts
timer.ts defines:
function resolveCronJobAgentId(state: CronServiceState, job: CronJob): string {
return normalizeAgentId(job.agentId ?? state.deps.defaultAgentId ?? DEFAULT_AGENT_ID);
}ops.ts defines:
function resolveJobAgentId(state: CronServiceState, job: CronJob): string {
const fallback = normalizeAgentId(state.deps.defaultAgentId);
return normalizeAgentId(job.agentId) || fallback;
}When both job.agentId and state.deps.defaultAgentId are absent, ops.ts resolves to an empty/falsy string while timer.ts falls back to DEFAULT_AGENT_ID. resolveMaintenanceExecutionDecision treats a falsy agent as never being a maintenance agent (isMaintenanceAgent = false). In maintenance-phase a job whose timer would be gated via DEFAULT_AGENT_ID would be blocked in manual runs with "maintenance-blocked" even though the scheduler wouldn't gate it the same way.
| nextOffset: number | null; | |
| }; | |
| function resolveJobAgentId(state: CronServiceState, job: CronJob): string { | |
| function resolveJobAgentId(state: CronServiceState, job: CronJob): string { | |
| return normalizeAgentId(job.agentId ?? state.deps.defaultAgentId ?? DEFAULT_AGENT_ID); | |
| } |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/cron/service/ops.ts
Line: 50-53
Comment:
**`resolveJobAgentId` in `ops.ts` lacks the `DEFAULT_AGENT_ID` fallback present in `timer.ts`**
`timer.ts` defines:
```typescript
function resolveCronJobAgentId(state: CronServiceState, job: CronJob): string {
return normalizeAgentId(job.agentId ?? state.deps.defaultAgentId ?? DEFAULT_AGENT_ID);
}
```
`ops.ts` defines:
```typescript
function resolveJobAgentId(state: CronServiceState, job: CronJob): string {
const fallback = normalizeAgentId(state.deps.defaultAgentId);
return normalizeAgentId(job.agentId) || fallback;
}
```
When both `job.agentId` and `state.deps.defaultAgentId` are absent, `ops.ts` resolves to an empty/falsy string while `timer.ts` falls back to `DEFAULT_AGENT_ID`. `resolveMaintenanceExecutionDecision` treats a falsy agent as never being a maintenance agent (`isMaintenanceAgent = false`). In maintenance-phase a job whose timer would be gated via `DEFAULT_AGENT_ID` would be blocked in manual runs with `"maintenance-blocked"` even though the scheduler wouldn't gate it the same way.
```suggestion
function resolveJobAgentId(state: CronServiceState, job: CronJob): string {
return normalizeAgentId(job.agentId ?? state.deps.defaultAgentId ?? DEFAULT_AGENT_ID);
}
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 236273db4e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ran = true; | ||
| } | ||
| scheduleNext(); | ||
| return ran ? { status: "ran", durationMs: Date.now() - startedAt } : res; |
There was a problem hiding this comment.
Return the targeted wake result instead of replay aggregate
When a targeted wake has deferred replays, ran is set from replay outcomes and this return path reports {status:"ran"} even if the current targeted runOnce call returns failed or a non-ran skip. In that case callers (including cron wake-now flows) can treat the request as successful and miss the actual failure for the newly requested wake. This happens whenever replay.ran === true and res.status !== "ran" in the same invocation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f306206927
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const agentId = normalizeAgentId(raw); | ||
| if (agentId) { |
There was a problem hiding this comment.
Skip invalid maintenance allowlist IDs instead of mapping to main
resolveMaintenanceAgentAllowlist currently feeds each configured entry through normalizeAgentId, which falls back to "main" for empty/invalid values. That means inputs like "", whitespace, or malformed IDs (for example "!!!", which passes current schema checks) silently add main to maintenanceAgents, unexpectedly blocking the default agent during normal phase and allowing it only in maintenance windows. This is a behavior regression that can shut off normal automation after a typo; invalid entries should be rejected or ignored rather than coerced to main.
Useful? React with 👍 / 👎.
| if (!isInterval || dueByInterval) { | ||
| enqueueDeferredRun(agent, { reason, queuedAtMs: now }); | ||
| } |
There was a problem hiding this comment.
Do not enqueue every non-interval wake for blocked agents
This branch defers blocked wakes whenever !isInterval, so any untargeted wake source (for example hook/exec/notification wakes) appends a deferred item even when the agent is not interval-due. In a busy environment with maintenance isolation enabled, blocked agents can accumulate large in-memory queues during normal hours and then replay a long backlog serially at window transition, causing avoidable memory growth and catch-up storms. Deferral should be coalesced or limited to interval-due/explicitly targeted wakes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: da2b103142
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (!nextAt) { | ||
| const deferredJobs = (state.store?.jobs ?? []).filter( | ||
| (job) => getDeferredMaintenanceRuns(job) > 0, | ||
| ); | ||
| const hasDeferredReplay = deferredJobs.some((job) => |
There was a problem hiding this comment.
Recheck deferred replays when next wake is in the future
armTimer only considers deferred-maintenance replay scheduling inside the if (!nextAt) branch, but deferred recurring jobs usually still have a finite nextRunAtMs (set by recordDeferredMaintenanceRun). In that case the timer is armed for that future schedule instead of rechecking maintenance phase transitions, so when a blocked job becomes allowed (for example after the maintenance window ends) replay can be delayed until the next cron slot rather than running promptly.
Useful? React with 👍 / 👎.
| prefix: "cron.maintenance", | ||
| kind: "hot", | ||
| actions: ["restart-cron", "restart-heartbeat"], | ||
| }, |
There was a problem hiding this comment.
Restart schedulers when maintenance uses user timezone
The new maintenance-phase gating depends on agents.defaults.userTimezone (buildGatewayCronService now snapshots it into cron deps, and heartbeat maintenance checks read cached config), but this reload plan only hot-restarts on cron.maintenance.*. A runtime change to agents.defaults.userTimezone with cron.maintenance.window.timezone: "user" leaves cron/heartbeat evaluating phase with stale timezone data until a full gateway restart.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9ce8f0f074
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for (const job of deferredJobs) { | ||
| const deferredRuns = getDeferredMaintenanceRuns(job); | ||
| for (let i = 0; i < deferredRuns; i += 1) { | ||
| scheduled.push({ |
There was a problem hiding this comment.
Preserve global FIFO when expanding deferred replay runs
The replay builder sorts only by each job’s firstDeferredMaintenanceAtMs and then appends all deferred runs for that job before moving to the next one. When a job has multiple deferred runs, this can execute newer runs ahead of older runs from other jobs (for example A1, B1, A2 becomes A1, A2, B1), which breaks the promised FIFO replay behavior and can starve other deferred jobs after long maintenance windows.
Useful? React with 👍 / 👎.
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. Close as superseded. The author documented that the fork branch for this PR cannot be updated and opened #74952 as the rebased replacement; public metadata shows that replacement is open with the same title, scope, and changed-file list. Current main still lacks the maintenance-window contract, so the remaining work should continue in the replacement PR rather than this stale branch. So I’m closing this here and keeping the remaining discussion on the canonical linked item. Review detailsBest possible solution: Close this stale, uneditable PR and continue all implementation review on #74952, where maintainers can resolve conflicts, evaluate the scheduler product semantics, address deferred replay issues, and validate the focused cron, heartbeat, schema, reload, protocol, docs, and CI surfaces. Do we have a high-confidence way to reproduce the issue? Not applicable as a user-facing bug reproduction. The supersession decision is high-confidence from the author’s replacement comment, matching PR metadata/file lists, and current-main checks showing the feature has not landed. Is this the best way to solve the issue? Yes. Closing the stale fork PR in favor of the open rebased replacement is the narrowest maintainable path; the code itself still needs normal PR review and fixes in #74952 before merge. Security review: Security review cleared: The diff touches CI secret scanning, but I found no concrete permission, secret exposure, dependency-source, or supply-chain regression in the proposed workflow changes. What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 914287642de5. |
|
Refresh note: current I did not push a partial resolution because that would risk overwriting newer scheduler/channel-kernel behavior. The next safe revision should rebase the maintenance-window implementation onto current |
|
Follow-up: this PR head is on a fork branch that I cannot update from the available credentials, so I published the rebased replacement from a writable fork as #74952. The previously reported Keeping this note public-safe: no local hostnames, tokens, account IDs, or runtime paths included. |
Summary
Adds a first-class daily maintenance window with hard role isolation and deferred replay across cron + heartbeat.
What changed
cron.maintenanceconfig:enabledwindow.startwindow.endwindow.timezonemaintenanceAgentsnormal | maintenance) used by both schedulers.cron.runhard-block on phase/role mismatch withmaintenance-blockedcron.statusdiagnostics for maintenance window/phase/deferred countscron.maintenance.*changes.Validation
./node_modules/.bin/oxfmt --check --threads=1 <touched-files>./node_modules/.bin/vitest run --config vitest.unit.config.ts src/infra/maintenance-phase.test.ts src/config/zod-schema.cron-maintenance.test.ts src/cron/service/timer.maintenance-window.test.ts src/cron/service.manual-run-maintenance.test.ts src/cron/service.status-maintenance.test.ts src/infra/heartbeat-runner.scheduler.test.ts src/gateway/config-reload.test.tsCannot find package '@mariozechner/pi-ai/oauth' imported from src/agents/auth-profiles/oauth.tsNotes
--no-verifybecause local pre-commit hooks invokepnpm, which was unavailable on PATH in this run context.