Skip to content

Load prompt rows once per generation step - #334

Merged
ibetitsmike merged 9 commits into
mainfrom
mike/issue-298-prompt-rows-once
Nov 15, 2026
Merged

ibetitsmike merged 9 commits into
mainfrom
mike/issue-298-prompt-rows-once

Conversation

@ibetitsmike

Copy link
Copy Markdown
Owner

Coder Agents opened this PR on behalf of @ibetitsmike.

Closes #298

What changed

One generation step loaded the chat's prompt rows (GetChatMessagesForPromptByChatID) up to 4 times: fork context loaded them for the todo snapshot check, the pinned skills check and the token budget check, and buildTurnEnvironment loaded them again. syncForkContext now loads the rows once per step pass when any of forkContextSharesPromptRows() (ForkChatTodos, ForkPinnedSkills, ForkTokenBudget) is enabled, and hands the slice to pinnedSkillsMessage, tokenBudgetMessage and, via generationPrepareInput.PromptRows, buildTurnEnvironment.

Each consumer keeps its nil-rows self-load path, so callers that do not share rows behave exactly as before.

Correctness: reload on insert

A fork context message commit bumps chats.history_version, which restarts the generation step, and the new pass runs syncForkContext again, which loads fresh rows. When sync commits nothing, no insert happens between the load and the prompt build in the same pass: the rows the prompt is built from are the rows that were checked. The turn environment build only reads rows. This is asserted by TestForkContextInsertRestartsStepWithRows.

Load counts

The turn runner runs one generation step per history_version, so a fork-context-restarting turn runs two passes and loads the rows twice, the same as before this PR (the old code also loaded 2-3 times per pass). Named upstream loads outside a step pass are unchanged and out of scope:

  • memoryIndexMessage first-turn pre-read (upstream, one load)
  • deriveFinalTurnRunResult end-of-turn status label (upstream, one load)
  • generateAndStoreChatSummary background summary (upstream, one load)

Tests

New coderd/x/chatd/fork_prompt_load_internal_test.go:

  • TestGenerationStepLoadsPromptRowsOnce: preset rows, fork experiments on, asserts exactly 5 loads in the turn (2 step passes + 3 named upstream loads) and both fork context headers in the first streaming request.
  • TestGenerationStepExperimentsOffKeepsUpstreamLoads: all fork experiments off, asserts 5 loads and neither header in the request.
  • TestGenerationStepNoPinsNoTodosLoadsOnce: fork experiments on, nothing seeded, asserts 5 loads and exactly one streaming request.
  • TestForkContextInsertRestartsStepWithRows: no preset, asserts both fork context messages land as model-only rows and the request contains them.

A counting store wraps the DB and counts GetChatMessagesForPromptByChatID calls. The fixture creates the chat idle and starts the turn with SendMessage, so no seed row can race the worker. fork_testhooks.go exports the three unexported entry points for the external test package; production code paths are unchanged.

Without the change the count test fails with 9 loads, so the reduction is measured, not assumed.

Notes

  • memoryIndexMessage keeps its own load: it runs in syncMemoryIndex before the shared load, and changing upstream memory index behavior is out of scope.
  • Deferred: rendering pinned skills from a cached materialized block instead of re-rendering per request. The prompt rows are now loaded once, but the render still happens per request.
  • generationPrepareInput lives in an upstream file (generation.go); the field addition follows the established fork pattern of one hook line per upstream file, extended here by the struct field the hook needs.

Verification

  • go test -count=1 -timeout 10m ./coderd/x/chatd/...: all 21 packages ok.
  • go vet ./coderd/x/chatd/: clean.
  • golangci-lint run --config=.golangci.new-code.yaml --new-from-merge-base=origin/main: 0 issues.
  • Full-tree lint has pre-existing findings elsewhere; none in the changed lines.

One generation step loaded the chat's prompt rows up to 4 times: fork
context for the todo snapshot check, the pinned skills check, the token
budget check, and buildTurnEnvironment. syncForkContext now loads the
rows once when any of those checks is enabled and hands them to each
check and to the turn environment build.

Correctness comes from reload on insert: a fork context message commit
bumps the chat history version, which restarts the step, and the new
pass syncs and loads again. When sync commits nothing, no inserts happen
between the load and the prompt build in the same pass.

Turns that fork context restart keep the same load count as before. The
upstream loads outside a step pass (memory index pre-read, final turn
run result, chat summary) are unchanged and out of scope.

Closes #298
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T13:18:55.003926Z 89a8009 Manual request
ℹ️ 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.

A failing shared prompt-row load returned an error to runTaskWithRetry,
which retries the whole task with no attempt cap and never marks the
chat errored. Before the shared load, the same query failing inside the
turn environment build was retried three times under the prepare phase
and then errored the chat. Log the failure and return no rows instead,
so the todo snapshot, pinned skills, token budget and turn environment
consumers fall back to their own loads and the established error path.

Also keep the loaded rows on the token budget error path, where nothing
was inserted, so the turn environment does not reload them.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Addressed the review findings:

  • P2 (fixed, a8a14a8): a failing shared prompt-row load returned the error to runTaskWithRetry, which retries the whole task with no attempt cap and never marks the chat errored, instead of the old prepare-phase retry (3 attempts, then the chat errors). The load failure is now logged and returns no rows, so the todo snapshot, pinned skills, token budget and turn environment consumers fall back to their own loads and the established error path. Also keeps the loaded rows on the token budget error path, where nothing was inserted.
  • P3 prepare-span (dropped): observability only; the step span still covers the load, and moving it back under StagePrepare would reintroduce the double-load shape this PR removes.
  • P3 test hooks in the production build (kept as-is): testhooks.go and aibridged/testhooks.go are existing repo patterns for ForTest helpers used by black-box _test packages; export_test.go would not be visible to the chatd_test package.

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a8a14a87ec

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/fork_context.go Resolved
…lback

After the organization token budget merge, forkGenerateCompaction loaded
prompt rows again on the summary fallback path of an automatic
compaction. The step's turn environment now carries the rows the fork
context sync loaded once, and the fallback reads them first, loading its
own only when the environment has none.

This also shares the load with tokenBudgetTriggers, which read the rows
the turn environment already held, so no new load appears there.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged origin/main (9308bf6, #330). That merge added a prompt-row load in forkGenerateCompaction on the summary fallback path. The step's turn environment now carries PromptRows (the rows the fork context sync loaded once) and the fallback reads them first, loading its own only when the environment has none. tokenBudgetTriggers already read the rows the environment held, so no new load appears there.

Counting tests rerun on the new head, all pass; full ./coderd/x/chatd/ package passes; new-code lint gate 0 issues; go vet clean. New head: 2d7bbd2.

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 2d7bbd2b01

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…ilure

A failed shared prompt-row load skipped the todo snapshot, pinned skills
and token budget checks for the pass, while the turn environment could
reload rows under its own retry and run the step without a due fork
context message. Continue with nil rows instead: each check falls back
to its own load, so a step that is due a message still commits it, and a
persistent failure still errors the chat on the prepare retry path.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Fixed the P2 review finding in 1032a06: the shared-load failure no longer returns early. syncForkContext continues with nil rows, so the todo snapshot, pinned skills and token budget checks fall back to their own loads and a step due a fork context message still commits it. A persistent failure still errors the chat through the consumer retry paths.

All tests and the lint gate rerun green on the new head. Requesting a fresh review.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 1032a06ff9

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged origin/main (9f99450, #331, site-only, no code conflicts). New head 8645472, not behind main. Waiting for fork-ci on this head, then a fresh Codex receipt.

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8645472f77

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/fork_testhooks.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged origin/main (5f049c1, #332). #334 adds no chatdmig node, so no requires line is needed; the new node 01a1da95 merges in cleanly with its requires line on 01a1da86. New head 78a3c62. Waiting for fork-ci, then a fresh Codex receipt.

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 78a3c62b9b

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…tion build

Codex flagged the exported TodoSnapshotMessageForTest,
PinnedSkillsMessageForTest and WriteChatTodosForTest wrappers in
fork_testhooks.go: they compiled into every normal chatd build and were
referenced only by the prompt-load test. Delete the file and make
fork_prompt_load_internal_test.go a real package chatd internal test that
calls todoSnapshotMessage, pinnedSkillsMessage and writeChatTodos
directly, with its own Anthropic server fixture, counting store and
request recorder instead of the package chatd_test helpers.

No production code changes. Test expectations are unchanged.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 89a80098ab

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike
ibetitsmike merged commit 99ced87 into main Nov 15, 2026
9 checks passed
@ibetitsmike
ibetitsmike deleted the mike/issue-298-prompt-rows-once branch November 15, 2026 13:40
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged as 99ced87 (squash, --match-head-commit).

Gates on head 89a8009, with main at 3f37f49 (live on the server at merge time):

  • Every check run on the head passed (9 of 9). fork-ci run 43716701008 ran on this exact head and passed.
  • Codex receipt on the head: Load prompt rows once per generation step #334 (comment) ("Didn't find any major issues", Reviewed commit: 89a80098ab).
  • Review threads: 0 unresolved. The Codex P1 on fork_testhooks.go (test helpers exported in the production build) was fixed in 150deda by deleting the file and moving the tests to package-internal tests.
  • Behind main: 0.
  • Opus review, read-only, on the exact head: mergeable, no P1 or P2. Nits not acted on: the upstream hooks in generation.go and turn_environment.go are more than one line (the early return in turn_environment.go could be a one-line fork helper), two comments on when PromptRows is nil are imprecise, ARCHITECTURE.md does not mention that the summary-fallback compaction reuses the step's rows, and the load-count tests run with fork-token-budget off.

Tests I ran on this head:

  • go test -count=1 -v -run 'TestGenerationStep|TestForkContext|TestTodoSnapshotMessage|TestPinnedSkills|TestTokenBudget|TestTurnEnvironment' ./coderd/x/chatd/: 11 of 11 pass.
  • Negative control: dropping prepareInput.PromptRows = promptRows in generation.go makes TestGenerationStepLoadsPromptRowsOnce and TestGenerationStepNoPinsNoTodosLoadsOnce fail (expected 5 loads, got 7). TestGenerationStepExperimentsOffKeepsUpstreamLoads still passes. Restored, all pass.
  • The workstream also ran the full ./coderd/x/chatd package (ok) and lint on new code (0 issues).

Not exercised: the token budget summary-fallback reuse of PromptRows has no load-count assertion. Not run on a live server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chatd: fork context sync reloads the whole prompt history up to twice per generation step

1 participant