Files
PaperClipAI/server
DottaandClaude Opus 5.5 ea8c734cb9 fix(chat): park GitHub terminal responses that wait for a newer run or task change (#21705)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The GitHub chat channel posts one App-owned response comment per
accepted request. The terminal-response sweep
(`terminal-response-work.ts`) finds processed, non-final responses whose
task's latest run has ended, and asks the acknowledgement owner to post
the final text.
> - On paperclip.staging, 1,557 processed `github_response_comment` rows
are not final. None changed in the last 5 minutes, and the oldest dates
from 2026-10-28. The sweep reads all of them again on each company-wide
rebuild (every 30 s per company), with one page read plus three
statements per row. Two of those statements run at about 13/s each in
`pg_stat_statements`.
> - The sweep cannot make progress on these rows. Their task's latest
run ended without owning the request (a later request started it), or
the pause is already shown. Nothing that the decision reads changes
until a new run starts, the task status changes, or the row changes.
> - This pull request records that wait on the row and skips it on broad
rebuilds until one of those inputs changes.
> - The benefit is that an idle backlog costs one page read per rebuild
instead of about three statements per row, and no request loses a path
to settle.

## Linked Issues or Issue Description

No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.

**What happened?**

On paperclip.staging (2026-11-15, about 01:45–02:25Z), two single-row
statements ran at nearly the same rate:

- `select id, run_id, company_id, status, responsible_user_id,
message_id, parent_context_id from run_identity_contexts where id = $1
and run_id = $2 and company_id = $3 and status = $4 limit $5` at
13.37/s.
- `select chat_conversations.issue_id, chat_endpoints.provider from
chat_message_links join chat_conversations … join chat_endpoints … where
chat_message_links.company_id = $3 and comment_id = $4 …` at 13.20/s.

They are `provenanceReads.context` and `provenanceReads.link` in
`run-origin.ts`. The terminal-response sweep reaches them through
`readGitHubResponseRun` for each row it loads.

The backlog of `github_response_comment` actions on staging:

- `processed`, `delivery_id` set, `result.final` not `true`: 1,557 rows
(the terminal sweep's set). None updated in the last 5 minutes. The
oldest `updated_at` is 2026-10-28.
- `result.code` of those rows: null 1,387, `acknowledgement_unconfirmed`
150, `acknowledgement_superseded` 20.
- The acknowledgement set (`received`, or `failed` and retryable) is
empty.
- Other rows: processed and final 6,645, failed and not retryable 265,
cancelled 116.

**Root cause**

`entry()` returns `null` ("nothing to post now") when
`githubResponseExecution` has no body. That happens when the task's
latest run has ended but does not own the request and the task is not
blocked. It also happens when the task is blocked and the row already
shows this pause (`pausedVersion` matches). The page query still selects
these rows, because the latest run has ended (or the task is blocked)
and the row is not final. Nothing records the decision, so each
company-wide rebuild reads every row again: `readGitHubResponseRun` (one
statement) plus `chatRunSourceMessageId` (the context and link reads)
for each row. The codes do not matter. `acknowledgement_unconfirmed` is
a retry code that a later successful acknowledgement keeps, and
`acknowledgement_superseded` marks a request whose shared PR comment has
a newer version. All three groups wait for the same thing: a newer run
that owns the request, or a task status change.

**Expected behavior**

A response that cannot progress costs nothing until the run, the task or
the response changes. A response that can progress settles as before.

**Steps to reproduce**

1. Create a GitHub endpoint and a task with several processed, non-final
response comments (codes null, `acknowledgement_unconfirmed`,
`acknowledgement_superseded`).
2. Give the task a newer ended run whose identity context names a later
request, so the run does not own the older requests.
3. Register the terminal-response sweep and send a company-wide hint
every 30 s.
4. On master, each rebuild reads every row again with about three
statements per row and writes nothing.

**Paperclip version or commit**

master at 958eda6f16.

## What Changed

- `server/src/services/chat-channels/github/terminal-response-work.ts`:
- The page query reads the task's latest run through one lateral
subquery. The subquery returns the run status (for the existing filter)
and a run version (id, status, `updated_at`). The run-index union and
its filters are unchanged.
- A wait key joins the run version, the task status and the row's
`updated_at`.
- When `entry()` decides that a row has nothing to post, the sweep
records `result.terminalWaitKey` in one batched update per page. The
update writes only if the row has not changed since the read, and it
leaves `updated_at` alone, because the key includes it.
- A broad load (every company, or one company with no narrower scope)
skips rows whose stored key equals the current key. Targeted loads
(task, delivery, conversation, endpoint, repository or number) and
`check()` still read every matching row.
- Only waits that do not depend on the owning run's reply are recorded:
the latest run does not own the request, or the pause is already shown.
A request that waits for its owning run's reply publication or native
presentation is never parked, because a publication commit changes none
of the key's inputs and a restart can lose its lease-release hint. Those
requests stay eligible for every broad load, as on master.
- `check()` records the key too when its revalidation finds nothing to
post.
-
`server/src/services/chat-channels/github/terminal-response-work.test.ts`
(new, real PostgreSQL), with staging-shaped fixtures: 30 tasks with 4
waiting responses each (codes null 89%, `acknowledgement_unconfirmed`
10%, `acknowledgement_superseded` 1%), and a newer ended run per task
that answered a later request:
- `stops re-reading processed, non-final responses that cannot progress
on every company rebuild`
  - `still settles a waiting response once a run that owns it ends`
  - `still pauses waiting responses once their task is blocked`
- `still settles a response after a restart lost the hint of the reply
publication it waited for` (an owning run's formal review is
`processing`; it commits with no hint; after a coordinator restart the
broad load acknowledges the request)
- `server/src/__tests__/chat-channels.integration.test.ts`: `finds owed
terminal GitHub work beyond a full page of unrelated request history`
now expects the 101 retained requests to carry a wait key in addition to
their code.

No GitHub comment is edited, posted or deleted by this change.
User-visible behavior is the same: a waiting request keeps its current
comment until a run that owns it ends or its task is blocked, as before.

## Verification

- `pnpm vitest run
src/services/chat-channels/github/terminal-response-work.test.ts`
(server):
- master: 2 of 3 fail (red). The first pass costs 362 statements for 120
rows (2 page reads + 3 per row). Four company rebuilds cost 1,448
statements, with 480 run identity reads, and write nothing.
- this branch: 4 of 4 pass (green). The first pass costs 364 statements
(the same reads plus 2 batched wait-key writes). Four company rebuilds
cost 4 statements (one page read each) and 0 run identity reads. An
owning run and a blocked task still settle their requests.
- The restart test fails on the first revision of this PR (no
acknowledgement) and passes now.
- `pnpm vitest run
src/services/chat-channels/github/terminal-response-work.test.ts
src/__tests__/chat-channels.integration.test.ts -t
"terminal|acknowledg|GitHub response|…"`: 193 passed.
- `pnpm typecheck` (server): passed.
- `pnpm verify` selected 2,738 of 3,565 test files ("retained
conservatively"), close to the full suite. I stopped it and relied on
the focused runs above plus required CI, per AGENTS.md. Before I stopped
it, two unrelated files failed locally:
`agent-commentary-skills.test.ts` (a local skills file is missing,
ENOENT) and one test in `agent-lifecycle/lifecycle.test.ts` (it passes
in isolation).

## Risks

- The wait key must change whenever a skipped row could progress. Its
inputs are the latest run (id, status, `updated_at`), the task status
and the row version. Run writers set `updated_at`, and the publication
lease sends a targeted hint that bypasses the key. A missed input delays
a final comment until the run, the task or the row next changes. It does
not lose the request.
- The first rebuild after deploy still reads the whole backlog once, and
writes one key update per page. The next PR batches those reads.
- `result` gains one internal key, `terminalWaitKey`. Writers that copy
`result` forward also set `updated_at`, which invalidates a copied key.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, local PostgreSQL tests) and
extended reasoning.

## 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
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

Related: #21674, #21675, #21676 (same class: a read loop that makes no
progress).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:40:39 -06:00
..