Skip to content

fix(cron): session-target automations fail on PostgreSQL state before they start - #187530

Merged
obviyus merged 3 commits into
openclaw:mainfrom
yousan:fix/cron-session-run-async-store-path-187334
Oct 29, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
yousan:fix/cron-session-run-async-store-path-187334

Conversation

@yousan

@yousan yousan commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #187334

What Problem This Solves

Session-target automations can fail before their agent turn starts when the Gateway uses PostgreSQL shared state and has no explicit cron store path. Prompt preparation calls the synchronous partition resolver on the Gateway thread, triggering PostgreSQL connections must run in a worker.

What Changed

Await the existing async worker resolver in session-target scratch preparation and standalone automation prompt preparation. Keep the existing prepared-scratch and explicit-path fast paths. No new store, database opener, schema, migration, partition-selection rule, retry or permission change; unrelated Doctor and one-shot callers are untouched.

Original fix: @yousan. Report: @etzelm in #187334. Contributor commits are preserved.

Evidence

Clean exact-head built Gateway + real PostgreSQL proof: a separate PostgreSQL 17.8 Docker server holds actual shared-state schemas and cron receipts; agents use SQLite. Jobs are created and forced through shipped Gateway RPC, with real local provider HTTP requests and persisted target-session replies.

  • Main session-target jobs fail twice before inference; candidate jobs succeed twice with exactly one normal turn each.
  • The same comparison passes against a non-default machine-selected partition. Native PG cron_run_receipts.store_key confirms the selected partition is retained.
  • SQLite session-target controls and no-target isolated controls succeed on both refs.
  • Legacy explicit override precedence is checked through the existing resolver contract. Current Gateway JSON correctly rejects the retired cron.store field; validation was not bypassed.

30/30 focused tests and formatting passed. Existing coverage now checks worker-owned selected-path resolution, preserved localized prompt content, prepared scratch without re-reading it, cancellation, source revocation and retained authority. Net test-count growth zero; production +4/-4 and test lines +50/-16.

Merge Danger

Two-way door: reverting restores synchronous metadata lookups. No persisted-format or schema change. Blast radius is cron prompt preparation when scratch is not already prepared; the async resolver already owns partition selection for both engines.

… they start

Without an explicit cron.store, session-target runs (and standalone
isolated prompt preparation) resolved the cron partition with the
synchronous machine-state read on the Gateway main thread. PostgreSQL
state refuses that ("PostgreSQL connections must run in a worker"), so
the run failed before enqueueing its turn. Resolve the partition with
the existing worker-backed async resolver instead.

Closes openclaw#187334

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01StYtJ4UGDrdH1BXUySJXmR
@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-29T09:03:31.518854Z
We couldn’t complete this review. Comment @codex review to try again.
bedbf22 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 29, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 29, 2026
@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Use the existing worker-backed async partition resolver when preparing automation scratch.

Example: A PostgreSQL-backed Gateway runs an automation targeting session:agent:main:proof187530 without prepared scratch.

  • Before: Partition lookup fails with “PostgreSQL connections must run in a worker” before inference.
  • After: The automation completes one model turn and saves its reply in the target session.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused repair with shipped Gateway proof, preserved storage contracts, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Exact-head terminal evidence exercises built Gateway cron RPC with real PostgreSQL shared state and a local HTTP model fixture, recording successful target-session replies for default and selected partitions plus SQLite controls; it satisfies the prior review's requested PostgreSQL proof.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Scheduled conversation follow-ups fail before their agent turn starts on PostgreSQL shared state.
Reason: This restores defined session-target behavior without adding configuration, storage, permissions, or another execution owner.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current PostgreSQL automation failure with a focused change; no actionable defects remain, and normal CI is still pending.

Priority: P1
Reviewed head: 1fe863ad4ea50b5ea2069e88f3b0899cdc95ac09

Before merge

None.

Findings

None.

Agent review details

How this fits together

Cron prepares job instructions and scratch before submitting a turn to the session controller; shared-state workers resolve the selected cron partition.

