feat(practice): run practice jobs on the code runner with one stored result per run

This commit is contained in:
shira committed 2026-10-11 19:31:08 +03:00
1 parent 9385b2ddd4
commit 9344228e84
17 files changed
+1010 -35

No files matched your search

@@ -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)
}