diff --git a/backend/db/migrations/00054_add_practice_job_runner_run.sql b/backend/db/migrations/00054_add_practice_job_runner_run.sql new file mode 100644 index 0000000..6eb3075 --- /dev/null +++ b/backend/db/migrations/00054_add_practice_job_runner_run.sql @@ -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; diff --git a/backend/db/queries/assessment_practice_queue.sql b/backend/db/queries/assessment_practice_queue.sql index a186189..7137a80 100644 --- a/backend/db/queries/assessment_practice_queue.sql +++ b/backend/db/queries/assessment_practice_queue.sql @@ -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, diff --git a/backend/integration_test/assessment_practice_http_test.go b/backend/integration_test/assessment_practice_http_test.go index 3a0ea43..41869f6 100644 --- a/backend/integration_test/assessment_practice_http_test.go +++ b/backend/integration_test/assessment_practice_http_test.go @@ -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 { diff --git a/backend/integration_test/assessment_practice_queue_test.go b/backend/integration_test/assessment_practice_queue_test.go index bc971dc..8c22482 100644 --- a/backend/integration_test/assessment_practice_queue_test.go +++ b/backend/integration_test/assessment_practice_queue_test.go @@ -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. diff --git a/backend/integration_test/assessment_practice_runner_test.go b/backend/integration_test/assessment_practice_runner_test.go new file mode 100644 index 0000000..cf8c79d --- /dev/null +++ b/backend/integration_test/assessment_practice_runner_test.go @@ -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) + } + } +} diff --git a/backend/integration_test/practice_runner_fixture_test.go b/backend/integration_test/practice_runner_fixture_test.go new file mode 100644 index 0000000..45b3879 --- /dev/null +++ b/backend/integration_test/practice_runner_fixture_test.go @@ -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) +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go b/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go index fff2bb9..17e7079 100644 --- a/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go +++ b/backend/internal/adapter/secondary/postgres/assessment_practice_queue.go @@ -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 { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go index c70981c..821262e 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice_queue.sql.go @@ -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, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index ed6f51c..1990d6e 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -256,6 +256,7 @@ type AssessmentPracticeJob struct { LeaseExpiresAt pgtype.Timestamptz StartedAt pgtype.Timestamptz LastErrorClass pgtype.Text + RunnerRunID pgtype.UUID } type AssessmentPracticeSubmission struct { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 8fa0eed..f059477 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -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. diff --git a/backend/internal/port/outbound/assessment_practice_queue.go b/backend/internal/port/outbound/assessment_practice_queue.go index 99128fa..e8b1136 100644 --- a/backend/internal/port/outbound/assessment_practice_queue.go +++ b/backend/internal/port/outbound/assessment_practice_queue.go @@ -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. diff --git a/backend/internal/usecase/practice/execute.go b/backend/internal/usecase/practice/execute.go index 3df3365..2ade341 100644 --- a/backend/internal/usecase/practice/execute.go +++ b/backend/internal/usecase/practice/execute.go @@ -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 } diff --git a/backend/internal/usecase/practice/execute_test.go b/backend/internal/usecase/practice/execute_test.go index fdcffaf..fc4a193 100644 --- a/backend/internal/usecase/practice/execute_test.go +++ b/backend/internal/usecase/practice/execute_test.go @@ -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 } diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 2989d9f..4ff7c44 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -818,11 +818,14 @@ The attempt flow does not serve practice items yet, so no practice exists in pro #### Practice queue -Implemented: a durable queue with one running and ten queued jobs. Code: migration `00053_create_assessment_practice_queue.sql`, the port `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), the store `adapter/secondary/postgres/assessment_practice_queue.go`, the executor `usecase/practice/execute.go`, the worker `backend/internal/worker/practicequeue/`, and the wiring `bootstrap/practice.go`. It is not the scheduled job runtime: a scheduled job runs its handler inside the transaction that completes it, while a practice try waits seconds or minutes for an external run, and no transaction may stay open that long. +Implemented: a durable queue with one running and ten queued jobs. Code: migrations `00053_create_assessment_practice_queue.sql` and `00054_add_practice_job_runner_run.sql`, the port `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), the store `adapter/secondary/postgres/assessment_practice_queue.go`, the executor `usecase/practice/execute.go`, the worker `backend/internal/worker/practicequeue/`, and the wiring `bootstrap/practice.go`. It is not the scheduled job runtime: a scheduled job runs its handler inside the transaction that completes it, while a practice try waits seconds or minutes for an external run, and no transaction may stay open that long. - States. A job is `queued`, `running` (under a lease of one worker), `finished` (its result is stored), or `failed` (the infrastructure gave up; never a verdict). It records the generation of its run key, the counted attempts, when it may be claimed (`available_at`), the lease, the start of the running try, and the class of the last failure. - Atomic limits. Admission and the claim take the same transaction-scoped advisory lock and count the unfinished jobs. A command is admitted only while fewer than eleven jobs (one running and ten queued) are unfinished; the claim runs a job only while no other running job holds a live lease, so at most one job runs across all backend instances. A debug run beyond the limit answers 503 with `Retry-After` and stores nothing. A final solution beyond it stores nothing either: the practice becomes `failed` with `sandbox_busy`, which consumes nothing and accepts the solution again. The claim prefers a running job whose lease expired, then final solutions before debug runs, and skips rows that another transaction locks, so it never waits for a row lock while it holds the queue lock. -- One try. The executor builds the runner request from the stored task and submission, submits it, and polls the run every `PRACTICE_POLL_INTERVAL`, renewing the lease each time. A finished run stores the result once (`result IS NULL` guard), finishes the job, and, for the latest final submission of a pending practice, finishes the practice, in one transaction guarded by the lease owner and the start of the try. A busy runner puts the job back for the time it asked for (1 s to 1 min) without counting an attempt. A runner that is unreachable, refuses the token, or answers outside its contract is retried with the same run key after a backoff (2 s doubling to 1 min); a run the runner could not evaluate, or a key it holds with another payload, is retried with the next generation, so the next try is a new run; a lost run is submitted again. After `PRACTICE_JOB_MAX_ATTEMPTS` counted attempts, or for a task that cannot form a valid request, the job fails and a final practice becomes `failed` with `sandbox_error`; nothing is graded. A run that stays unfinished for 10 minutes counts as a failed try. +- One try. The executor builds the runner request from the stored task and submission, submits it, and polls the run every `PRACTICE_POLL_INTERVAL`, renewing the lease each time. A finished run stores the result once (`result IS NULL` guard), finishes the job with the opaque run ID of the runner run (`runner_run_id`, unique, set only on a finished job), and, for the latest final submission of a pending practice, finishes the practice, in one transaction guarded by the lease owner and the start of the try. A busy runner puts the job back for the time it asked for (1 s to 1 min) without counting an attempt. A runner that is unreachable, refuses the token, or answers outside its contract is retried with the same run key after a backoff (2 s doubling to 1 min); a run the runner could not evaluate, or a key it holds with another payload, is retried with the next generation, so the next try is a new run; a lost run is submitted again. After `PRACTICE_JOB_MAX_ATTEMPTS` counted attempts, or for a task that cannot form a valid request, the job fails and a final practice becomes `failed` with `sandbox_error`; nothing is graded. A run that stays unfinished for 10 minutes counts as a failed try. +- Runner isolation. The runner request carries the language, the source, the limits, and the test groups, nothing else: a debug run has the public examples and the candidate's own tests, a final solution the hidden groups only. The attempt item, the submission, and the generation reach the runner only as the opaque run ID, an HMAC under `CODE_RUNNER_RUN_KEY`, so the runner cannot link a run to a candidate. The stored `runner_run_id` is that ID: it lets an operator match a stored result to the runner's own log line without the runner learning who the candidate is. +- Repeats. A response lost or cut after the runner accepted the run, a request timeout, and a restart of the worker all end in a retry with the same run key, so the runner returns the run it already holds (200 instead of 202) and starts none. The result is written under the lease of the try and the `result IS NULL` guard, and the database refuses a second result, so a run has at most one result and one `runner_run_id`. +- Infrastructure failure. A runner that is stopped, unreachable, or answers outside its contract never produces a verdict. While tries remain, a debug run reads as `queued`, which tells the client to read it again; after the last try it reads as `failed` with `sandbox_error` and no result, a final practice becomes `failed` with `sandbox_error`, and neither changes the attempt, its result, or the confirmed category of the candidate. A new debug run or final solution is accepted at once. - Restart. A worker that stops gives its job back at once without counting. A worker that dies leaves the lease to expire; the next claim takes the job over with the same generation and counts one attempt, the runner returns the run it already has, and the result is stored once. A late completion by the dead worker changes nothing, because the job no longer belongs to its try. - Debug run limits. Besides the queue, a candidate gets at most `PRACTICE_RUNS_PER_MINUTE` and `PRACTICE_RUNS_PER_HOUR` new debug runs (the Redis limiter, keyed by a keyed digest of the account) and one unfinished run per practice; both answer 429 with `Retry-After`. A limiter failure refuses the run as unavailable. - Off without a runner. Without `CODE_RUNNER_URL` the worker does not start, and the operations answer 503 and store nothing. Several backend instances may run the worker; the claim keeps one job running among them. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 2190aa2..03a82aa 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -662,7 +662,17 @@ What the tests do not prove: isolation in the production VM until the suite has - A worker is killed mid-job (its pool closed, so it cannot give the job back): another worker claims nothing while the lease lives, takes the job over after it expires, and finishes it on the same run key, with one run on the runner, one counted takeover, and one result; a late completion by the killed worker is refused and leaves the result unchanged. - A second debug run while the first is unfinished, and a third within a minute, answer 429 `rate_limited` with `Retry-After` and store nothing. -Unit tests: `usecase/practice/execute_test.go` checks with fakes that an unreachable runner keeps the run key, an infrastructure failure and a reused key raise the generation, an invalid request and the last attempt fail without a stored result, a lost run is submitted again, and a shutdown gives the job back uncounted. `config/practice_test.go` checks the defaults and refused values of the practice settings. The tests do not run code in a sandbox and do not prove the timing of a real runner. +`TestAssessmentPracticeRunnerProtocol` in `backend/integration_test/assessment_practice_runner_test.go` uses the same harness with the real queue worker and the real TLS 1.3 client of the code runner (`adapter/secondary/code_runner`), against a local fixture of the runner protocol (`practice_runner_fixture_test.go`: an `httptest` TLS server with the bearer token, PUT and GET of `/v1/runs/{id}`, one run per run ID, and 422 for another payload). The fixture does not run code: it recognizes one Python and one Go program that print the sum of two integers and compares their output with the expected output of each test, and a failed public test carries the program output as its diagnostic. The production runner VM is not called. Sequential cases: + +- A Python and a Go debug run of two candidates finish through the API. Each candidate's own test expects a wrong sum, so the diagnostic shows what that program printed: `got 42` for the Python submission and `got 123` for the Go one, never the other's. The job keeps the `runner_run_id` of the run, and the fixture started that run from the source of that submission. The wire request has the fields `groups`, `language`, `limits`, and `source` only, the groups `public` and `custom` and no hidden group, headers limited to transport and the service token, a version 8 run ID that is none of the user, attempt, practice, or submission IDs, and none of those IDs, the email, or the session cookie in the path, headers, or body. Another candidate reads the run as 404. +- A final solution whose response is cut after the runner accepted the run (the connection is dropped) is retried after the backoff on the same run key: the runner holds one run, the job is `finished` with one counted attempt and generation 0, exactly one final result is stored, and its `runner_run_id` is that run. The wire request of a final solution has the groups `hidden-1` to `hidden-3` only. +- A debug run whose answer outlasts the request timeout ends the try as a retry, the run reads as `queued`, and the repeat joins the run the runner already holds. +- A worker that died mid-run (its pool is closed) is replaced by a worker with a new client built from the same settings after the lease expires. The new client derives the same run ID, so the runner still holds one run, one takeover is counted, and one result and one `runner_run_id` are stored. +- With the runner stopped, a debug run stays `queued` while tries remain, then reads as `failed` with `sandbox_error`, no result, no `runner_run_id`, and a finished time. The attempt state and version, the result count, and the confirmed categories of the candidate are the same before and after, and the practice is still `not_started`. A new debug run on the same practice is accepted and finishes once a working runner is back. A final solution with the stopped runner makes the practice `failed` with `sandbox_error` and no result, leaves the candidate state unchanged, and is accepted again and finished by a working runner. In the end no `runner_run_id` belongs to two jobs. + +The fixture proves the protocol path and the storage and retry rules; it does not prove that a real sandbox compiles or runs Python and Go or the timing of a real runner. + +Unit tests: `usecase/practice/execute_test.go` checks with fakes that an unreachable runner keeps the run key, an infrastructure failure and a reused key raise the generation, an invalid request and the last attempt fail without a stored result, a lost run is submitted again, a shutdown gives the job back uncounted, and a finished run without a valid run ID is retried and stores no result while a valid one is stored with the result. `config/practice_test.go` checks the defaults and refused values of the practice settings. The tests do not run code in a sandbox and do not prove the timing of a real runner. ## Semantic matching tests diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 90b9f61..458158e 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -818,11 +818,14 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи #### Очередь практики -Реализовано: долговечная очередь с одним выполняемым и десятью ожидающими заданиями. Код: миграция `00053_create_assessment_practice_queue.sql`, порт `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), хранилище `adapter/secondary/postgres/assessment_practice_queue.go`, исполнитель `usecase/practice/execute.go`, обработчик `backend/internal/worker/practicequeue/` и сборка `bootstrap/practice.go`. Это не среда заданий по сроку: задание по сроку выполняет обработчик внутри транзакции, которая его завершает, а попытка практики секунды или минуты ждет внешний прогон, и держать транзакцию открытой так долго нельзя. +Реализовано: долговечная очередь с одним выполняемым и десятью ожидающими заданиями. Код: миграции `00053_create_assessment_practice_queue.sql` и `00054_add_practice_job_runner_run.sql`, порт `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), хранилище `adapter/secondary/postgres/assessment_practice_queue.go`, исполнитель `usecase/practice/execute.go`, обработчик `backend/internal/worker/practicequeue/` и сборка `bootstrap/practice.go`. Это не среда заданий по сроку: задание по сроку выполняет обработчик внутри транзакции, которая его завершает, а попытка практики секунды или минуты ждет внешний прогон, и держать транзакцию открытой так долго нельзя. - Состояния. Задание бывает `queued`, `running` (под арендой одного обработчика), `finished` (результат сохранен) или `failed` (инфраструктура отказалась от задания; это никогда не вердикт). Оно хранит поколение ключа прогона, учтенные попытки, момент, когда его можно взять (`available_at`), аренду, начало текущей попытки и класс последнего сбоя. - Атомарные лимиты. Допуск и захват берут одну транзакционную advisory-блокировку и считают незавершенные задания. Команда допускается, только пока незавершенных заданий меньше одиннадцати (одно выполняется и десять ждут); захват запускает задание, только пока ни одно другое выполняемое задание не держит живую аренду, поэтому на всех экземплярах backend выполняется не больше одного задания. Отладочный прогон сверх лимита получает 503 с `Retry-After` и ничего не сохраняет. Финальное решение сверх лимита тоже ничего не сохраняет: практика становится `failed` с `sandbox_busy`, что ничего не расходует и снова принимает решение. Захват сначала берет выполняемое задание с истекшей арендой, затем финальные решения раньше отладочных прогонов и пропускает строки, заблокированные другой транзакцией, поэтому никогда не ждет блокировку строки, удерживая блокировку очереди. -- Одна попытка. Исполнитель строит запрос к исполнителю кода из сохраненной задачи и отправки, отправляет его и опрашивает прогон каждые `PRACTICE_POLL_INTERVAL`, каждый раз продлевая аренду. Завершенный прогон сохраняет результат один раз (условие `result IS NULL`), завершает задание и, для последнего финального решения практики в `pending`, завершает практику; все это в одной транзакции под условием владельца аренды и начала попытки. Занятый исполнитель возвращает задание в очередь на запрошенное им время (от 1 с до 1 мин) без учета попытки. Недоступный исполнитель, отказ в токене или ответ вне контракта повторяются с тем же ключом прогона после паузы (2 с, удваиваясь до 1 мин); прогон, который исполнитель не смог оценить, или ключ, под которым он хранит другие данные, повторяются со следующим поколением, то есть новым прогоном; потерянный прогон отправляется снова. После `PRACTICE_JOB_MAX_ATTEMPTS` учтенных попыток или для задачи, из которой не строится корректный запрос, задание завершается с `failed`, а финальная практика становится `failed` с `sandbox_error`; ничего не оценивается. Прогон, который не завершился за 10 минут, считается неудачной попыткой. +- Одна попытка. Исполнитель строит запрос к исполнителю кода из сохраненной задачи и отправки, отправляет его и опрашивает прогон каждые `PRACTICE_POLL_INTERVAL`, каждый раз продлевая аренду. Завершенный прогон сохраняет результат один раз (условие `result IS NULL`), завершает задание с непрозрачным ID прогона исполнителя (`runner_run_id`, уникален, задается только у завершенного задания) и, для последнего финального решения практики в `pending`, завершает практику; все это в одной транзакции под условием владельца аренды и начала попытки. Занятый исполнитель возвращает задание в очередь на запрошенное им время (от 1 с до 1 мин) без учета попытки. Недоступный исполнитель, отказ в токене или ответ вне контракта повторяются с тем же ключом прогона после паузы (2 с, удваиваясь до 1 мин); прогон, который исполнитель не смог оценить, или ключ, под которым он хранит другие данные, повторяются со следующим поколением, то есть новым прогоном; потерянный прогон отправляется снова. После `PRACTICE_JOB_MAX_ATTEMPTS` учтенных попыток или для задачи, из которой не строится корректный запрос, задание завершается с `failed`, а финальная практика становится `failed` с `sandbox_error`; ничего не оценивается. Прогон, который не завершился за 10 минут, считается неудачной попыткой. +- Изоляция исполнителя. Запрос к исполнителю содержит язык, исходный код, лимиты и группы тестов, и ничего больше: отладочный прогон несет публичные примеры и тесты кандидата, финальное решение только скрытые группы. Элемент попытки, отправка и поколение попадают к исполнителю только как непрозрачный ID прогона, HMAC под `CODE_RUNNER_RUN_KEY`, поэтому исполнитель не может связать прогон с кандидатом. Сохраненный `runner_run_id` и есть этот ID: по нему оператор сопоставляет сохраненный результат со строкой журнала самого исполнителя, а исполнитель не узнает, кто кандидат. +- Повторы. Потерянный или оборванный после приема прогона ответ, тайм-аут запроса и перезапуск обработчика заканчиваются повтором с тем же ключом прогона, поэтому исполнитель возвращает уже существующий прогон (200 вместо 202) и новый не запускает. Результат пишется под арендой попытки и условием `result IS NULL`, а база отказывает во втором результате, поэтому у прогона не больше одного результата и одного `runner_run_id`. +- Сбой инфраструктуры. Остановленный, недостижимый или отвечающий вне контракта исполнитель никогда не дает вердикта. Пока остаются попытки, отладочный прогон читается как `queued`, то есть клиенту нужно прочитать его снова; после последней попытки он читается как `failed` с `sandbox_error` без результата, финальная практика становится `failed` с `sandbox_error`, и ничто из этого не меняет попытку, ее результат и подтвержденную категорию кандидата. Новый отладочный прогон или финальное решение принимается сразу. - Перезапуск. Остановленный обработчик сразу возвращает задание без учета попытки. Упавший обработчик оставляет аренду истекать; следующий захват забирает задание с тем же поколением и учитывает одну попытку, исполнитель возвращает уже существующий прогон, а результат сохраняется один раз. Позднее завершение от упавшего обработчика ничего не меняет, потому что задание больше не принадлежит его попытке. - Лимиты отладочных прогонов. Кроме очереди, кандидат получает не больше `PRACTICE_RUNS_PER_MINUTE` и `PRACTICE_RUNS_PER_HOUR` новых отладочных прогонов (ограничитель в Redis по ключевому дайджесту аккаунта) и один незавершенный прогон на практику; оба лимита отвечают 429 с `Retry-After`. Сбой ограничителя отклоняет прогон как недоступный. - Без исполнителя выключено. Без `CODE_RUNNER_URL` обработчик не запускается, а операции отвечают 503 и ничего не сохраняют. Обработчик может работать на нескольких экземплярах backend; захват оставляет среди них одно выполняемое задание. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 5f87249..f8c23f3 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -662,7 +662,17 @@ Vitest работает в Node без DOM, поэтому ограничени - Обработчик убит посреди задания (его пул закрыт, поэтому вернуть задание он не может): другой обработчик ничего не берет, пока аренда жива, забирает задание после ее истечения и завершает его с тем же ключом прогона: один прогон у исполнителя, одна учтенная попытка захвата и один результат; позднее завершение от убитого обработчика отклоняется и не меняет результат. - Второй отладочный прогон, пока первый не завершен, и третий в пределах минуты получают 429 `rate_limited` с `Retry-After` и ничего не сохраняют. -Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, а остановка возвращает задание без учета попытки. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя. +`TestAssessmentPracticeRunnerProtocol` в `backend/integration_test/assessment_practice_runner_test.go` использует ту же обвязку с настоящим обработчиком очереди и настоящим клиентом исполнителя кода по TLS 1.3 (`adapter/secondary/code_runner`) против локальной подделки протокола исполнителя (`practice_runner_fixture_test.go`: TLS-сервер `httptest` с bearer-токеном, PUT и GET на `/v1/runs/{id}`, одним прогоном на ID прогона и 422 для другого содержимого). Подделка не запускает код: она узнает одну программу на Python и одну на Go, которые печатают сумму двух целых, и сравнивает их вывод с ожидаемым выводом каждого теста; у проваленного публичного теста вывод программы лежит в диагностике. Боевая VM исполнителя не вызывается. Последовательные случаи: + +- Отладочные прогоны на Python и на Go двух кандидатов завершаются через API. Собственный тест каждого кандидата ожидает неверную сумму, поэтому диагностика показывает, что напечатала программа: `got 42` у отправки на Python и `got 123` у отправки на Go, но не наоборот. Задание хранит `runner_run_id` прогона, и подделка запустила этот прогон из исходного кода именно этой отправки. Запрос на проводе содержит только поля `groups`, `language`, `limits` и `source`, группы `public` и `custom` и ни одной скрытой, заголовки только транспортные и сервисный токен, ID прогона версии 8, который не совпадает ни с ID пользователя, попытки, практики или отправки, и ни одного из этих ID, email и cookie сессии в пути, заголовках и теле. Другой кандидат читает прогон как 404. +- Финальное решение, ответ на которое оборван после приема прогона исполнителем (соединение сброшено), повторяется после паузы с тем же ключом прогона: у исполнителя один прогон, задание `finished` с одной учтенной попыткой и поколением 0, сохранен ровно один финальный результат, и его `runner_run_id` - этот прогон. Запрос финального решения содержит только группы `hidden-1`...`hidden-3`. +- Отладочный прогон, ответ на который идет дольше тайм-аута запроса, завершает попытку повтором, прогон читается как `queued`, а повтор присоединяется к прогону, который исполнитель уже держит. +- Обработчик, умерший посреди прогона (его пул закрыт), заменяется после истечения аренды обработчиком с новым клиентом, собранным из тех же настроек. Новый клиент получает тот же ID прогона, поэтому у исполнителя по-прежнему один прогон, учтен один захват, сохранены один результат и один `runner_run_id`. +- При остановленном исполнителе отладочный прогон остается `queued`, пока есть попытки, затем читается как `failed` с `sandbox_error`, без результата и `runner_run_id`, со временем завершения. Состояние и версия попытки, число результатов и подтвержденные категории кандидата до и после одинаковы, а практика остается `not_started`. Новый отладочный прогон той же практики принимается и завершается, когда исполнитель снова работает. Финальное решение при остановленном исполнителе переводит практику в `failed` с `sandbox_error` без результата, не меняет состояние кандидата и принимается снова и завершается рабочим исполнителем. В конце ни один `runner_run_id` не принадлежит двум заданиям. + +Подделка доказывает путь по протоколу и правила хранения и повтора; она не доказывает, что настоящая песочница собирает и запускает Python и Go, и не доказывает время работы настоящего исполнителя. + +Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, остановка возвращает задание без учета попытки, а завершенный прогон без верного ID повторяется и не сохраняет результат, тогда как верный ID сохраняется вместе с результатом. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя. ## Тесты семантического подбора