flowchart LR
  A[Scheduled automation] --> B[Prompt preparation]
  B --> C[Async partition resolver]
  C --> D[Shared state worker]
  D --> E[Scratch snapshot]
  E --> F[Session controller]
  F --> G[Target conversation]
Loading

Technical review

Best possible solution:

Land the existing async-resolver substitution after the normal exact-head CI gates pass.

Do we have a high-confidence way to reproduce the issue?

The supplied Gateway comparison reproduces the precise pre-inference PostgreSQL failure on main, and fetched-main source retains the responsible synchronous calls; this review executed no target code.

Is this the best way to solve the issue?

The patch is the smallest complete repair: reuse the existing worker resolver in both affected async owners while retaining partition precedence, scratch bypasses, and current-authority checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against c6999b9ffb17.

Provenance checked

  • Session-target scratch preparation keeps the original intent (ec5d369: The automation migration placed scratch preparation under the ordinary session controller while preserving notices and retained execution authority.)
  • Standalone and selected-partition prompt preparation keeps the original intent (691a3e1: The prior optimization carried the Gateway-selected partition while preserving standalone configuration-based selection and separate session storage.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source 0, Tests +34. Total +34 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 4 4 0
Tests 2 50 16 +34
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 54 20 +34

Review metrics

Metric Value Why it matters
Production versus test LOC Production +4/-4; tests +50/-16 Production remains a two-call substitution; test growth extends existing cases to protect worker-owned lookup, selected partitions, and prepared scratch.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Session-target automations on PostgreSQL shared state fail before execution, preventing scheduled follow-ups.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-29T09:16:44.707Z sha bedbf22 :: needs real behavior proof before merge. :: none

Reviewed October 29, 2026, 6:05 AM ET / 10:05 UTC (Revision 2).

@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Clean exact-head PostgreSQL Gateway proof

Candidate 1fe863ad4ea50b5ea2069e88f3b0899cdc95ac09, clean tree fd15382cffea7f0e6051d1f60613a6b13d168bea; baseline main 1e11b88f4e28de99fd4cda7221246fa3bc0f5a17. Complete clean Git archives were built inside secretless node:24.22.1 Docker. Contributor commit bedbf220 is preserved; added commits consolidate and strengthen existing tests only.

The Gateway uses the documented mixed-engine config: database.engine=sqlite, database.families.state.engine=postgres, and a PostgreSQL connection env SecretRef. Agent stores remain SQLite. A separate real Docker server runs PostgreSQL 17.8, with unaccent, pg_trgm and vector, on a task-only network with no published host port. The model is a deterministic local HTTP fixture, not a paid upstream.

Through the built CLI and real Gateway RPC:

  1. chat.send creates the target session, returns started plus a run ID, and agent.wait observes completion.
  2. cron.add creates real interval jobs targeting session:agent:main:proof187530.
  3. cron.run forces and waits for each run; cron.runs reads its persisted outcome.
  4. Actual provider HTTP requests, run summaries and target chat.history confirm execution and routing. No scratch is preloaded into the target jobs.

Observed results:

backend / selection       main target 1  main target 2  candidate target 1  candidate target 2
PostgreSQL / default      error, 0 HTTP  error, 0 HTTP  ok, 1 HTTP          ok, 1 HTTP
PostgreSQL / selected      error, 0 HTTP  error, 0 HTTP  ok, 1 HTTP          ok, 1 HTTP
SQLite / default          ok, 1 HTTP     ok, 1 HTTP     ok, 1 HTTP          ok, 1 HTTP

No-target isolated control: ok, one normal model turn on both refs in all six runs.

Main's PostgreSQL target failures are the specific pre-turn error:

Cannot open PostgreSQL connection: PostgreSQL connections must run in a worker;
only synchronous admission, migrations, and CLI one-shots may run on the main thread...

Both candidate target runs record their exact PROOF187530_TARGET1 / TARGET2 reply markers and commit them into the requested session's history. There are no extra or misrouted model turns.

The selected-partition setup writes only the existing cron.store machine-state key through writeConfigMachineStateAsync before Gateway startup. The Gateway JSON still has no cron.store override. Native PostgreSQL queries confirm the real backend and selected partition:

baseline selected task_runs:  failed=2, succeeded=1
candidate selected task_runs: succeeded=3

baseline cron_run_receipts.store_key = <baseline>/selected-partition/jobs.json
  error=2, ok=1
candidate cron_run_receipts.store_key = <candidate>/selected-partition/jobs.json
  ok=3

The PG server's actual application tables—not a status label—hold these rows. cron.status retains a historical storage=sqlite label even with PG state; that label is not used as backend evidence.

Controls and limits: current Gateway JSON correctly rejects the retired cron.store config field. I did not disable validation or alter its schema. Explicit legacy override precedence is checked through the existing sync/async resolver contract on the real PG fixture; both return the same explicit path instead of the machine-selected path. Existing standalone prompt coverage verifies worker-owned lookup with fresh scratch revisions. The prepared-scratch fast path supplies its original content without re-reading scratch. Cancellation, source revocation and retained-authority cases remain passing. No Doctor or unrelated one-shot caller is changed.

Root cause and fix: two async prompt owners still called the synchronous partition resolver on their caller thread. Await the existing async worker resolver instead. Partition choice, stores, schemas, migration, retry and authority contracts are unchanged; there is no new DB opener or helper.

Focused verification: 30/30 tests passed in session-run.test.ts and scratch-store.test.ts; formatting passed on all four changed TypeScript files. The added worker-resolution case is folded into existing localized-prompt coverage, with the prepared-scratch control retained in that same owner case: net test-count growth 0. Production +4/-4; test lines +50/-16.

Original fix: @yousan. Report: @etzelm in #187334. No merge performed.

@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026
@obviyus
obviyus merged commit 6630db1 into openclaw:main Oct 29, 2026
145 of 146 checks passed
@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Landed in 6630db1. Thanks @yousan. Cron session-target jobs now run on PostgreSQL-backed Gateways.

github-actions Bot pushed a commit to SebbeBengtsonSebbeBengtson1528/openclaw that referenced this pull request Oct 29, 2026
… they start (#187530)

fix(cron): use the async partition resolver for session-target runs on PostgreSQL

Cron runs with a session target, and standalone runs, prepared their session with the synchronous partition resolver. A Gateway that keeps shared state in PostgreSQL can't resolve partitions synchronously, so these jobs failed with a worker-thread error before inference. They now use the existing async worker resolver that already owns this path. No store or schema changes.

Evidence: built Gateway with PostgreSQL 17.8 shared state and SQLite agents. On main, session-target jobs failed before inference with the worker-thread error (twice); with this change they completed with one provider request and the reply stored in the correct target session (twice), including on a custom partition, which PostgreSQL store_key receipts confirm. SQLite and no-target controls behave the same on both refs. Details: openclaw/openclaw#187530 (comment).

Thanks @yousan.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 30, 2026
… they start (openclaw#187530)

fix(cron): use the async partition resolver for session-target runs on PostgreSQL

Cron runs with a session target, and standalone runs, prepared their session with the synchronous partition resolver. A Gateway that keeps shared state in PostgreSQL can't resolve partitions synchronously, so these jobs failed with a worker-thread error before inference. They now use the existing async worker resolver that already owns this path. No store or schema changes.

Evidence: built Gateway with PostgreSQL 17.8 shared state and SQLite agents. On main, session-target jobs failed before inference with the worker-thread error (twice); with this change they completed with one provider request and the reply stored in the correct target session (twice), including on a custom partition, which PostgreSQL store_key receipts confirm. SQLite and no-target controls behave the same on both refs. Details: openclaw#187530 (comment).

Thanks @yousan.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: one-shot session-target automations fail with "PostgreSQL connections must run in a worker" on PostgreSQL state

2 participants