feat(practice): run practice jobs on the code runner with one stored result per run
This commit is contained in:
1 parent
9385b2ddd4
commit
9344228e84
17 files changed
+1010
-35
No files matched your search
@@ -0,0 +1,20 @@
|
||||
-- +goose Up
|
||||
-- A finished practice job keeps the opaque run ID under which the code runner
|
||||
-- held the run that produced the stored result. The ID is the HMAC-derived
|
||||
-- value of the run key (attempt item, submission, generation) that the runner
|
||||
-- itself logs, so an operator can match a stored result to one runner run
|
||||
-- without the runner learning who the candidate is. Only the finishing try
|
||||
-- writes it, in the transaction that stores the result; a failed or unfinished
|
||||
-- job has none. The ID is unique, because one run produces at most one result.
|
||||
ALTER TABLE assessment_practice_jobs
|
||||
ADD COLUMN runner_run_id uuid,
|
||||
ADD CONSTRAINT assessment_practice_jobs_runner_run_state CHECK (
|
||||
runner_run_id IS NULL OR state = 'finished'
|
||||
),
|
||||
ADD CONSTRAINT assessment_practice_jobs_runner_run_key UNIQUE (runner_run_id);
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE assessment_practice_jobs
|
||||
DROP CONSTRAINT assessment_practice_jobs_runner_run_key,
|
||||
DROP CONSTRAINT assessment_practice_jobs_runner_run_state,
|
||||
DROP COLUMN runner_run_id;
|
||||
@@ -149,11 +149,13 @@ WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND result IS NULL;
|
||||
|
||||
-- Ends a running try as finished or failed.
|
||||
-- Ends a running try as finished or failed. A finished job keeps the run ID
|
||||
-- of the runner run that produced its result.
|
||||
-- name: FinishAssessmentPracticeJob :execrows
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
runner_run_id = sqlc.narg(runner_run_id),
|
||||
finished_at = greatest(created_at, clock_timestamp()),
|
||||
last_error_class = coalesce(sqlc.narg(error_class), last_error_class),
|
||||
lease_owner = NULL,
|
||||
|
||||
@@ -292,11 +292,18 @@ func createPractice(
|
||||
if err != nil {
|
||||
t.Fatalf("generate practice ID: %v", err)
|
||||
}
|
||||
// A submission is stamped with the database time, so the practice is
|
||||
// created with it too: a database clock slightly behind the test host
|
||||
// would otherwise put the first submission before its practice.
|
||||
var createdAt time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT clock_timestamp()`).Scan(&createdAt); err != nil {
|
||||
t.Fatalf("read database time: %v", err)
|
||||
}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.AssessmentPractices().Create(ctx, domain.AssessmentPractice{
|
||||
ID: id, AttemptID: domain.AssessmentAttemptID(attemptID), UserID: userID, Kind: kind, Task: practiceTestTask(),
|
||||
Status: domain.AssessmentPracticeNotStarted, CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
Status: domain.AssessmentPracticeNotStarted, CreatedAt: createdAt.UTC().Truncate(time.Microsecond),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -231,7 +231,7 @@ func TestAssessmentPracticeQueue(t *testing.T) {
|
||||
|
||||
// The crashed worker coming back late cannot add a second result.
|
||||
lateStore := postgresadapter.NewPracticeJobStore(newPoolFor(ctx, t, harness.databaseURL))
|
||||
held, err := lateStore.Complete(ctx, stale, domain.PracticeRunResult{Outcome: domain.PracticeOutcomeWrongAnswer, Groups: []domain.PracticeGroupOutcome{}})
|
||||
held, err := lateStore.Complete(ctx, stale, uuid.New(), domain.PracticeRunResult{Outcome: domain.PracticeOutcomeWrongAnswer, Groups: []domain.PracticeGroupOutcome{}})
|
||||
if err != nil || held {
|
||||
t.Fatalf("late completion held = %v, error %v; want refused", held, err)
|
||||
}
|
||||
@@ -275,13 +275,13 @@ func TestAssessmentPracticeQueue(t *testing.T) {
|
||||
// practiceQueueRig builds workers on the test clock and the fake runner.
|
||||
type practiceQueueRig struct {
|
||||
pool *pgxpool.Pool
|
||||
runner *fakePracticeRunner
|
||||
runner outbound.CodeRunner
|
||||
clock *practiceQueueClock
|
||||
logger *slog.Logger
|
||||
worker *practicequeue.Worker
|
||||
}
|
||||
|
||||
func newPracticeQueueRig(t *testing.T, pool *pgxpool.Pool, runner *fakePracticeRunner, clock *practiceQueueClock) *practiceQueueRig {
|
||||
func newPracticeQueueRig(t *testing.T, pool *pgxpool.Pool, runner outbound.CodeRunner, clock *practiceQueueClock) *practiceQueueRig {
|
||||
t.Helper()
|
||||
rig := &practiceQueueRig{pool: pool, runner: runner, clock: clock, logger: slog.New(slog.DiscardHandler)}
|
||||
rig.worker = rig.newWorker(t)
|
||||
@@ -438,7 +438,7 @@ func (runner *fakePracticeRunner) Poll(_ context.Context, request outbound.CodeR
|
||||
|
||||
func (runner *fakePracticeRunner) statusLocked(run *fakePracticeRun) outbound.CodeRunStatus {
|
||||
if runner.holding && !run.finished {
|
||||
return outbound.CodeRunStatus{State: outbound.CodeRunRunning, RunID: "fake"}
|
||||
return outbound.CodeRunStatus{State: outbound.CodeRunRunning, RunID: fakeRunnerRunID(run.request.Key)}
|
||||
}
|
||||
run.finished = true
|
||||
result := outbound.CodeRunResult{Outcome: outbound.CodeOutcomeAccepted, Duration: 10 * time.Millisecond}
|
||||
@@ -452,7 +452,13 @@ func (runner *fakePracticeRunner) statusLocked(run *fakePracticeRun) outbound.Co
|
||||
}
|
||||
result.Groups = append(result.Groups, groupResult)
|
||||
}
|
||||
return outbound.CodeRunStatus{State: outbound.CodeRunFinished, RunID: "fake", Result: &result}
|
||||
return outbound.CodeRunStatus{State: outbound.CodeRunFinished, RunID: fakeRunnerRunID(run.request.Key), Result: &result}
|
||||
}
|
||||
|
||||
// fakeRunnerRunID is a stable run ID per run key, as the real runner client
|
||||
// derives one.
|
||||
func fakeRunnerRunID(key outbound.CodeRunKey) string {
|
||||
return uuid.NewSHA1(key.SubmissionID, []byte{byte(key.Generation)}).String()
|
||||
}
|
||||
|
||||
// hold keeps new and unfinished runs running until it is turned off.
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/practice"
|
||||
)
|
||||
|
||||
const (
|
||||
practiceRunnerTestTimeout = 8 * time.Minute
|
||||
// practiceRunnerBackoff moves the test clock past the first backoff of a
|
||||
// failed try (10 s in the queue rig).
|
||||
practiceRunnerBackoff = 11 * time.Second
|
||||
)
|
||||
|
||||
// TestAssessmentPracticeRunnerProtocol drives practice runs through the real
|
||||
// router, the real queue worker, and the real TLS client of the code runner
|
||||
// against a local fixture of the runner protocol. The fixture does not run
|
||||
// code; see practiceRunnerFixture for what it decides.
|
||||
func TestAssessmentPracticeRunnerProtocol(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), practiceRunnerTestTimeout)
|
||||
defer cancel()
|
||||
harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) {
|
||||
return practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true)
|
||||
})
|
||||
clock := &practiceQueueClock{}
|
||||
runner := newPracticeRunnerFixture(t)
|
||||
queue := newPracticeQueueRig(t, harness.pool, runner.client(t), clock)
|
||||
|
||||
t.Run("python and go public runs finish and show the output of their own submission", func(t *testing.T) {
|
||||
alpha := newPracticeCandidate(ctx, t, harness, "runner-alpha", 10)
|
||||
beta := newPracticeCandidate(ctx, t, harness, "runner-beta", 20)
|
||||
// Each candidate's own test expects a wrong sum, so the diagnostic of
|
||||
// the failed test shows what that program printed for that input.
|
||||
alphaRun := createPracticeRun(t, harness, alpha, "python", practiceRunnerPythonSource("alpha"),
|
||||
[]domain.PracticeTest{{Input: "40 2\n", ExpectedOutput: "41\n"}}, "runner-alpha-run")
|
||||
betaRun := createPracticeRun(t, harness, beta, "go", practiceRunnerGoSource("beta"),
|
||||
[]domain.PracticeTest{{Input: "100 23\n", ExpectedOutput: "124\n"}}, "runner-beta-run")
|
||||
if alphaRun.State != "queued" || betaRun.State != "queued" {
|
||||
t.Fatalf("created runs are %q and %q, want queued", alphaRun.State, betaRun.State)
|
||||
}
|
||||
runsBefore := runner.runCount()
|
||||
queue.drain(t, ctx)
|
||||
|
||||
for _, expected := range []struct {
|
||||
candidate practiceCandidate
|
||||
run practiceRunnerRun
|
||||
marker string
|
||||
language string
|
||||
output string
|
||||
email string
|
||||
}{
|
||||
{alpha, alphaRun, "alpha", "python3", "got 42", "runner-alpha@example.test"},
|
||||
{beta, betaRun, "beta", "go", "got 123", "runner-beta@example.test"},
|
||||
} {
|
||||
read := readPracticeRunnerRun(t, harness, expected.candidate, expected.run.ID)
|
||||
if read.State != "finished" || read.FailureReason != nil || read.FinishedAt == nil || read.Result == nil || read.Result.Outcome != "wrong_answer" {
|
||||
t.Fatalf("run of %s = %+v, want finished with a wrong answer of the candidate's own test", expected.marker, read)
|
||||
}
|
||||
if len(read.Result.Tests) != 3 {
|
||||
t.Fatalf("run of %s lists %d tests, want the 2 examples and the candidate's test", expected.marker, len(read.Result.Tests))
|
||||
}
|
||||
for _, example := range read.Result.Tests[:2] {
|
||||
if example.Source != "example" || example.Outcome != "accepted" || example.Diagnostic != nil {
|
||||
t.Fatalf("example of %s = %+v, want accepted without a diagnostic", expected.marker, example)
|
||||
}
|
||||
}
|
||||
own := read.Result.Tests[2]
|
||||
if own.Source != "candidate" || own.Index != 1 || own.Outcome != "wrong_answer" || own.Diagnostic == nil || *own.Diagnostic != expected.output {
|
||||
t.Fatalf("candidate test of %s = %+v, want a wrong answer with the output %q", expected.marker, own, expected.output)
|
||||
}
|
||||
|
||||
// The run behind the stored result belongs to this submission: the
|
||||
// job keeps its runner run ID, and the runner started that run from
|
||||
// this candidate's source.
|
||||
job := readRunnerJob(t, ctx, harness.pool, expected.run.ID)
|
||||
if job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.attempts != 0 || job.generation != 0 {
|
||||
t.Fatalf("job of %s = %+v, want finished once with a runner run ID", expected.marker, job)
|
||||
}
|
||||
held, found := runner.run(job.runnerRunID.String())
|
||||
if !found || !strings.Contains(held.Request.Source, "marker: "+expected.marker+"\n") || string(held.Request.Language) != expected.language {
|
||||
t.Fatalf("runner run %s = %+v (found %v), want the %s source of %s", job.runnerRunID, held.Request, found, expected.language, expected.marker)
|
||||
}
|
||||
requireRunnerRequestIsolated(t, runner, job.runnerRunID.String(), runnerIsolation{
|
||||
candidate: expected.candidate, email: expected.email, submissionID: expected.run.ID,
|
||||
groups: []string{practice.PublicGroupID, practice.CustomGroupID}, forbidden: []string{practiceHiddenMarker, "hidden"},
|
||||
})
|
||||
}
|
||||
if started := len(runner.runIDsSince(runsBefore)); started != 2 {
|
||||
t.Fatalf("the runner started %d runs for two submissions, want 2", started)
|
||||
}
|
||||
// A candidate reads only their own run.
|
||||
requireSessionProblem(t, practiceRunRead(t, harness, beta, alpha.attemptID, alphaRun.ID), http.StatusNotFound, "not_found")
|
||||
requireSessionProblem(t, practiceRunRead(t, harness, beta, beta.attemptID, alphaRun.ID), http.StatusNotFound, "not_found")
|
||||
assertPracticeStatus(t, ctx, harness.pool, alpha.practiceID, "not_started", "")
|
||||
})
|
||||
|
||||
t.Run("a response cut after the runner accepted the run is repeated without a second run or result", func(t *testing.T) {
|
||||
gamma := newPracticeCandidate(ctx, t, harness, "runner-gamma", 30)
|
||||
runsBefore := runner.runCount()
|
||||
runner.failNextAccept("cut")
|
||||
submitPracticeFinal(t, ctx, harness, gamma, "runner-gamma-final")
|
||||
submissionID := latestPracticeSubmission(t, ctx, harness.pool, gamma.practiceID, "final")
|
||||
|
||||
if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry {
|
||||
t.Fatalf("try with a cut response = %q claimed %v, error %v; want retry", outcome, claimed, err)
|
||||
}
|
||||
job := readRunnerJob(t, ctx, harness.pool, submissionID)
|
||||
if job.state != "queued" || job.attempts != 1 || job.generation != 0 || job.errorClass != "runner_unavailable" || job.resultStored || job.runnerRunID != nil {
|
||||
t.Fatalf("job after the cut = %+v, want queued on the same run key without a result", job)
|
||||
}
|
||||
assertPracticeStatus(t, ctx, harness.pool, gamma.practiceID, "pending", "")
|
||||
if accepted := runner.runIDsSince(runsBefore); len(accepted) != 1 {
|
||||
t.Fatalf("the runner accepted %d runs before the repeat, want 1", len(accepted))
|
||||
}
|
||||
if _, claimed, err := queue.worker.RunOnce(ctx); err != nil || claimed {
|
||||
t.Fatalf("claim before the backoff = %v, error %v; want none", claimed, err)
|
||||
}
|
||||
|
||||
clock.advance(practiceRunnerBackoff)
|
||||
if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished {
|
||||
t.Fatalf("repeat after the backoff = %q, error %v; want finished", outcome, err)
|
||||
}
|
||||
accepted := runner.runIDsSince(runsBefore)
|
||||
job = readRunnerJob(t, ctx, harness.pool, submissionID)
|
||||
if len(accepted) != 1 || job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.runnerRunID.String() != accepted[0] || job.generation != 0 {
|
||||
t.Fatalf("job after the repeat = %+v with runs %v, want the single accepted run finished", job, accepted)
|
||||
}
|
||||
assertPracticeStatus(t, ctx, harness.pool, gamma.practiceID, "finished", "")
|
||||
assertFinalResultCount(t, ctx, harness.pool, gamma.practiceID, 1)
|
||||
requireRunnerRequestIsolated(t, runner, accepted[0], runnerIsolation{
|
||||
candidate: gamma, email: "runner-gamma@example.test", submissionID: submissionID,
|
||||
groups: []string{"hidden-1", "hidden-2", "hidden-3"}, forbidden: []string{"public", "custom"},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("a run that outlasts the request timeout is joined on the repeat", func(t *testing.T) {
|
||||
delta := newPracticeCandidate(ctx, t, harness, "runner-delta", 40)
|
||||
runsBefore := runner.runCount()
|
||||
runner.failNextAccept("stall")
|
||||
run := createPracticeRun(t, harness, delta, "python", practiceRunnerPythonSource("delta"), nil, "runner-delta-run")
|
||||
|
||||
if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry {
|
||||
t.Fatalf("try that timed out = %q claimed %v, error %v; want retry", outcome, claimed, err)
|
||||
}
|
||||
job := readRunnerJob(t, ctx, harness.pool, run.ID)
|
||||
if job.state != "queued" || job.attempts != 1 || job.generation != 0 || job.errorClass != "runner_unavailable" || job.resultStored {
|
||||
t.Fatalf("job after the timeout = %+v, want queued on the same run key", job)
|
||||
}
|
||||
if read := readPracticeRunnerRun(t, harness, delta, run.ID); read.State != "queued" || read.FailureReason != nil || read.Result != nil {
|
||||
t.Fatalf("run while the try is repeated = %+v, want queued", read)
|
||||
}
|
||||
|
||||
clock.advance(practiceRunnerBackoff)
|
||||
if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished {
|
||||
t.Fatalf("repeat after the timeout = %q, error %v; want finished", outcome, err)
|
||||
}
|
||||
accepted := runner.runIDsSince(runsBefore)
|
||||
job = readRunnerJob(t, ctx, harness.pool, run.ID)
|
||||
if len(accepted) != 1 || job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.runnerRunID.String() != accepted[0] {
|
||||
t.Fatalf("job after the repeat = %+v with runs %v, want the single accepted run finished", job, accepted)
|
||||
}
|
||||
if read := readPracticeRunnerRun(t, harness, delta, run.ID); read.State != "finished" || read.Result == nil || read.Result.Outcome != "accepted" {
|
||||
t.Fatalf("run after the repeat = %+v, want finished and accepted", read)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a worker restarted with a new client joins the run of the dead one", func(t *testing.T) {
|
||||
epsilon := newPracticeCandidate(ctx, t, harness, "runner-epsilon", 50)
|
||||
submitPracticeFinal(t, ctx, harness, epsilon, "runner-epsilon-final")
|
||||
submissionID := latestPracticeSubmission(t, ctx, harness.pool, epsilon.practiceID, "final")
|
||||
runsBefore := runner.runCount()
|
||||
runner.hold(true)
|
||||
defer runner.hold(false)
|
||||
|
||||
crashedPool := newPoolFor(ctx, t, harness.databaseURL)
|
||||
crashed := queue.workerOn(t, crashedPool)
|
||||
crashCtx, crash := context.WithCancel(ctx)
|
||||
crashedDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(crashedDone)
|
||||
_, _, _ = crashed.worker.RunOnce(crashCtx)
|
||||
}()
|
||||
waitForRunnerRuns(t, ctx, runner, runsBefore+1)
|
||||
// The process dies: its connections are gone, so the lease keeps the
|
||||
// job running.
|
||||
crashedPool.Close()
|
||||
crash()
|
||||
<-crashedDone
|
||||
started := runner.runIDsSince(runsBefore)
|
||||
if len(started) != 1 {
|
||||
t.Fatalf("the dead worker started %d runs, want 1", len(started))
|
||||
}
|
||||
|
||||
// The new process builds a new client from the same settings.
|
||||
restartedRig := newPracticeQueueRig(t, harness.pool, runner.client(t), clock)
|
||||
clock.advance(practiceQueueLease + time.Second)
|
||||
runner.hold(false)
|
||||
if outcome, claimed, err := restartedRig.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeFinished {
|
||||
t.Fatalf("restarted worker = %q claimed %v, error %v; want the job finished", outcome, claimed, err)
|
||||
}
|
||||
job := readRunnerJob(t, ctx, harness.pool, submissionID)
|
||||
if job.state != "finished" || job.attempts != 1 || job.generation != 0 || job.runnerRunID == nil || job.runnerRunID.String() != started[0] || !job.resultStored {
|
||||
t.Fatalf("recovered job = %+v, want finished on the run %s with one counted takeover", job, started[0])
|
||||
}
|
||||
if all := runner.runIDsSince(runsBefore); len(all) != 1 {
|
||||
t.Fatalf("the runner holds %d runs for the submission, want 1", len(all))
|
||||
}
|
||||
assertFinalResultCount(t, ctx, harness.pool, epsilon.practiceID, 1)
|
||||
assertPracticeStatus(t, ctx, harness.pool, epsilon.practiceID, "finished", "")
|
||||
})
|
||||
|
||||
t.Run("a stopped runner leaves a retryable state and changes nothing about the candidate", func(t *testing.T) {
|
||||
stopped := newPracticeRunnerFixture(t)
|
||||
stoppedQueue := newPracticeQueueRig(t, harness.pool, stopped.client(t), clock)
|
||||
stopped.stop()
|
||||
|
||||
zeta := newPracticeCandidate(ctx, t, harness, "runner-zeta", 60)
|
||||
before := candidateGradeState(t, ctx, harness.pool, zeta)
|
||||
run := createPracticeRun(t, harness, zeta, "python", practiceRunnerPythonSource("zeta"), nil, "runner-zeta-run")
|
||||
|
||||
// Two tries fail and wait for their backoff; the run stays queued,
|
||||
// which tells the client to read it again.
|
||||
for try := 1; try <= 2; try++ {
|
||||
if outcome, claimed, err := stoppedQueue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry {
|
||||
t.Fatalf("try %d on a stopped runner = %q claimed %v, error %v; want retry", try, outcome, claimed, err)
|
||||
}
|
||||
read := readPracticeRunnerRun(t, harness, zeta, run.ID)
|
||||
if read.State != "queued" || read.FailureReason != nil || read.Result != nil || read.FinishedAt != nil {
|
||||
t.Fatalf("run after try %d = %+v, want queued without a verdict", try, read)
|
||||
}
|
||||
clock.advance(practiceRunnerBackoff * 2)
|
||||
}
|
||||
if outcome, _, err := stoppedQueue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFailed {
|
||||
t.Fatalf("last try on a stopped runner = %q, error %v; want failed without a verdict", outcome, err)
|
||||
}
|
||||
read := readPracticeRunnerRun(t, harness, zeta, run.ID)
|
||||
if read.State != "failed" || read.FailureReason == nil || *read.FailureReason != "sandbox_error" || read.Result != nil || read.FinishedAt == nil {
|
||||
t.Fatalf("run after the last try = %+v, want failed with sandbox_error and no result", read)
|
||||
}
|
||||
job := readRunnerJob(t, ctx, harness.pool, run.ID)
|
||||
if job.state != "failed" || job.errorClass != "runner_unavailable" || job.resultStored || job.runnerRunID != nil {
|
||||
t.Fatalf("job after the last try = %+v, want failed with no result and no runner run", job)
|
||||
}
|
||||
if after := candidateGradeState(t, ctx, harness.pool, zeta); after != before {
|
||||
t.Fatalf("candidate state changed by an infrastructure failure:\nbefore %s\nafter %s", before, after)
|
||||
}
|
||||
assertPracticeStatus(t, ctx, harness.pool, zeta.practiceID, "not_started", "")
|
||||
|
||||
// The failure is retryable: the same practice takes a new run, and the
|
||||
// working runner finishes it.
|
||||
again := createPracticeRun(t, harness, zeta, "python", practiceRunnerPythonSource("zeta-again"), nil, "runner-zeta-again")
|
||||
queue.drain(t, ctx)
|
||||
if read := readPracticeRunnerRun(t, harness, zeta, again.ID); read.State != "finished" || read.Result == nil || read.Result.Outcome != "accepted" {
|
||||
t.Fatalf("run after the runner came back = %+v, want finished and accepted", read)
|
||||
}
|
||||
|
||||
// A final solution is no verdict either: the practice fails without a
|
||||
// grade and accepts the solution again.
|
||||
eta := newPracticeCandidate(ctx, t, harness, "runner-eta", 70)
|
||||
etaBefore := candidateGradeState(t, ctx, harness.pool, eta)
|
||||
submitPracticeFinal(t, ctx, harness, eta, "runner-eta-final")
|
||||
stoppedQueue.drain(t, ctx)
|
||||
assertPracticeStatus(t, ctx, harness.pool, eta.practiceID, "failed", "sandbox_error")
|
||||
assertNoPracticeResult(t, ctx, harness.pool, eta.practiceID)
|
||||
if after := candidateGradeState(t, ctx, harness.pool, eta); after != etaBefore {
|
||||
t.Fatalf("candidate state changed by an infrastructure failure:\nbefore %s\nafter %s", etaBefore, after)
|
||||
}
|
||||
submitPracticeFinal(t, ctx, harness, eta, "runner-eta-final-again")
|
||||
queue.drain(t, ctx)
|
||||
assertPracticeStatus(t, ctx, harness.pool, eta.practiceID, "finished", "")
|
||||
assertFinalResultCount(t, ctx, harness.pool, eta.practiceID, 1)
|
||||
})
|
||||
|
||||
assertEverySubmissionHasOneJob(t, ctx, harness.pool)
|
||||
assertEveryRunnerRunHasOneResult(t, ctx, harness.pool)
|
||||
}
|
||||
|
||||
func practiceRunnerPythonSource(marker string) string {
|
||||
return practicePythonSum + "# marker: " + marker + "\n"
|
||||
}
|
||||
|
||||
func practiceRunnerGoSource(marker string) string {
|
||||
return practiceGoSum + "// marker: " + marker + "\n"
|
||||
}
|
||||
|
||||
// practiceRunnerRun is a created run as the API answers it.
|
||||
type practiceRunnerRun struct {
|
||||
ID uuid.UUID
|
||||
State string
|
||||
}
|
||||
|
||||
func createPracticeRun(
|
||||
t *testing.T,
|
||||
harness *practiceHarness,
|
||||
candidate practiceCandidate,
|
||||
language, source string,
|
||||
tests []domain.PracticeTest,
|
||||
key string,
|
||||
) practiceRunnerRun {
|
||||
t.Helper()
|
||||
response := practiceRunRequest(t, harness, candidate, practiceRunBody(t, candidate.practiceID, language, source, tests), key)
|
||||
if response.Code != http.StatusAccepted {
|
||||
t.Fatalf("create %s run = %d %s", language, response.Code, response.Body.String())
|
||||
}
|
||||
run := decodePracticeRun(t, response)
|
||||
return practiceRunnerRun{ID: run.ID, State: run.State}
|
||||
}
|
||||
|
||||
// practiceRunnerRunBody decodes the fields of a run that these tests read.
|
||||
type practiceRunnerRunBody struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
State string `json:"state"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
FailureReason *string `json:"failure_reason"`
|
||||
Result *struct {
|
||||
Outcome string `json:"outcome"`
|
||||
Tests []struct {
|
||||
Source string `json:"source"`
|
||||
Index int `json:"index"`
|
||||
Outcome string `json:"outcome"`
|
||||
Diagnostic *string `json:"diagnostic"`
|
||||
} `json:"tests"`
|
||||
} `json:"result"`
|
||||
}
|
||||
|
||||
// readPracticeRunnerRun reads a run of the candidate's own attempt through
|
||||
// the API and checks that the response is public.
|
||||
func readPracticeRunnerRun(t *testing.T, harness *practiceHarness, candidate practiceCandidate, runID uuid.UUID) practiceRunnerRunBody {
|
||||
t.Helper()
|
||||
response := practiceRunRead(t, harness, candidate, candidate.attemptID, runID)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("read run = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
assertPracticeResponseIsPublic(t, response)
|
||||
var run practiceRunnerRunBody
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &run); err != nil || run.ID != runID {
|
||||
t.Fatalf("run response %s: %v", response.Body.String(), err)
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
// runnerJobRow is the execution job of a submission with its stored outcome.
|
||||
type runnerJobRow struct {
|
||||
state string
|
||||
attempts int
|
||||
generation int
|
||||
errorClass string
|
||||
runnerRunID *uuid.UUID
|
||||
resultStored bool
|
||||
}
|
||||
|
||||
func readRunnerJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool, submissionID uuid.UUID) runnerJobRow {
|
||||
t.Helper()
|
||||
var job runnerJobRow
|
||||
var class *string
|
||||
if err := pool.QueryRow(ctx, `SELECT job.state, job.attempts, job.generation, job.last_error_class, job.runner_run_id,
|
||||
submission.result IS NOT NULL
|
||||
FROM assessment_practice_jobs AS job
|
||||
JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id
|
||||
WHERE job.submission_id = $1`, submissionID).Scan(
|
||||
&job.state, &job.attempts, &job.generation, &class, &job.runnerRunID, &job.resultStored); err != nil {
|
||||
t.Fatalf("read practice job: %v", err)
|
||||
}
|
||||
if class != nil {
|
||||
job.errorClass = *class
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
func assertFinalResultCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, want int) {
|
||||
t.Helper()
|
||||
var stored int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions
|
||||
WHERE practice_id = $1 AND mode = 'final' AND result IS NOT NULL`, practiceID).Scan(&stored); err != nil {
|
||||
t.Fatalf("count final results: %v", err)
|
||||
}
|
||||
if stored != want {
|
||||
t.Fatalf("%d final results stored, want %d", stored, want)
|
||||
}
|
||||
}
|
||||
|
||||
// assertEveryRunnerRunHasOneResult checks that a runner run ID belongs to one
|
||||
// finished job that has a result, and that no unfinished job has one.
|
||||
func assertEveryRunnerRunHasOneResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
var duplicated, withoutResult int
|
||||
if err := pool.QueryRow(ctx, `SELECT
|
||||
(SELECT count(*) FROM (SELECT runner_run_id FROM assessment_practice_jobs
|
||||
WHERE runner_run_id IS NOT NULL GROUP BY runner_run_id HAVING count(*) > 1) AS repeated),
|
||||
(SELECT count(*) FROM assessment_practice_jobs AS job
|
||||
JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id
|
||||
WHERE job.state = 'finished' AND job.runner_run_id IS NOT NULL AND submission.result IS NULL)`).Scan(&duplicated, &withoutResult); err != nil {
|
||||
t.Fatalf("check runner runs: %v", err)
|
||||
}
|
||||
if duplicated != 0 || withoutResult != 0 {
|
||||
t.Fatalf("%d runner runs repeat and %d have no result, want none", duplicated, withoutResult)
|
||||
}
|
||||
}
|
||||
|
||||
// candidateGradeState is what an infrastructure failure must not change: the
|
||||
// confirmed categories, the results, and the state and version of the attempt.
|
||||
func candidateGradeState(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidate practiceCandidate) string {
|
||||
t.Helper()
|
||||
var state string
|
||||
if err := pool.QueryRow(ctx, `SELECT jsonb_build_object(
|
||||
'categories', coalesce((SELECT jsonb_agg(to_jsonb(category) ORDER BY category.specialization)
|
||||
FROM candidate_assessment_categories AS category WHERE category.candidate_id = $1), '[]'::jsonb),
|
||||
'results', (SELECT count(*) FROM assessment_attempt_results WHERE user_id = $1),
|
||||
'attempt', (SELECT jsonb_build_object('state', attempt.state, 'version', attempt.version)
|
||||
FROM assessment_attempts AS attempt WHERE attempt.id = $2))::text`,
|
||||
candidate.userID, candidate.attemptID).Scan(&state); err != nil {
|
||||
t.Fatalf("read candidate grade state: %v", err)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func waitForRunnerRuns(t *testing.T, ctx context.Context, runner *practiceRunnerFixture, want int) {
|
||||
t.Helper()
|
||||
for ctx.Err() == nil {
|
||||
if runner.runCount() >= want {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("runner did not accept %d runs", want)
|
||||
}
|
||||
|
||||
// runnerIsolation says what the runner may see of one submission.
|
||||
type runnerIsolation struct {
|
||||
candidate practiceCandidate
|
||||
email string
|
||||
submissionID uuid.UUID
|
||||
// groups are the group IDs of the request, in order.
|
||||
groups []string
|
||||
// forbidden are texts that the request must not carry.
|
||||
forbidden []string
|
||||
}
|
||||
|
||||
// requireRunnerRequestIsolated checks the wire form of a run: the path holds
|
||||
// an opaque run ID, the headers hold only the transport and the service
|
||||
// token, and the body holds the language, the source, the limits, and the
|
||||
// groups, with nothing about the candidate, the attempt, or the submission.
|
||||
func requireRunnerRequestIsolated(t *testing.T, runner *practiceRunnerFixture, runID string, want runnerIsolation) {
|
||||
t.Helper()
|
||||
var puts []runnerCall
|
||||
for _, call := range runner.callsFor(runID) {
|
||||
if call.Method == http.MethodPut {
|
||||
puts = append(puts, call)
|
||||
}
|
||||
}
|
||||
if len(puts) == 0 {
|
||||
t.Fatalf("the runner saw no PUT of run %s", runID)
|
||||
}
|
||||
identifiers := []string{
|
||||
want.candidate.userID.String(), want.candidate.attemptID.String(), want.candidate.practiceID.String(),
|
||||
want.candidate.additionalID.String(), want.submissionID.String(), want.email, want.candidate.cookie, want.candidate.csrf,
|
||||
}
|
||||
if slices.Contains(identifiers, runID) {
|
||||
t.Fatalf("the run ID %s is a business identifier", runID)
|
||||
}
|
||||
parsed, err := uuid.Parse(runID)
|
||||
if err != nil || parsed.Version() != 8 {
|
||||
t.Fatalf("run ID %q is not an opaque version 8 UUID: %v", runID, err)
|
||||
}
|
||||
allowedHeaders := []string{"Accept", "Accept-Encoding", "Authorization", "Content-Length", "Content-Type", "User-Agent"}
|
||||
for _, call := range puts {
|
||||
for name, values := range call.Header {
|
||||
if !slices.Contains(allowedHeaders, name) {
|
||||
t.Fatalf("request to the runner carries the header %s", name)
|
||||
}
|
||||
for _, value := range values {
|
||||
for _, identifier := range identifiers {
|
||||
if strings.Contains(value, identifier) {
|
||||
t.Fatalf("header %s carries an identifier of the candidate", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
body := string(call.Body)
|
||||
for _, text := range append(append([]string(nil), identifiers...), want.forbidden...) {
|
||||
if text != "" && strings.Contains(body, text) {
|
||||
t.Fatalf("request to the runner carries %q: %s", text, body)
|
||||
}
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(call.Body, &fields); err != nil {
|
||||
t.Fatalf("decode the request to the runner: %v", err)
|
||||
}
|
||||
names := make([]string, 0, len(fields))
|
||||
for name := range fields {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
if !slices.Equal(names, []string{"groups", "language", "limits", "source"}) {
|
||||
t.Fatalf("request to the runner has the fields %v, want groups, language, limits, and source only", names)
|
||||
}
|
||||
var groups []struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(fields["groups"], &groups); err != nil {
|
||||
t.Fatalf("decode the groups sent to the runner: %v", err)
|
||||
}
|
||||
got := make([]string, 0, len(groups))
|
||||
for _, group := range groups {
|
||||
got = append(got, group.ID)
|
||||
}
|
||||
if !slices.Equal(got, want.groups) {
|
||||
t.Fatalf("groups sent to the runner = %v, want %v", got, want.groups)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
coderunner "lincodex/backend/internal/adapter/secondary/code_runner"
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
||||
)
|
||||
|
||||
const (
|
||||
practiceRunnerToken = "fixture-token-0123456789abcdef0123456789abcdef"
|
||||
practiceRunnerRunKey = "fixture-run-key-0123456789abcdef0123456789abcdef"
|
||||
// practiceRunnerTimeout is the request timeout of the client under test.
|
||||
// It is short so that a stalled answer ends a try quickly.
|
||||
practiceRunnerTimeout = 750 * time.Millisecond
|
||||
// practiceRunnerStall outlasts practiceRunnerTimeout.
|
||||
practiceRunnerStall = 10 * time.Second
|
||||
// practiceRunnerPrefix is the path of a run in the runner protocol.
|
||||
practiceRunnerPrefix = "/v1/runs/"
|
||||
)
|
||||
|
||||
// Sources of the two programs that the fixture recognizes. Each reads two
|
||||
// integers and prints their sum.
|
||||
const (
|
||||
practicePythonSum = "print(sum(map(int, input().split())))\n"
|
||||
practiceGoSum = "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar a, b int\n\tfmt.Scan(&a, &b)\n\tfmt.Println(a + b)\n}\n"
|
||||
)
|
||||
|
||||
// runnerCall is what the fixture saw on the wire.
|
||||
type runnerCall struct {
|
||||
Method string
|
||||
Path string
|
||||
Header http.Header
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// fixtureRun is one run that the fixture holds.
|
||||
type fixtureRun struct {
|
||||
ID string
|
||||
Request api.RunRequest
|
||||
Body []byte
|
||||
Result api.RunResult
|
||||
fingerprint [sha256.Size]byte
|
||||
}
|
||||
|
||||
// practiceRunnerFixture is a local stand-in for the code runner. It speaks
|
||||
// the protocol of api/runner over TLS 1.3 like the production runner: a
|
||||
// bearer token, PUT and GET of /v1/runs/{id}, a run held once per run ID, and
|
||||
// 422 for the same ID with another payload. It does not run code: it
|
||||
// recognizes the two sum programs of this test file and compares their
|
||||
// output with the expected output of each test, so the output of a program
|
||||
// follows its source and its input.
|
||||
type practiceRunnerFixture struct {
|
||||
server *httptest.Server
|
||||
|
||||
mu sync.Mutex
|
||||
runs map[string]*fixtureRun
|
||||
order []string
|
||||
calls []runnerCall
|
||||
// holding keeps every run running until it is turned off.
|
||||
holding bool
|
||||
// afterAccept is applied once to the next newly accepted run: "cut"
|
||||
// drops the connection without an answer, "stall" delays the answer past
|
||||
// the client timeout. In both cases the run exists on the runner.
|
||||
afterAccept string
|
||||
}
|
||||
|
||||
func newPracticeRunnerFixture(t *testing.T) *practiceRunnerFixture {
|
||||
t.Helper()
|
||||
fixture := &practiceRunnerFixture{runs: map[string]*fixtureRun{}}
|
||||
fixture.server = httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve))
|
||||
fixture.server.TLS = &tls.Config{MinVersion: tls.VersionTLS13}
|
||||
fixture.server.StartTLS()
|
||||
t.Cleanup(fixture.server.Close)
|
||||
return fixture
|
||||
}
|
||||
|
||||
// client builds a new client of the runner, as a restarted process would.
|
||||
func (fixture *practiceRunnerFixture) client(t *testing.T) *coderunner.Client {
|
||||
t.Helper()
|
||||
client, err := coderunner.NewClient(coderunner.Settings{
|
||||
BaseURL: fixture.server.URL, Token: practiceRunnerToken, RunKey: practiceRunnerRunKey,
|
||||
CAPEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.server.Certificate().Raw}),
|
||||
RequestTimeout: practiceRunnerTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("coderunner.NewClient() error = %v", err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// stop shuts the runner down; later connections are refused.
|
||||
func (fixture *practiceRunnerFixture) stop() { fixture.server.Close() }
|
||||
|
||||
func (fixture *practiceRunnerFixture) hold(holding bool) {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
fixture.holding = holding
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) failNextAccept(how string) {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
fixture.afterAccept = how
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) runCount() int {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
return len(fixture.order)
|
||||
}
|
||||
|
||||
// runIDsSince returns the run IDs that the fixture accepted after it held
|
||||
// the first count runs.
|
||||
func (fixture *practiceRunnerFixture) runIDsSince(count int) []string {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
return append([]string(nil), fixture.order[count:]...)
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) run(id string) (fixtureRun, bool) {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
run, found := fixture.runs[id]
|
||||
if !found {
|
||||
return fixtureRun{}, false
|
||||
}
|
||||
return *run, true
|
||||
}
|
||||
|
||||
// callsFor returns the requests that named the run.
|
||||
func (fixture *practiceRunnerFixture) callsFor(id string) []runnerCall {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
var calls []runnerCall
|
||||
for _, call := range fixture.calls {
|
||||
if call.Path == practiceRunnerPrefix+id {
|
||||
calls = append(calls, call)
|
||||
}
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) serve(writer http.ResponseWriter, request *http.Request) {
|
||||
body, _ := io.ReadAll(request.Body)
|
||||
fixture.mu.Lock()
|
||||
fixture.calls = append(fixture.calls, runnerCall{
|
||||
Method: request.Method, Path: request.URL.Path, Header: request.Header.Clone(), Body: body,
|
||||
})
|
||||
fixture.mu.Unlock()
|
||||
|
||||
if request.Header.Get("Authorization") != "Bearer "+practiceRunnerToken {
|
||||
writeRunnerProblem(writer, http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
|
||||
return
|
||||
}
|
||||
id := strings.TrimPrefix(request.URL.Path, practiceRunnerPrefix)
|
||||
switch request.Method {
|
||||
case http.MethodPut:
|
||||
fixture.put(writer, request, id, body)
|
||||
case http.MethodGet:
|
||||
fixture.get(writer, id)
|
||||
default:
|
||||
writeRunnerProblem(writer, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) put(writer http.ResponseWriter, request *http.Request, id string, body []byte) {
|
||||
var payload api.RunRequest
|
||||
if err := payload.UnmarshalJSON(body); err != nil {
|
||||
writeRunnerProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
return
|
||||
}
|
||||
runID, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
writeRunnerProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
return
|
||||
}
|
||||
fingerprint := sha256.Sum256(body)
|
||||
|
||||
fixture.mu.Lock()
|
||||
if existing, found := fixture.runs[id]; found {
|
||||
defer fixture.mu.Unlock()
|
||||
if existing.fingerprint != fingerprint {
|
||||
writeRunnerProblem(writer, http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused)
|
||||
return
|
||||
}
|
||||
writeRunnerStatus(writer, http.StatusOK, fixture.statusLocked(existing))
|
||||
return
|
||||
}
|
||||
fixture.runs[id] = &fixtureRun{
|
||||
ID: id, Request: payload, Body: body, Result: evaluateFixtureRun(payload), fingerprint: fingerprint,
|
||||
}
|
||||
fixture.order = append(fixture.order, id)
|
||||
action := fixture.afterAccept
|
||||
fixture.afterAccept = ""
|
||||
fixture.mu.Unlock()
|
||||
|
||||
switch action {
|
||||
case "cut":
|
||||
// The run is accepted and the connection ends without an answer.
|
||||
panic(http.ErrAbortHandler)
|
||||
case "stall":
|
||||
select {
|
||||
case <-time.After(practiceRunnerStall):
|
||||
case <-request.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
writeRunnerStatus(writer, http.StatusAccepted, api.RunStatus{RunID: runID, State: api.RunStateRunning})
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) get(writer http.ResponseWriter, id string) {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
run, found := fixture.runs[id]
|
||||
if !found {
|
||||
writeRunnerProblem(writer, http.StatusNotFound, api.ProblemCodeNotFound)
|
||||
return
|
||||
}
|
||||
writeRunnerStatus(writer, http.StatusOK, fixture.statusLocked(run))
|
||||
}
|
||||
|
||||
func (fixture *practiceRunnerFixture) statusLocked(run *fixtureRun) api.RunStatus {
|
||||
status := api.RunStatus{RunID: uuid.MustParse(run.ID), State: api.RunStateRunning}
|
||||
if !fixture.holding {
|
||||
status.State = api.RunStateFinished
|
||||
status.Result = api.NewOptRunResult(run.Result)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// evaluateFixtureRun produces the result of a run: every test of a group runs
|
||||
// until the first one that fails, and a failed public test carries the output
|
||||
// of the program as its diagnostic, which the practice API shows.
|
||||
func evaluateFixtureRun(request api.RunRequest) api.RunResult {
|
||||
result := api.RunResult{Outcome: api.RunOutcomeAccepted, DurationMs: 25}
|
||||
for _, group := range request.Groups {
|
||||
groupResult := api.GroupResult{
|
||||
ID: group.ID, Visibility: group.Visibility, Outcome: api.RunOutcomeAccepted, TotalTests: int32(len(group.Tests)),
|
||||
}
|
||||
for _, test := range group.Tests {
|
||||
output := fixtureProgramOutput(request.Source, test.Input)
|
||||
testResult := api.TestResult{ID: test.ID, Outcome: api.RunOutcomeAccepted, TimeMs: 3, WallTimeMs: 4, MemoryKB: 1024}
|
||||
if output != strings.TrimSpace(test.ExpectedOutput) {
|
||||
testResult.Outcome = api.RunOutcomeWrongAnswer
|
||||
if group.Visibility == api.TestVisibilityPublic {
|
||||
testResult.Diagnostic = api.NewOptString("got " + output)
|
||||
}
|
||||
groupResult.Outcome = api.RunOutcomeWrongAnswer
|
||||
groupResult.Tests = append(groupResult.Tests, testResult)
|
||||
break
|
||||
}
|
||||
groupResult.PassedTests++
|
||||
groupResult.Tests = append(groupResult.Tests, testResult)
|
||||
}
|
||||
if result.Outcome == api.RunOutcomeAccepted {
|
||||
result.Outcome = groupResult.Outcome
|
||||
}
|
||||
result.Groups = append(result.Groups, groupResult)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// fixtureProgramOutput is the output of the sum programs for an input: the
|
||||
// sum of its integer words. Another program prints nothing.
|
||||
func fixtureProgramOutput(source, input string) string {
|
||||
if !strings.Contains(source, "sum(map(int, input().split()))") && !strings.Contains(source, "fmt.Println(a + b)") {
|
||||
return ""
|
||||
}
|
||||
total := 0
|
||||
for _, word := range strings.Fields(input) {
|
||||
if value, err := strconv.Atoi(word); err == nil {
|
||||
total += value
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(total)
|
||||
}
|
||||
|
||||
func writeRunnerStatus(writer http.ResponseWriter, code int, status api.RunStatus) {
|
||||
// The generated types encode themselves; json.Marshal cannot encode an
|
||||
// unset optional field.
|
||||
body, err := status.MarshalJSON()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
writeRunnerJSON(writer, code, "application/json", body)
|
||||
}
|
||||
|
||||
func writeRunnerProblem(writer http.ResponseWriter, code int, problem api.ProblemCode) {
|
||||
body, err := (&api.Problem{
|
||||
Type: "urn:lincodex:problem:" + string(problem), Title: "Problem", Status: int32(code), Code: problem,
|
||||
}).MarshalJSON()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
writeRunnerJSON(writer, code, "application/problem+json", body)
|
||||
}
|
||||
|
||||
func writeRunnerJSON(writer http.ResponseWriter, code int, contentType string, body []byte) {
|
||||
writer.Header().Set("Content-Type", contentType)
|
||||
writer.Header().Set("Content-Length", strconv.Itoa(len(body)))
|
||||
writer.WriteHeader(code)
|
||||
_, _ = writer.Write(body)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
@@ -153,8 +154,16 @@ func (store *PracticeJobStore) Requeue(ctx context.Context, job outbound.Claimed
|
||||
return updated == 1, nil
|
||||
}
|
||||
|
||||
func (store *PracticeJobStore) Complete(ctx context.Context, job outbound.ClaimedPracticeJob, result domain.PracticeRunResult) (bool, error) {
|
||||
func (store *PracticeJobStore) Complete(
|
||||
ctx context.Context,
|
||||
job outbound.ClaimedPracticeJob,
|
||||
runnerRunID uuid.UUID,
|
||||
result domain.PracticeRunResult,
|
||||
) (bool, error) {
|
||||
const location = "PracticeJobStore.Complete"
|
||||
if runnerRunID == uuid.Nil {
|
||||
return false, errors.New(location + " - runner run ID must be set")
|
||||
}
|
||||
if err := result.Validate(); err != nil {
|
||||
return false, fmt.Errorf("%s - validate result: %w", location, err)
|
||||
}
|
||||
@@ -177,7 +186,7 @@ func (store *PracticeJobStore) Complete(ctx context.Context, job outbound.Claime
|
||||
if stored != 1 {
|
||||
return outbound.ErrPracticeResultExists
|
||||
}
|
||||
if err := finishPracticeJob(ctx, queries, job, practiceJobFinished, ""); err != nil {
|
||||
if err := finishPracticeJob(ctx, queries, job, practiceJobFinished, "", runnerRunID); err != nil {
|
||||
return err
|
||||
}
|
||||
if mode == domain.PracticeModeFinal {
|
||||
@@ -205,7 +214,7 @@ func (store *PracticeJobStore) Fail(ctx context.Context, job outbound.ClaimedPra
|
||||
if err != nil || !locked {
|
||||
return err
|
||||
}
|
||||
if err := finishPracticeJob(ctx, queries, job, practiceJobFailed, class); err != nil {
|
||||
if err := finishPracticeJob(ctx, queries, job, practiceJobFailed, class, uuid.Nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if mode == domain.PracticeModeFinal {
|
||||
@@ -247,9 +256,15 @@ func finishPracticeJob(
|
||||
job outbound.ClaimedPracticeJob,
|
||||
state string,
|
||||
class outbound.PracticeJobErrorClass,
|
||||
runnerRunID uuid.UUID,
|
||||
) error {
|
||||
// A failed job has no run ID: uuid.Nil stores NULL.
|
||||
var runnerRun pgtype.UUID
|
||||
if runnerRunID != uuid.Nil {
|
||||
runnerRun = pgUUID(runnerRunID)
|
||||
}
|
||||
finished, err := queries.FinishAssessmentPracticeJob(ctx, sqlc.FinishAssessmentPracticeJobParams{
|
||||
State: state, ErrorClass: pgOptionalText(string(class)), SubmissionID: pgUUID(job.SubmissionID),
|
||||
State: state, ErrorClass: pgOptionalText(string(class)), RunnerRunID: runnerRun, SubmissionID: pgUUID(job.SubmissionID),
|
||||
LeaseOwner: pgUUID(job.LeaseOwner), StartedAt: timestamp(job.StartedAt),
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -170,31 +170,35 @@ const finishAssessmentPracticeJob = `-- name: FinishAssessmentPracticeJob :execr
|
||||
UPDATE assessment_practice_jobs
|
||||
SET
|
||||
state = $1,
|
||||
runner_run_id = $2,
|
||||
finished_at = greatest(created_at, clock_timestamp()),
|
||||
last_error_class = coalesce($2, last_error_class),
|
||||
last_error_class = coalesce($3, last_error_class),
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = greatest(updated_at, clock_timestamp())
|
||||
WHERE
|
||||
submission_id = $3
|
||||
submission_id = $4
|
||||
AND state = 'running'
|
||||
AND lease_owner = $4
|
||||
AND started_at = $5
|
||||
AND lease_owner = $5
|
||||
AND started_at = $6
|
||||
`
|
||||
|
||||
type FinishAssessmentPracticeJobParams struct {
|
||||
State string
|
||||
RunnerRunID pgtype.UUID
|
||||
ErrorClass pgtype.Text
|
||||
SubmissionID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
StartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Ends a running try as finished or failed.
|
||||
// Ends a running try as finished or failed. A finished job keeps the run ID
|
||||
// of the runner run that produced its result.
|
||||
func (q *Queries) FinishAssessmentPracticeJob(ctx context.Context, arg FinishAssessmentPracticeJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, finishAssessmentPracticeJob,
|
||||
arg.State,
|
||||
arg.RunnerRunID,
|
||||
arg.ErrorClass,
|
||||
arg.SubmissionID,
|
||||
arg.LeaseOwner,
|
||||
|
||||
@@ -256,6 +256,7 @@ type AssessmentPracticeJob struct {
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
StartedAt pgtype.Timestamptz
|
||||
LastErrorClass pgtype.Text
|
||||
RunnerRunID pgtype.UUID
|
||||
}
|
||||
|
||||
type AssessmentPracticeSubmission struct {
|
||||
|
||||
@@ -307,7 +307,8 @@ type Querier interface {
|
||||
// made at or after reserved_since. A retry of the delivery inside the
|
||||
// provider's idempotency window reuses it instead of counting again.
|
||||
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
|
||||
// Ends a running try as finished or failed.
|
||||
// Ends a running try as finished or failed. A finished job keeps the run ID
|
||||
// of the runner run that produced its result.
|
||||
FinishAssessmentPracticeJob(ctx context.Context, arg FinishAssessmentPracticeJobParams) (int64, error)
|
||||
// Reads the durable active deletion request when an earlier request already
|
||||
// exists. A completed request does not suppress a later explicit request.
|
||||
|
||||
@@ -97,11 +97,12 @@ type PracticeJobStore interface {
|
||||
// Requeue puts a try back into the queue; held is false when the job no
|
||||
// longer belongs to the try.
|
||||
Requeue(ctx context.Context, job ClaimedPracticeJob, requeue PracticeRequeue) (held bool, err error)
|
||||
// Complete stores the result of the submission once, finishes the job,
|
||||
// and, for the latest final submission of a pending practice, finishes
|
||||
// the practice, all in one transaction. held is false, with nothing
|
||||
// written, when the job no longer belongs to the try.
|
||||
Complete(ctx context.Context, job ClaimedPracticeJob, result domain.PracticeRunResult) (held bool, err error)
|
||||
// Complete stores the result of the submission once, finishes the job
|
||||
// with the opaque ID of the runner run that produced the result, and, for
|
||||
// the latest final submission of a pending practice, finishes the
|
||||
// practice, all in one transaction. held is false, with nothing written,
|
||||
// when the job no longer belongs to the try.
|
||||
Complete(ctx context.Context, job ClaimedPracticeJob, runnerRunID uuid.UUID, result domain.PracticeRunResult) (held bool, err error)
|
||||
// Fail ends the job as failed with the error class and, for the latest
|
||||
// final submission of a pending practice, marks the practice failed with
|
||||
// sandbox_error. It never stores a verdict.
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
@@ -172,19 +174,23 @@ func (executor *Executor) runnerFailure(ctx context.Context, job outbound.Claime
|
||||
}
|
||||
|
||||
func (executor *Executor) complete(ctx context.Context, job outbound.ClaimedPracticeJob, status outbound.CodeRunStatus) (ExecutionOutcome, error) {
|
||||
if status.Result == nil {
|
||||
// A finished run names the runner run that the stored result belongs to;
|
||||
// a status without a result or a valid run ID is outside the contract.
|
||||
runnerRunID, idErr := uuid.Parse(status.RunID)
|
||||
if status.Result == nil || idErr != nil || runnerRunID == uuid.Nil {
|
||||
return executor.runnerFailure(ctx, job, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
storeCtx, cancel := executor.storeContext(ctx)
|
||||
defer cancel()
|
||||
held, err := executor.store.Complete(storeCtx, job, runResult(*status.Result))
|
||||
held, err := executor.store.Complete(storeCtx, job, runnerRunID, runResult(*status.Result))
|
||||
switch {
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("Executor.complete - store result: %w", err)
|
||||
case !held:
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
executor.logger.Info("practice job finished", jobAttributes(job, slog.String("outcome", string(status.Result.Outcome)))...)
|
||||
executor.logger.Info("practice job finished", jobAttributes(job,
|
||||
slog.String("outcome", string(status.Result.Outcome)), slog.String("runner_run_id", runnerRunID.String()))...)
|
||||
return OutcomeFinished, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -95,6 +95,33 @@ func TestExecutorHandlesPollFailuresAndShutdown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorStoresTheRunnerRunIDWithTheResult(t *testing.T) {
|
||||
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
job := outbound.ClaimedPracticeJob{SubmissionID: uuid.New(), StartedAt: now}
|
||||
|
||||
store := &fakeJobStore{}
|
||||
runner := &fakeRunner{submits: []outbound.CodeRunState{outbound.CodeRunFinished}}
|
||||
executor := testExecutor(t, runner, store, now)
|
||||
if outcome, err := executor.Execute(t.Context(), job); err != nil || outcome != OutcomeFinished {
|
||||
t.Fatalf("Execute() = %q, error %v; want finished", outcome, err)
|
||||
}
|
||||
if store.runnerRunID != uuid.MustParse(fakeRunID) {
|
||||
t.Fatalf("stored runner run ID = %s, want %s", store.runnerRunID, fakeRunID)
|
||||
}
|
||||
|
||||
// A finished run without a valid run ID is outside the runner contract,
|
||||
// so no result is stored and the try is retried on the same key.
|
||||
for _, runID := range []string{"", "not-a-uuid", uuid.Nil.String()} {
|
||||
store = &fakeJobStore{}
|
||||
runner = &fakeRunner{submits: []outbound.CodeRunState{outbound.CodeRunFinished}, runID: &runID}
|
||||
executor = testExecutor(t, runner, store, now)
|
||||
outcome, err := executor.Execute(t.Context(), job)
|
||||
if err != nil || outcome != OutcomeRetry || store.completed || store.requeue.Generation != job.Generation {
|
||||
t.Fatalf("Execute() with run ID %q = %q, error %v, completed %v; want a retry without a result", runID, outcome, err, store.completed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testExecutor(t *testing.T, runner outbound.CodeRunner, store outbound.PracticeJobStore, now time.Time) *Executor {
|
||||
t.Helper()
|
||||
executor, err := NewExecutor(runner, store, func() time.Time { return now }, ExecutionSettings{
|
||||
@@ -108,6 +135,8 @@ func testExecutor(t *testing.T, runner outbound.CodeRunner, store outbound.Pract
|
||||
}
|
||||
|
||||
type fakeRunner struct {
|
||||
// runID overrides the run ID of a finished status when set.
|
||||
runID *string
|
||||
submitErr error
|
||||
pollErr error
|
||||
submits []outbound.CodeRunState
|
||||
@@ -121,7 +150,7 @@ func (runner *fakeRunner) Submit(_ context.Context, request outbound.CodeRunRequ
|
||||
return outbound.CodeRunStatus{}, runner.submitErr
|
||||
}
|
||||
state := runner.submits[min(runner.submitCalls, len(runner.submits))-1]
|
||||
return fakeStatus(state, request), nil
|
||||
return runner.status(state, request), nil
|
||||
}
|
||||
|
||||
func (runner *fakeRunner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
@@ -129,9 +158,20 @@ func (runner *fakeRunner) Poll(_ context.Context, request outbound.CodeRunReques
|
||||
if runner.pollErr != nil {
|
||||
return outbound.CodeRunStatus{}, runner.pollErr
|
||||
}
|
||||
return fakeStatus(outbound.CodeRunFinished, request), nil
|
||||
return runner.status(outbound.CodeRunFinished, request), nil
|
||||
}
|
||||
|
||||
func (runner *fakeRunner) status(state outbound.CodeRunState, request outbound.CodeRunRequest) outbound.CodeRunStatus {
|
||||
status := fakeStatus(state, request)
|
||||
if runner.runID != nil {
|
||||
status.RunID = *runner.runID
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// fakeRunID is the opaque run ID that the fake runner reports.
|
||||
const fakeRunID = "0a1b2c3d-4e5f-8a6b-8c7d-9e0f1a2b3c4d"
|
||||
|
||||
func fakeStatus(state outbound.CodeRunState, request outbound.CodeRunRequest) outbound.CodeRunStatus {
|
||||
if state != outbound.CodeRunFinished {
|
||||
return outbound.CodeRunStatus{State: state}
|
||||
@@ -143,13 +183,15 @@ func fakeStatus(state outbound.CodeRunState, request outbound.CodeRunRequest) ou
|
||||
PassedTests: len(group.Tests), TotalTests: len(group.Tests),
|
||||
})
|
||||
}
|
||||
return outbound.CodeRunStatus{State: state, Result: &result}
|
||||
return outbound.CodeRunStatus{State: state, RunID: fakeRunID, Result: &result}
|
||||
}
|
||||
|
||||
type fakeJobStore struct {
|
||||
requeue outbound.PracticeRequeue
|
||||
failedWith outbound.PracticeJobErrorClass
|
||||
completed bool
|
||||
// runnerRunID is the run ID that Complete stored.
|
||||
runnerRunID uuid.UUID
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Claim(context.Context, outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) {
|
||||
@@ -173,8 +215,9 @@ func (store *fakeJobStore) Requeue(_ context.Context, _ outbound.ClaimedPractice
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) Complete(context.Context, outbound.ClaimedPracticeJob, domain.PracticeRunResult) (bool, error) {
|
||||
func (store *fakeJobStore) Complete(_ context.Context, _ outbound.ClaimedPracticeJob, runnerRunID uuid.UUID, _ domain.PracticeRunResult) (bool, error) {
|
||||
store.completed = true
|
||||
store.runnerRunID = runnerRunID
|
||||
return true, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user