Michael Suchacz 1c722ff969 fix(coderd/database): order the chat prompt query and its boundary by id (#27619)
## Stack context

Follows #27495 (merged), which gives `chat_messages.id` an append-order
guarantee and moves the history reads onto it. This PR applies the same
fix to the query that builds the model prompt.

## Why?

`GetChatMessagesForPromptByChatID` mixed two orderings. It selected the
compaction boundary with `created_at DESC, id DESC`, then applied that
boundary with an `id >` comparison, and returned rows with `created_at
ASC, id ASC`.

`created_at` is `now()`, so it is the transaction start time. Every row
in one insert batch shares it, and concurrent transactions can commit in
the opposite order to the one they started in. Two consequences, both
reaching the provider:

- **Malformed prompts.** A tool result could be ordered ahead of the
assistant message that requested it.
`chatprompt.injectMissingToolResults` does not repair this: it only
handles tool rows already contiguous after an assistant row, and adds
missing results. It never moves a tool row that precedes its assistant,
and nothing re-sorts the rows in Go.
- **Wrong compaction boundary.** The boundary is picked by timestamp but
compared by id, so a stale compressed summary could be retained while
the actual latest one was dropped.

## Changes

Both the boundary CTE and the outer query order by `id`. The `id >`
predicate is unchanged, which is the point: the ordering now matches the
comparison that was always being made.

**The boundary index was dead, so it is rebuilt to match.**
`idx_chat_messages_compressed_summary_boundary` was created for exactly
this lookup, but its predicate requires `role = 'system'` while
compaction writes its summary with the user role
(`message_conversion.go:334`, the only writer of `compressed = true`).
It matched zero rows, and no other query can use it. Migration `000560`
rebuilds it as `(chat_id, id DESC) WHERE compressed AND NOT deleted AND
visibility = 'model'`, which also matches the new order key.

Measured on PostgreSQL 13 with a 20k-message chat, 11 summaries, and 14
sibling chats so `chat_id` is selective:

| boundary lookup | plan | buffers |
|---|---|---|
| old predicate | Index Scan `idx_chat_messages_chat`, 19,989 rows
filtered | 267 |
| rebuilt index | Index Only Scan | 2 |

Not in scope: the outer `SELECT` still inspects every row of the chat,
because its `role = 'system' AND compressed = FALSE` disjunct has no
lower `id` bound. That predates this PR and needs a query rewrite rather
than an index.

## Testing

Two subtests, both verified red by reverting the `ORDER BY` and
regenerating:

- `OrdersByIDWhenTimestampsDisagree` returned `[4,3,2,1]` instead of
`[1,2,3,4]`, placing the tool result before the assistant call.
- `CompactionBoundaryUsesID` selected the stale summary and leaked the
messages between the two summaries into the prompt.

Existing subtests pass unchanged. Migration up/down tests pass, and the
rebuilt index was verified red-green: restoring the old predicate
returns the plan to a 267-buffer scan, and the old predicate matches 0
rows in the fixture.

> Opened by Mux on behalf of Mike.
2026-07-29 14:04:59 +02:00
2022-04-04 11:55:06 -05:00
2026-07-15 14:57:23 +01:00

Coder Logo Light Coder Logo Dark

Self-Hosted Cloud Development Environments and AI Agents

Coder Banner Light Coder Banner Dark

Quickstart | Docs | Why Coder | Premium

discord release godoc Go Report Card OpenSSF Best Practices OpenSSF Scorecard license

Coder is a self-hosted platform for cloud development environments and AI coding agents. Workspaces are defined with Terraform, connected through a secure Wireguard® tunnel, and automatically shut down when not used. Coder Agents runs a native AI coding agent whose loop executes in the control plane on your infrastructure, with no API keys in workspaces.

  • Define cloud development environments in Terraform
    • EC2 VMs, Kubernetes Pods, Docker Containers, etc.
  • Automatically shutdown idle resources to save on costs
  • Onboard developers in seconds instead of days
  • Delegate coding work to AI agents on your infrastructure
    • Bring any model (Anthropic, OpenAI, Google, Bedrock, self-hosted)
    • No LLM credentials in workspaces, user identity on every action
    • Centralized model governance, cost tracking, and audit logging

Coder platform showing templates and a running workspace

Quickstart

The most convenient way to try Coder is to install it on your local machine and experiment with provisioning cloud development environments using Docker (works on Linux, macOS, and Windows).

# First, install Coder
curl -L https://coder.com/install.sh | sh

# Start the Coder server (caches data in ~/.cache/coder)
coder server

# Navigate to http://localhost:3000 to create your initial user,
# create a Docker template and provision a workspace

Install

The easiest way to install Coder is to use the install script for Linux and macOS. For Windows, use the latest ..._installer.exe file from GitHub Releases.

curl -L https://coder.com/install.sh | sh

You can run the install script with --dry-run to see the commands that will be used to install without executing them. Run the install script with --help for additional flags.

See install for additional methods.

Once installed, you can start a production deployment with a single command:

# Automatically sets up an external access URL on *.try.coder.app
coder server

# Requires a PostgreSQL instance (version 13 or higher) and external access URL
coder server --postgres-url <url> --access-url <url>

Use coder --help to get a list of flags and environment variables. See the install guides for a complete tutorial.

Documentation

Browse the documentation or visit a specific section below:

  • Workspaces: Workspaces contain the IDEs, dependencies, and configuration information needed for software development
  • Templates: Templates are written in Terraform and describe the infrastructure for workspaces
  • Coder Agents: Delegate coding work to AI agents running on your self-hosted infrastructure
  • Administration: Learn how to operate Coder
  • Premium: Learn about paid features built for large teams
  • IDEs: Connect your existing editor to a workspace

Support

Feel free to open an issue if you have questions, run into bugs, or have a feature request.

Join our Discord to provide feedback on in-progress features and chat with the community using Coder!

Integrations

New integrations are always in progress. Open an issue to request one. Contributions are welcome in any official or community repository.

Official

Community

Contributing

New contributors are always welcome. If you are new to the Coder codebase, see the contribution guide to get started.

Hiring

Apply on the careers page if you are interested in joining the team.

S
Description
Provision remote development environments via Terraform
Readme AGPL-3.0
908 MiB
Languages
Go 74.9%
TypeScript 23.1%
Shell 0.8%
HCL 0.3%
PLpgSQL 0.3%
Other 0.4%