Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions infra/lib/api-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,16 @@ export class ApiStack extends cdk.Stack {

// --- SQS Queues ---

// Queues the worker reads (tickets, CI fix, feedback, webhooks). AWS
// asks for a visibility timeout of at least six times the function's
// timeout (900 s) and a redrive count of at least 5. A ticket run hands
// off to a NEW message before 900 s, so the visibility only matters
// after a crash: the message comes back after 90 minutes, and the
// stuck-run sweep (20 minutes without an update) has failed the run with
// a reason by then.
const WORKER_QUEUE_VISIBILITY = cdk.Duration.seconds(6 * 900);
const WORKER_QUEUE_MAX_RECEIVES = 5;

// Dead letter queue (shared)
const dlq = new sqs.Queue(this, "DLQ", {
queueName: `${prefix}-dlq`,
Expand All @@ -278,9 +288,9 @@ export class ApiStack extends cdk.Stack {

this.ticketQueue = new sqs.Queue(this, "TicketQueue", {
queueName: `${prefix}-tickets`,
visibilityTimeout: cdk.Duration.minutes(16), // > Lambda timeout
visibilityTimeout: WORKER_QUEUE_VISIBILITY,
encryption: sqs.QueueEncryption.SQS_MANAGED,
deadLetterQueue: { queue: dlq, maxReceiveCount: 3 },
deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES },
});

// CoderHelm's mail relay (hosted side of hybrid only): its sending
Expand All @@ -291,26 +301,26 @@ export class ApiStack extends cdk.Stack {

this.ciFixQueue = new sqs.Queue(this, "CiFixQueue", {
queueName: `${prefix}-ci-fix`,
visibilityTimeout: cdk.Duration.minutes(16),
visibilityTimeout: WORKER_QUEUE_VISIBILITY,
encryption: sqs.QueueEncryption.SQS_MANAGED,
deadLetterQueue: { queue: dlq, maxReceiveCount: 3 },
deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES },
});

this.feedbackQueue = new sqs.Queue(this, "FeedbackQueue", {
queueName: `${prefix}-feedback`,
visibilityTimeout: cdk.Duration.minutes(16),
visibilityTimeout: WORKER_QUEUE_VISIBILITY,
encryption: sqs.QueueEncryption.SQS_MANAGED,
deadLetterQueue: { queue: dlq, maxReceiveCount: 3 },
deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES },
});

// Outbound webhooks: events the work emits (`webhook_emit`) and the
// delayed retries of their deliveries (`webhook_send`). Its own queue so
// a delivery never waits behind long runs on the tickets queue.
this.webhookQueue = new sqs.Queue(this, "WebhookQueue", {
queueName: `${prefix}-webhooks`,
visibilityTimeout: cdk.Duration.minutes(16),
visibilityTimeout: WORKER_QUEUE_VISIBILITY,
encryption: sqs.QueueEncryption.SQS_MANAGED,
deadLetterQueue: { queue: dlq, maxReceiveCount: 3 },
deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES },
});

// Review-reminder sweep: every 20 min, drop a constant message on the ticket
Expand Down
18 changes: 15 additions & 3 deletions infra/test/synth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,18 @@ test("sign-in: hosted keeps its open pool (no pre-sign-up trigger) and optional
assert.ok(pool.Properties.LambdaConfig.CustomMessage);
});

test("worker queues: visibility 6x the worker timeout, redrive count 5", () => {
const api = synth(selfHost())["coderhelm-prod-api"];
for (const name of ["tickets", "ci-fix", "feedback", "webhooks"]) {
const queues = api.findResources("AWS::SQS::Queue", {
Properties: { QueueName: `coderhelm-prod-${name}` },
});
const q = (Object.values(queues)[0] as any).Properties;
assert.equal(q.VisibilityTimeout, 5400, name);
assert.equal(q.RedrivePolicy.maxReceiveCount, 5, name);
}
});

