mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
## 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
38 lines
2.8 KiB
JSON
38 lines
2.8 KiB
JSON
{
|
|
"$comment": "Per-file Vitest durations (ms) for server/src/__tests__/chat-channels/*.integration.test.ts used by scripts/run-vitest-stable.mjs (--group general-chat) to balance file-level shards via LPT. Refreshed from 8-core PR run 45592683902 with the 4-way split of github-review-workflow.integration.test.ts. Missing files take the partitioner's median weight. Timing changes only partition work; they never skip a test.",
|
|
"unit": "ms",
|
|
"sources": [
|
|
"github-actions:45592683902@57638686dc"
|
|
],
|
|
"coverage": {
|
|
"measured": 24,
|
|
"inventory": 24
|
|
},
|
|
"durations": {
|
|
"server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts": 62795,
|
|
"server/src/__tests__/chat-channels/discord-command-registration.integration.test.ts": 12500,
|
|
"server/src/__tests__/chat-channels/discord-gateway-lease.integration.test.ts": 7200,
|
|
"server/src/__tests__/chat-channels/discord-modals-and-publications.integration.test.ts": 36248,
|
|
"server/src/__tests__/chat-channels/discord-setup-and-commands.integration.test.ts": 72200,
|
|
"server/src/__tests__/chat-channels/github-lifecycle-and-revocation.integration.test.ts": 17500,
|
|
"server/src/__tests__/chat-channels/github-retry-and-recovery.integration.test.ts": 67500,
|
|
"server/src/__tests__/chat-channels/github-review-finding-threads.integration.test.ts": 57428,
|
|
"server/src/__tests__/chat-channels/github-review-publications.integration.test.ts": 28492,
|
|
"server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts": 34444,
|
|
"server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts": 58821,
|
|
"server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts": 62020,
|
|
"server/src/__tests__/chat-channels/github-webhook-recovery.integration.test.ts": 52606,
|
|
"server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts": 12547,
|
|
"server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts": 45584,
|
|
"server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts": 94522,
|
|
"server/src/__tests__/chat-channels/slack-protocol.integration.test.ts": 17846,
|
|
"server/src/__tests__/chat-channels/slack-setup-and-registration.integration.test.ts": 91332,
|
|
"server/src/__tests__/chat-channels/teams-authority-and-transfer.integration.test.ts": 70577,
|
|
"server/src/__tests__/chat-channels/teams-ingress-and-media.integration.test.ts": 57795,
|
|
"server/src/__tests__/chat-channels/telegram-drafts-and-progress.integration.test.ts": 59100,
|
|
"server/src/__tests__/chat-channels/telegram-first-seen-controls.integration.test.ts": 27400,
|
|
"server/src/__tests__/chat-channels/telegram-ingress-and-callbacks.integration.test.ts": 43737,
|
|
"server/src/__tests__/chat-channels/telegram-media-and-recovery.integration.test.ts": 52158
|
|
}
|
|
}
|