Files
PaperClipAI/server
Dotta 84ca111c78 fix(slack): align form publication wait backoff with enrollment deadlines (#23819)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Slack chat channels deliver interactive question forms that depend
on Cloud events and form-owner enrollment before Paperclip posts the
prompt.
> - When enrollment is pending and backed off for 60s to 300s,
`createSlackFormPublicationStage` returns a hardcoded `retryAfterMs:
2_000` wait instead of reading the enrollment `nextAttemptAt` deadline.
> - That hardcoded 2-second wait makes the publication worker claim
leases, run 20 to 30 SQL queries, emit `chat publication failed`
warnings every few seconds, and keep `chat_endpoint_leases` hot while
blocking idle sleep.
> - This pull request derives the publication wait delay from the
pending `slackCloudIntent` or `slack_form_owner` deadline (bounded to
`[2_000 ms, 300_000 ms]`), clears waiting publication deadlines and
notifies `chatPublications` whenever enrollment commits, retires, or
enters `attention`, rechecks wait state via a shared predicate inside a
savepoint (`FOR SHARE NOWAIT`) in the deferral transaction, and logs
pre-send waits at debug level.
> - The benefit is cutting a 5-minute enrollment wait from ~100–150
publication/lease cycles to 1 while preserving immediate wake on early
enrollment completion or attention settlement.

## Linked Issues or Issue Description

**What happened?**
A Slack form publication waiting on
`form_publication_enrollment_pending` loops every ~2–3 seconds and logs
`chat publication failed` warnings continuously while enrollment is
backed off for up to 300 seconds. Each tick claims and deletes
`chat_endpoint_leases`, writes `chat_publications`, and prevents the
worker from going quiet.

**Expected behavior**
A Slack form publication waiting on pending enrollment schedules its
`nextAttemptAt` to match the pending `slackCloudIntent.nextAttemptAt` or
`slack_form_owner.result.nextAttemptAt` deadline (with a 2-second floor
for past/due deadlines and a 300-second cap), emits a debug log rather
than a failure warning, and wakes immediately when enrollment commits
early, retires, or transitions to `attention`.

**Steps to reproduce**
1. Configure a Slack endpoint with managed Cloud forms and a pending
`slackCloudIntent` or staged `slack_form_owner` backed off 60s–300s in
the future.
2. Create an `ask_user_questions` interaction with a Slack form prompt
(`question_form_open`) on an active Slack conversation.
3. Run the `chatPublications` delivery worker and observe
`chat_publications.next_attempt_at` and server logs.

**Paperclip version or commit**
Reproduced on `master` prior to
`0c0cd68c711da5ebdb0cbaf5a2d54bc96faca7c4`.

**Deployment mode**
Self-hosted server

## What Changed

- **`server/src/services/chat-channels/slack/form-publication.ts`**:
Extract single-source-of-truth `pendingIntentDeadline` and
`pendingOwnerDeadline` helpers used by both the main readiness gate and
the `stillWaiting(tx)` recheck. Compute `retryAfterMs` from the actual
pending deadline clamped to `[2_000 ms, 300_000 ms]`. Use `FOR SHARE
NOWAIT` in `stillWaiting(tx)` so the recheck never blocks on concurrent
enrollment updates.
- **`server/src/services/chat-channels/publications/preparation.ts` &
`publications/failures.ts`**: Extend `ChatPublicationPreparationWait`
with an optional platform-agnostic `stillWaiting?: (tx: DbTransaction)
=> Promise<boolean>` callback. Execute `stillWaiting` inside a
PostgreSQL savepoint (`tx.transaction(...)`): if `stillWaiting` returns
`false`, commit `nextAttemptAt = null` so an enrollment commit racing
deferral wakes immediately; if `stillWaiting` hits lock contention
(`NOWAIT`) or a transient error, roll back only the savepoint and commit
`state = "retry"` with a `<= 2_000 ms` fallback so a benign pre-send
wait can never stay `streaming` and become `delivery_unknown`. Log
`waitingBeforeSend` deferrals at `logger.debug(..., "chat publication
waiting before send")` instead of `logger.warn(..., "chat publication
failed")`.
- **`server/src/services/chat-channels/slack/form-owner.ts` &
`cloud-enrollment.ts`**: Add
`clearWaitingSlackFormPublicationDeadlines(tx, endpoint)` and register
`notifyChatPublicationWork(tx)` before writes across every enrollment
resolution/retirement/attention transition
(`reconcileSlackFormEnrollment`, `stageSlackFormEnrollment` for an
already-enrolled owner, `stageSlackFormOwnerConfiguration` deactivation,
`reconcilePendingSlackFormWork` permanent `attention`,
`stageSlackCloudEnrollmentIntent` inactive/attention staging, and
`createSlackCloudEnrollment` `intent_authority_changed` / `attention` /
retirement commits).
- **Tests & CI timing manifests**: Extended
`server/src/__tests__/slack-cloud-forms.test.ts` and
`server/src/services/chat-channels/slack/cloud-enrollment.test.ts`,
added a focused real embedded-PostgreSQL suite in
`server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts`
(641 lines; keeping `slack-protocol.integration.test.ts` untouched at
726 lines), and registered its measured 8-core CI timing (`12547 ms`) in
`scripts/chat-shard-durations.json` and
`scripts/general-server-shard-durations.json`.

### Sleep-Aware Background Work Contract

- **Trigger**: Shared `DELIVERY_QUEUES.chatPublications`
transaction-aware work signals (`notifyChatPublicationWork`) and saved
per-row `chat_publications.next_attempt_at` deadlines read by
`nextPublicationAt()`.
- **Durable source of truth**: `chat_publications` (`state`,
`next_attempt_at`, `attempts`, `redacted_error`), `chat_endpoints.setup`
(`slackCloudIntent`, `slackCloudForms`), and `chat_actions`
(`slack_form_owner`).
- **Pending-work predicate**: `publicationEligibility()` selects
`chat_publications` in `pending`/`retry` whose `next_attempt_at` is
`null` or due (`<= now`) on active/verifying endpoints.
- **Next deadline/retry**: `nextAttemptAt` tracks `clamp(2_000, 300_000,
enrollmentDeadline - now)` while enrollment is scheduled, is cleared to
`null` when enrollment completes, retires, or enters `attention` (or
when `stillWaiting(tx)` sees enrollment already settled), and falls back
to `<= 2_000 ms` if `stillWaiting` encounters lock contention.
- **Quiet condition**: Once waiting publications defer to the enrollment
deadline (up to 300s), no publication sweep or lease write runs until
either that deadline arrives or an enrollment producer commits a state
change; once enrollment resolves, publications publish or settle to
`failed`/`cancelled` and `nextPublicationAt()` returns `null`.

## Verification

Verified on commit `a75b654d3d75f9b36f860b0793baa94f5811fdac`:

- Reproduced pre-fix RED failures before applying the fix: unit tests
confirmed hardcoded `2000 ms` waits for 60s/300s deadlines and missing
publication wake on `slackCloudIntent` attention; real PostgreSQL tests
confirmed 2s `nextAttemptAt` scheduling, `chat publication failed` warn
logs, and 5-minute stranding on the concurrent commit race.
- `pnpm check:module-boundaries` — PASS.
- `node scripts/check-test-budget.mjs --base origin/master` — PASS (113
nightly suites validated, 3 test files checked).
- `node --test ./scripts/__tests__/run-vitest-stable-shard.test.mjs
./scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
./scripts/ci/test-selection-pr-timings.test.mjs
./scripts/check-test-budget.test.mjs
.github/scripts/tests/ci-dependency-cache.test.mjs` — PASS (79/79
tests).
- `pnpm --filter @paperclipai/server typecheck` — PASS (all 7 typecheck
layers green; unchanged server sources since `459443a36a`).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/slack-cloud-forms.test.ts
src/services/chat-channels/slack/cloud-enrollment.test.ts
src/services/chat-publication-errors.test.ts
src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts`
— PASS (4 test files, 106/106 tests passed; unchanged server sources
since `459443a36a`).
- Scope note: Local tests verify worker quiet, durable deadlines, and
PostgreSQL reactivation; they do not by themselves prove deployed host
suspension or fleet cost reduction.

## Risks

- Low risk; no database schema or migration changes are introduced.
- Lock ordering stays acyclic (`chat_endpoint_leases` ->
`chat_endpoints` -> `chat_actions` -> `chat_publications`), and
`stillWaiting(tx)` uses `FOR SHARE NOWAIT` inside a PostgreSQL savepoint
so lock contention can neither block nor abort publication finalization.
- `clearWaitingSlackFormPublicationDeadlines` only clears
`next_attempt_at` on `state = 'retry'` rows with `redacted_error =
'form_publication_enrollment_pending'` for the affected `(company_id,
endpoint_id)`, verified by test to leave unrelated provider rate-limit
backoffs untouched.
- Process-local transaction notifications cover supported application
writers; startup reconstruction and the bounded 300s ceiling still
recover any external or out-of-band state change.

## Model Used

Gemini 4 Neon (Google DeepMind, XHigh reasoning, with tool use and code
execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-04 20:37:16 -06:00
..