test("outbound webhooks: one queue, wired to the worker, sendable by every emitter", () => {
const t = synth(selfHost());
const api = t["coderhelm-prod-api"];
Expand All @@ -739,9 +751,9 @@ test("outbound webhooks: one queue, wired to the worker, sendable by every emitt
const ids = Object.keys(queues);
assert.equal(ids.length, 1, "one webhooks queue");
const q = (queues[ids[0]] as any).Properties;
// Visible longer than the worker can run, retried into the shared DLQ.
assert.equal(q.VisibilityTimeout, 960);
assert.equal(q.RedrivePolicy.maxReceiveCount, 3);
// AWS: visibility at least 6x the worker's 900 s, redrive count at least 5.
assert.equal(q.VisibilityTimeout, 5400);
assert.equal(q.RedrivePolicy.maxReceiveCount, 5);
// Every function that emits or sends knows the queue.
const gw = envOf(api, "coderhelm-prod-gateway");
assert.ok(gw.WEBHOOK_QUEUE_URL, "gateway");
Expand Down
27 changes: 27 additions & 0 deletions lambda/stuck-run-cleanup/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@
ROUND_FIELD = "round"
INCOMPLETE_FIELD = "round_incomplete"
ROUND_BUDGET_SECONDS = 750
# A ticket run works in steps (services/worker/src/passes/steps.rs): each
# step queues the next as a new message and records `step_queued_at`. A step
# that is queued and hasn't started (a full queue) is not stuck; past this
# long, it is.
STEP_QUEUED_FIELD = "step_queued_at"
MAX_STEP_QUEUED_HOURS = int(os.environ.get("MAX_STEP_QUEUED_HOURS", "6"))
ROUND_SWEEP_GRACE_SECONDS = 300
ROUND_LABELS = {
"ci_fix": "CI fix round",
Expand Down Expand Up @@ -124,6 +130,23 @@ def round_in_budget(run, now):
return now < deadline + timedelta(seconds=ROUND_SWEEP_GRACE_SECONDS)


def step_queued(run, now):
"""True while the run's next step is queued and hasn't started yet.

A step that starts updates `updated_at`, so a queued time after the last
update means no step is running and one is waiting for the queue. A step
that started and then died (a crash) has its queued time before the last
update, and the run is swept as usual.
"""
queued = _parse_time(run.get(STEP_QUEUED_FIELD))
if queued is None:
return False
updated = _parse_time(run.get("updated_at") or run.get("created_at"))
if updated is not None and queued < updated:
return False
return now < queued + timedelta(hours=MAX_STEP_QUEUED_HOURS)


def has_pull_request(run):
try:
number = int(run.get("pr_number") or 0)
Expand Down Expand Up @@ -242,6 +265,7 @@ def handler(event, context):
},
"ProjectionExpression": (
"team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, "
"step_queued_at, "
"#round, pr_number, pr_url"
),
}
Expand All @@ -256,6 +280,9 @@ def handler(event, context):
if status == "running" and round_in_budget(item, now):
# Its fix round is still inside its own budget.
continue
if status == "running" and step_queued(item, now):
# Its next step is queued and hasn't started.
continue
if updated and updated < cutoff:
stuck_runs.append(item)

Expand Down
22 changes: 22 additions & 0 deletions lambda/tests/test_stuck_run_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,25 @@ def test_no_pr_means_no_pr(self):

if __name__ == "__main__":
unittest.main()


class StepQueued(unittest.TestCase):
NOW = sweep.datetime(2026, 10, 28, 12, 0, tzinfo=sweep.timezone.utc)

def at(self, minutes):
return (self.NOW - sweep.timedelta(minutes=minutes)).isoformat()

def test_a_queued_step_not_started_is_not_stuck(self):
run = {"updated_at": self.at(40), "step_queued_at": self.at(39)}
self.assertTrue(sweep.step_queued(run, self.NOW))

def test_a_started_step_that_died_is_swept(self):
run = {"updated_at": self.at(30), "step_queued_at": self.at(45)}
self.assertFalse(sweep.step_queued(run, self.NOW))

def test_a_step_queued_too_long_is_swept(self):
run = {"updated_at": self.at(60 * 8), "step_queued_at": self.at(60 * 7)}
self.assertFalse(sweep.step_queued(run, self.NOW))

def test_no_step_queued(self):
self.assertFalse(sweep.step_queued({"updated_at": self.at(30)}, self.NOW))
7 changes: 7 additions & 0 deletions services/worker/src/clients/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ use aws_sdk_codebuild::types::{EnvironmentVariable, EnvironmentVariableType, Sta
use aws_sdk_s3::presigning::PresigningConfig;

const MARKER_END: &str = "CODERHELM_CHECKS_END exit=";
/// What a codegen build CodeBuild timed out reports: a tooling failure.
pub const CODEGEN_TIMED_OUT: &str = "the sandbox build timed out (CodeBuild TIMED_OUT)";
const MARKER_START: &str = "===CODERHELM_CHECKS_START===";
/// Poll cadence while a build runs.
const POLL_INTERVAL: Duration = Duration::from_secs(6);
Expand Down Expand Up @@ -615,6 +617,11 @@ impl<'a> SandboxClient<'a> {
.map_err(|e| format!("codebuild batch_get_builds failed: {e}"))?;
let build = builds.builds().first().ok_or("no build record")?;
let status = build.build_status();
if matches!(status, Some(StatusType::TimedOut)) {
// CodeBuild's own build timeout: the sandbox, not the change
// and not this step's time.
return Ok(CodegenOutcome::not_run(CODEGEN_TIMED_OUT));
}
if !matches!(status, Some(StatusType::InProgress)) {
let (group, stream) = build
.logs()
Expand Down
Loading
Loading