Skip to content

WIP feat: support retries/hard failure limit for prebuilds in reconcile prior to provisioner - #21326

Closed
cstyan wants to merge 5 commits into
mainfrom
callum/prebuild-fail-interval
Closed

cstyan wants to merge 5 commits into
mainfrom
callum/prebuild-fail-interval

Conversation

@cstyan

@cstyan cstyan commented Dec 18, 2025

Copy link
Copy Markdown
Collaborator

This PR is meant to address the recent issues we saw regarding heavy CPU/memory usage in profiling related prebuilds, specifically endless retrying of prebuilds for presets that have invalid config and thus will never succeed.

The wsbuilder.Build is where this error can occur, though IIUC there can also be transient errors there (for example network connection issues or DB load related), so the changes here are twofold:

  • a backoff retry in the reconcile loop for prebuilds which hit 500 error codes (transient issues)
  • the writing of a DB entry for 400s (config related issues) that will never succeed until the template is updated, these are the same records that the reconcile loop should already be looking for as part of the GetPresetsAtFailureLimit query

Callum Styan and others added 5 commits December 16, 2025 23:51
The prebuilds reconcile loop can currently spam workspace creation
attempts that are always going to fail, such as when required dynamic
parameters are missing or unresolved.

This change introduces an in-memory per-preset backoff mechanism that
tracks consecutive creation failures and delays subsequent creation
attempts using linear backoff:

- First failure: backoff for 1x interval (default 1 minute)
- Second consecutive failure: backoff for 2x interval (2 minutes)
- Third consecutive failure: backoff for 3x interval (3 minutes)
- And so on...

When a creation succeeds, the failure tracking is cleared and any
subsequent failure starts backoff from 1x interval again.

This complements the existing database-based backoff system by
preventing immediate retry spam when creation fails quickly (e.g.,
due to missing parameters), while still allowing periodic retries
and recovery when issues are fixed.

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

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Encapsulates the failure tracking logic into a dedicated
presetFailuresTracker struct with its own methods, improving code
organization and separation of concerns.

Changes:
- Created presetFailuresTracker struct with failures map and mutex
- Moved RecordFailure, RecordSuccess, and ShouldBackoff methods to
  the tracker
- Updated StoreReconciler to hold a failureTracker instance
- Updated all call sites to use the new tracker methods

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

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
…hit hard limit

Previously, the failure tracking applied backoff to all creation errors
regardless of type. This meant that permanent configuration errors (400s)
would be retried with backoff, delaying the hard failure limit detection.

Now we distinguish between error types:
- Transient errors (500-level): Database failures, network issues, etc.
  These trigger the backoff mechanism to reduce spam during outages.
- Config errors (400-level): Missing parameters, validation failures, etc.
  These skip backoff and fail immediately, counting toward the hard limit.

This allows presets with permanent issues (e.g., missing dynamic parameters)
to hit the hard failure limit (default 3 consecutive failures) and get marked
as PrebuildStatusHardLimited, while transient infrastructure issues get
incremental backoff without blocking the hard limit detection.

The hard limit system (GetPresetsAtFailureLimit) tracks the last N builds
in the database. When all N fail with job_status='failed', the preset is
marked hard-limited and creation is blocked entirely until the issue is
resolved.

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

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Previously, when wsbuilder.Build() failed with config errors (400-level),
no workspace or build records were created because the transaction rolled back.
This meant config errors never counted toward the hard failure limit, which
queries workspace_latest_builds.job_status in the database.

Now when Build() fails with a non-transient error (non-500):
1. The workspace is created
2. A provisioner job is created and immediately marked as failed
3. A workspace build is created linking to the failed job
4. The transaction commits, preserving the failure record

This allows the hard limit detection (GetPresetsAtFailureLimit) to see
these failures and mark presets as PrebuildStatusHardLimited after N
consecutive config errors (default 3).

The flow is now:
- Transient errors (500s): Trigger in-memory backoff, no DB record
- Config errors (400s): Create failed DB record, count toward hard limit
- After N config failures: Preset marked hard-limited, creation blocked

Implementation details:
- createFailedBuildRecord() mimics successful build creation but marks job
  as failed immediately using UpdateProvisionerJobWithCompleteWithStartedAtByID
- Uses dbauthz.AsProvisionerd(ctx) to authorize the job completion
- job_status is a generated column: becomes 'failed' when completed_at is
  set and error is non-empty

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

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
This test verifies that when createPrebuiltWorkspace encounters a
config error (HTTP 400-level error from wsbuilder.Build), it creates
a failed build record in the database so the error counts toward the
hard failure limit.

The test (TestConfigErrorCreatesFailedBuildRecord):
- Creates a template with a required mutable parameter
- Creates a preset without providing the required parameter
- Runs reconciliation which triggers wsbuilder.Build failure
- Verifies workspace and failed build record are created
- Verifies provisioner job has job_status='failed'
- Verifies the failure appears in GetPresetsAtFailureLimit query

Note: This test requires postgres (via dbtestutil.NewDB) to run the
full reconciliation flow including complex SQL queries. The test will
run successfully in CI where postgres is available.

This completes the config error handling implementation from commit
4, ensuring that permanent configuration issues properly count toward
the hard failure limit and trigger preset suspension after N failures.
@cstyan
cstyan requested a review from ssncferreira December 18, 2025 22:14
@github-actions

Copy link
Copy Markdown
Contributor


Thank you for your submission, we really appreciate it. Like many open-source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution. You can sign the CLA by just posting a Pull Request Comment same as the below format.


I have read the CLA Document and I hereby sign the CLA


Callum Styan seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You can retrigger this bot by commenting recheck in this Pull Request. Posted by the CLA Assistant Lite bot.

@ssncferreira ssncferreira left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think we need to revisit some of this logic. This PR introduces two mechanisms (in-memory backoff and creating failed build records outside wsbuilder.Build()) that may not work correctly in production.


case prebuilds.ActionTypeCreate:
// Check if we should backoff on this preset due to recent creation failures
if shouldBackoff, backoffUntil := c.failureTracker.ShouldBackoff(ps.Preset.ID, c.cfg.ReconciliationBackoffInterval.Value()); shouldBackoff {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This in-memory approach doesn't work well in a multi-replica scenario. The prebuild reconciliation loop can run on a different coderd replica every time. This leads to up to N extra failures (where N = number of replicas) before backoff takes effect across the system. For instance, with 3 replicas:

  • T+0s: Preset A fails on replica 1, consecutive=1, backoff 1 minute
  • T+10s: Preset A fails on replica 2, consecutive=1, backoff 1 minute
  • T+20s: Preset A fails on replica 3, consecutive=1, backoff 1 minute
  • ...
  • T+1m: Replica 1 backoff expires, fails again, consecutive=2, backoff 2 minutes
  • T+1m10s: Replica 2 backoff expires, fails again, consecutive=2, backoff 2 minutes
  • ...
    Each replica independently escalates its own backoff duration, but they're all out of sync. The "consecutive" count is per-replica, not global. For this to be a global backoff, we would need to store this information in the database, so it is visible on each reconciliation loop.

slog.F("original_error", err.Error()))
}
}
return err

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This will rollback the prebuilds transaction, removing both the prebuilt workspace (created earlier in the transaction) as well as the recently created failed workspace build and provisioner job.

Creating a provisioner job and workspace build outside of wsbuilder.Build() is a new pattern that could introduce unexpected issues. All workspace build and provisioner job creation currently goes through wsbuilder.Build(), which handles various invariants and side effects. Bypassing it may lead to inconsistent state or break assumptions in other parts of the codebase.

@github-actions github-actions Bot added the stale This issue is like stale bread. label Dec 30, 2025
@github-actions github-actions Bot closed this Jan 3, 2026
@github-actions
github-actions Bot deleted the callum/prebuild-fail-interval branch June 19, 2026 00:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale This issue is like stale bread.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants