771 lines
38 KiB
Go
771 lines
38 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"math/rand/v2"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/adapter/primary/cli/assessmentreview"
|
|
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/adapter/secondary/prometheus"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/inbound"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
"lincodex/backend/internal/worker/jobrunner"
|
|
)
|
|
|
|
const (
|
|
reviewDuplicateIntegerAnswer = 123456
|
|
reviewAddressOne = "192.0.2.77"
|
|
reviewAddressTwo = "198.51.100.88"
|
|
reviewAddressThree = "203.0.113.99"
|
|
)
|
|
|
|
// reviewTestSignalPolicy returns thresholds that make the band deterministic
|
|
// for requests that arrive within milliseconds: the median deviation is off
|
|
// (it needs more answers than an attempt has), the review level is out of reach
|
|
// for the server signals that every fast test run produces, and the duplicate
|
|
// levels are low enough for a copied pair to reach them in a population of a
|
|
// handful of attempts, where a matched answer carries only a bit or two.
|
|
func reviewTestSignalPolicy() domain.AssessmentSignalPolicy {
|
|
signals := domain.DemoAssessmentSignalPolicy()
|
|
signals.FastAnswersAttention, signals.FastAnswersReview = 3, 1000
|
|
signals.DeviationMinAnswers = 220
|
|
signals.DeviatingAnswersAttention, signals.DeviatingAnswersReview = 1000, 1000
|
|
signals.ParallelAlternationsAttention, signals.ParallelAlternationsReview = 2, 1000
|
|
signals.ExtraNetworksAttention, signals.ExtraNetworksReview = 2, 1000
|
|
signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 4, 6
|
|
return signals
|
|
}
|
|
|
|
// reviewUnreachableSignalPolicy is a later policy version under which the same
|
|
// behavior stays normal.
|
|
func reviewUnreachableSignalPolicy() domain.AssessmentSignalPolicy {
|
|
signals := reviewTestSignalPolicy()
|
|
signals.FastAnswersAttention, signals.FastAnswersReview = 1000, 1000
|
|
signals.ParallelAlternationsAttention, signals.ParallelAlternationsReview = 1000, 1000
|
|
signals.ExtraNetworksAttention, signals.ExtraNetworksReview = 1000, 1000
|
|
signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 4096, 4096
|
|
signals.ClientFocusLossAttentionMS = 24 * 60 * 60 * 1000
|
|
signals.ClientClipboardEventsAttention, signals.ClientFullscreenExitsAttention = 1000, 1000
|
|
return signals
|
|
}
|
|
|
|
type reviewCandidate struct {
|
|
user domain.User
|
|
cookies [2]*http.Cookie
|
|
csrf [2]string
|
|
}
|
|
|
|
// newReviewCandidate creates a verified candidate with a questionnaire and the
|
|
// C3 consent and logs in once per requested session.
|
|
func newReviewCandidate(ctx context.Context, t *testing.T, harness *assessmentAttemptHTTPHarness, email, addressBase string, sessions int) reviewCandidate {
|
|
t.Helper()
|
|
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
|
if err != nil {
|
|
t.Fatalf("HashNewPassword() error = %v", err)
|
|
}
|
|
user := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, true)
|
|
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", user.ID); err != nil {
|
|
t.Fatalf("set candidate onboarding step: %v", err)
|
|
}
|
|
candidate := reviewCandidate{user: user}
|
|
for session := range sessions {
|
|
candidate.cookies[session], candidate.csrf[session] = loginConsentHTTP(t, harness.sessionHTTPHarness, email, fmt.Sprintf("%s.%d:1234", addressBase, 10+session))
|
|
}
|
|
if response := assessmentAttemptQuestionnaireRequest(t, harness, candidate.cookies[0].Value, candidate.csrf[0], addressBase+".20:1234"); response.Code != http.StatusOK {
|
|
t.Fatalf("save questionnaire = %d %s", response.Code, response.Body.String())
|
|
}
|
|
grantCurrentAttemptConsent(t, harness, candidate.cookies[0], candidate.csrf[0], addressBase+".21:1234")
|
|
return candidate
|
|
}
|
|
|
|
func (candidate reviewCandidate) createAttempt(t *testing.T, harness *assessmentAttemptHTTPHarness, key, remoteAddr string) assessmentAnswerHTTPAttempt {
|
|
t.Helper()
|
|
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
|
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr)
|
|
var attempt assessmentAnswerHTTPAttempt
|
|
if response.Code != http.StatusCreated || json.Unmarshal(response.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil {
|
|
t.Fatalf("create real attempt = %d %s", response.Code, response.Body.String())
|
|
}
|
|
return attempt
|
|
}
|
|
|
|
// answerAll submits every item of the attempt in order. Request i is sent by
|
|
// session i modulo the number of sessions and from the matching address.
|
|
func (candidate reviewCandidate) answerAll(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
harness *assessmentAttemptHTTPHarness,
|
|
attempt assessmentAnswerHTTPAttempt,
|
|
sessions int,
|
|
addresses []string,
|
|
answerFor func(item assessmentAnswerHTTPItem) json.RawMessage,
|
|
keyPrefix string,
|
|
) assessmentAnswerHTTPAttempt {
|
|
t.Helper()
|
|
return candidate.answerFirst(ctx, t, harness, attempt, 0, sessions, addresses, answerFor, keyPrefix)
|
|
}
|
|
|
|
// answerFirst answers the first count items, or all of them when count is zero.
|
|
func (candidate reviewCandidate) answerFirst(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
harness *assessmentAttemptHTTPHarness,
|
|
attempt assessmentAnswerHTTPAttempt,
|
|
count, sessions int,
|
|
addresses []string,
|
|
answerFor func(item assessmentAnswerHTTPItem) json.RawMessage,
|
|
keyPrefix string,
|
|
) assessmentAnswerHTTPAttempt {
|
|
t.Helper()
|
|
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
|
|
if count > 0 {
|
|
items = items[:count]
|
|
}
|
|
version := attempt.Version
|
|
last := attempt
|
|
for index, item := range items {
|
|
body, err := json.Marshal(struct {
|
|
ExpectedVersion int64 `json:"expected_version"`
|
|
ItemID uuid.UUID `json:"item_id"`
|
|
Answer json.RawMessage `json:"answer"`
|
|
}{ExpectedVersion: version, ItemID: item.ID, Answer: answerFor(item)})
|
|
if err != nil {
|
|
t.Fatalf("marshal answer: %v", err)
|
|
}
|
|
session := index % sessions
|
|
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
|
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), sessionHTTPTestOrigin,
|
|
candidate.cookies[session].Value, candidate.csrf[session], fmt.Sprintf("%s-%d", keyPrefix, item.Ordinal),
|
|
addresses[index%len(addresses)]+":4321")
|
|
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &last) != nil {
|
|
t.Fatalf("answer item %d = %d %s", item.Ordinal, response.Code, response.Body.String())
|
|
}
|
|
version = last.Version
|
|
}
|
|
return last
|
|
}
|
|
|
|
func (candidate reviewCandidate) finalize(t *testing.T, harness *assessmentAttemptHTTPHarness, attempt assessmentAnswerHTTPAttempt, key, remoteAddr string) {
|
|
t.Helper()
|
|
body, err := json.Marshal(map[string]int64{"expected_version": attempt.Version})
|
|
if err != nil {
|
|
t.Fatalf("marshal finalization: %v", err)
|
|
}
|
|
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
|
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", string(body), sessionHTTPTestOrigin,
|
|
candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("finalize attempt = %d %s", response.Code, response.Body.String())
|
|
}
|
|
}
|
|
|
|
func answerFromBody(t *testing.T, version int64, item assessmentAnswerHTTPItem, correct bool) json.RawMessage {
|
|
t.Helper()
|
|
var envelope struct {
|
|
Answer json.RawMessage `json:"answer"`
|
|
}
|
|
if err := json.Unmarshal(assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct), &envelope); err != nil {
|
|
t.Fatalf("decode fixture answer: %v", err)
|
|
}
|
|
return envelope.Answer
|
|
}
|
|
|
|
func correctReviewAnswer(t *testing.T) func(assessmentAnswerHTTPItem) json.RawMessage {
|
|
return func(item assessmentAnswerHTTPItem) json.RawMessage { return answerFromBody(t, 1, item, true) }
|
|
}
|
|
|
|
// copiedReviewAnswer gives every candidate the same wrong answer for the same
|
|
// family, whatever the seed: a constant number, and for an order the reverse of
|
|
// the identity order.
|
|
func copiedReviewAnswer(t *testing.T) func(assessmentAnswerHTTPItem) json.RawMessage {
|
|
return func(item assessmentAnswerHTTPItem) json.RawMessage {
|
|
if item.Variant.AnswerFormat == domain.AnswerFormatInteger {
|
|
return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%d}`, reviewDuplicateIntegerAnswer))
|
|
}
|
|
tasks := item.Variant.Parameters["tasks"]
|
|
elements := make([]string, 0, tasks)
|
|
for task := tasks; task >= 1; task-- {
|
|
elements = append(elements, fmt.Sprintf("job_%d", task))
|
|
}
|
|
answer, err := json.Marshal(map[string]any{"format": "order", "element_ids": elements})
|
|
if err != nil {
|
|
t.Fatalf("marshal copied order answer: %v", err)
|
|
}
|
|
return answer
|
|
}
|
|
}
|
|
|
|
// reviewJobWorker builds a scheduled job worker for the review kind. now is the
|
|
// clock of the worker: a clock far ahead also runs the jobs due at the
|
|
// deadlines of the attempts.
|
|
func reviewJobWorker(t *testing.T, harness *assessmentAttemptHTTPHarness, now func() time.Time, batch int) *jobrunner.Worker {
|
|
t.Helper()
|
|
settings := jobTestSettings(time.Second)
|
|
settings.BatchSize = batch
|
|
worker, err := jobrunner.New([]inbound.JobHandler{assessment.NewSignalReviewJob(nil)},
|
|
postgresadapter.NewScheduledJobStore(harness.pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, now)
|
|
if err != nil {
|
|
t.Fatalf("jobrunner.New() error = %v", err)
|
|
}
|
|
return worker
|
|
}
|
|
|
|
// runReviewJobs runs passes until none claims a job and fails on any retry or
|
|
// dead job: a review must succeed at once.
|
|
func runReviewJobs(ctx context.Context, t *testing.T, worker *jobrunner.Worker) int {
|
|
t.Helper()
|
|
done := 0
|
|
for range 50 {
|
|
result, err := worker.RunDue(ctx)
|
|
if err != nil {
|
|
t.Fatalf("RunDue() error = %v", err)
|
|
}
|
|
if result.Retried != 0 || result.Dead != 0 || result.LeaseLost != 0 {
|
|
t.Fatalf("review job pass = %+v, want only finished jobs", result)
|
|
}
|
|
if result.Claimed == 0 {
|
|
return done
|
|
}
|
|
done += result.Done
|
|
}
|
|
t.Fatal("review jobs did not become idle")
|
|
return done
|
|
}
|
|
|
|
func reviewNow() time.Time { return time.Now().UTC() }
|
|
|
|
func reviewFarFuture() time.Time { return time.Now().UTC().Add(200 * time.Hour) }
|
|
|
|
type storedReview struct {
|
|
Band string
|
|
Reasons []string
|
|
PolicyVersion int32
|
|
PolicyID uuid.UUID
|
|
Fast int32
|
|
Alternations int32
|
|
ExtraNetworks int32
|
|
MatchedInt int32
|
|
Evidence int32
|
|
ClipboardN int32
|
|
}
|
|
|
|
func readStoredReview(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness, attemptID uuid.UUID) (storedReview, bool) {
|
|
t.Helper()
|
|
var review storedReview
|
|
rows, err := harness.pool.Query(ctx, `
|
|
SELECT r.band, r.reasons, p.version, r.policy_version_id, r.fast_answers, r.parallel_alternations, r.extra_networks,
|
|
r.matched_integer_items, r.duplicate_evidence_bits, r.client_clipboard_events
|
|
FROM assessment_attempt_reviews r JOIN policy_versions p ON p.id = r.policy_version_id WHERE r.attempt_id = $1`, attemptID)
|
|
if err != nil {
|
|
t.Fatalf("read stored review: %v", err)
|
|
}
|
|
defer rows.Close()
|
|
if !rows.Next() {
|
|
return storedReview{}, false
|
|
}
|
|
if err := rows.Scan(&review.Band, &review.Reasons, &review.PolicyVersion, &review.PolicyID, &review.Fast, &review.Alternations,
|
|
&review.ExtraNetworks, &review.MatchedInt, &review.Evidence, &review.ClipboardN); err != nil {
|
|
t.Fatalf("scan stored review: %v", err)
|
|
}
|
|
return review, true
|
|
}
|
|
|
|
func newReviewHarness(ctx context.Context, t *testing.T, signals domain.AssessmentSignalPolicy) *assessmentAttemptHTTPHarness {
|
|
t.Helper()
|
|
env := bootstrap(t, postgresService, redisService)
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
applyMigrations(ctx, t, databaseURL)
|
|
isolatedEnv := *env
|
|
isolatedEnv.Config.DatabaseURL = databaseURL
|
|
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
|
t.Cleanup(harness.pool.Close)
|
|
seedAssessmentAttemptHTTPBankWithSignals(ctx, t, harness.pool, &signals)
|
|
return harness
|
|
}
|
|
|
|
func TestAssessmentSignalReviewOverHTTP(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
|
defer cancel()
|
|
oldSignals := reviewTestSignalPolicy()
|
|
harness := newReviewHarness(ctx, t, oldSignals)
|
|
|
|
fast := newReviewCandidate(ctx, t, harness, "review-fast@example.test", "192.0.2", 2)
|
|
control := newReviewCandidate(ctx, t, harness, "review-control@example.test", "192.0.3", 2)
|
|
copyOne := newReviewCandidate(ctx, t, harness, "review-copy-one@example.test", "192.0.4", 1)
|
|
copyTwo := newReviewCandidate(ctx, t, harness, "review-copy-two@example.test", "192.0.5", 1)
|
|
abandoned := newReviewCandidate(ctx, t, harness, "review-abandoned@example.test", "192.0.6", 1)
|
|
|
|
// Four attempts start under the first policy version.
|
|
fastAttempt := fast.createAttempt(t, harness, "review-fast-create", "192.0.2.30:1234")
|
|
copyOneAttempt := copyOne.createAttempt(t, harness, "review-copy-one-create", "192.0.4.30:1234")
|
|
copyTwoAttempt := copyTwo.createAttempt(t, harness, "review-copy-two-create", "192.0.5.30:1234")
|
|
abandonedAttempt := abandoned.createAttempt(t, harness, "review-abandoned-create", "192.0.6.30:1234")
|
|
|
|
// A new policy version is published while they are in progress; an attempt
|
|
// that starts afterwards pins the new version.
|
|
newSignals := reviewUnreachableSignalPolicy()
|
|
newPolicy := integrationPolicy(11)
|
|
newPolicy.Assessment.MaxAttemptsPerWindow = 1
|
|
demoAttemptPolicy := domain.DemoProductPolicyV2().Assessment
|
|
newPolicy.Assessment.Attempt, newPolicy.Assessment.Training = demoAttemptPolicy.Attempt, demoAttemptPolicy.Training
|
|
newPolicy.Assessment.Attempt.MaxSessions, newPolicy.Assessment.Attempt.IdleTimeoutSeconds = 1, 60
|
|
newPolicy.Assessment.Signals = &newSignals
|
|
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
|
newVersion, err := publisher.Publish(ctx, policy.PublishInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: newPolicy,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Publish(new signal policy) error = %v", err)
|
|
}
|
|
// A category opening is bound to one product policy version, so the
|
|
// category is opened again under the new version.
|
|
openAssessmentAttemptFixtureCategory(ctx, t, assessment.NewBank(postgresadapter.NewTransactor(harness.pool)),
|
|
newVersion.ID(), domain.AssessmentCategory("backend"), domain.SpecializationBackend, domain.GradeJunior)
|
|
controlAttempt := control.createAttempt(t, harness, "review-control-create", "192.0.3.30:1234")
|
|
|
|
// Very fast answers, two logged-in sessions that take turns, three networks,
|
|
// and client paste events: the attempt gets attention.
|
|
addresses := []string{reviewAddressOne, reviewAddressTwo, reviewAddressThree}
|
|
fastItems := readAssessmentAnswerHTTPItems(t, ctx, harness, fastAttempt.ID)
|
|
for index := range 3 {
|
|
response := submitAssessmentSignal(t, harness, fastAttempt.ID, fast.cookies[1], fast.csrf[1], fmt.Sprintf("review-paste-%d", index),
|
|
assessmentSignalBody(t, fastItems[0].ID, time.Now().UTC().Truncate(time.Microsecond), "paste", int32Pointer(40)), reviewAddressTwo+":4321")
|
|
assertSignalReceipt(t, response, http.StatusOK, "accepted", 1)
|
|
}
|
|
fastDone := fast.answerAll(ctx, t, harness, fastAttempt, 2, addresses, correctReviewAnswer(t), "review-fast-answer")
|
|
fast.finalize(t, harness, fastDone, "review-fast-finalize", "192.0.2.31:1234")
|
|
|
|
// The same behavior under the later version, from a candidate who started
|
|
// after the policy changed.
|
|
controlDone := control.answerAll(ctx, t, harness, controlAttempt, 2, addresses, correctReviewAnswer(t), "review-control-answer")
|
|
control.finalize(t, harness, controlDone, "review-control-finalize", "192.0.3.31:1234")
|
|
|
|
// The reviews are computed by scheduled jobs after the attempts ended, not
|
|
// in the transactions of the candidates: nothing exists before the worker
|
|
// runs, and the results are already readable.
|
|
if _, found := readStoredReview(t, ctx, harness, fastAttempt.ID); found {
|
|
t.Fatal("a review exists before the review job ran: it was computed in the candidate's transaction")
|
|
}
|
|
var pendingJobs int
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status = 'pending'`).Scan(&pendingJobs); err != nil || pendingJobs < 4 {
|
|
t.Fatalf("pending review jobs = %d (error %v), want a deadline job per answered attempt and an ended job per finalized one", pendingJobs, err)
|
|
}
|
|
immediate := reviewJobWorker(t, harness, reviewNow, 5)
|
|
runReviewJobs(ctx, t, immediate)
|
|
|
|
fastReview, found := readStoredReview(t, ctx, harness, fastAttempt.ID)
|
|
if !found || fastReview.Band != "attention" {
|
|
t.Fatalf("fast attempt review = %+v (found %v), want band attention", fastReview, found)
|
|
}
|
|
for _, reason := range []string{"fast_answers", "parallel_sessions", "extra_networks", "client_signals"} {
|
|
if !slices.Contains(fastReview.Reasons, reason) {
|
|
t.Errorf("fast attempt reasons = %v, want %s", fastReview.Reasons, reason)
|
|
}
|
|
}
|
|
if slices.Contains(fastReview.Reasons, "duplicate_answers") || fastReview.ClipboardN != 3 || fastReview.ExtraNetworks != 2 {
|
|
t.Errorf("fast attempt reasons = %v, clipboard events = %d, extra networks = %d; want no duplicate flag, three paste events, and two extra networks",
|
|
fastReview.Reasons, fastReview.ClipboardN, fastReview.ExtraNetworks)
|
|
}
|
|
controlReview, found := readStoredReview(t, ctx, harness, controlAttempt.ID)
|
|
if !found || controlReview.Band != "normal" || len(controlReview.Reasons) != 0 {
|
|
t.Fatalf("attempt under the later policy version review = %+v (found %v), want band normal", controlReview, found)
|
|
}
|
|
if fastReview.PolicyVersion == newVersion.Version() || controlReview.PolicyVersion != newVersion.Version() || domain.PolicyVersionID(controlReview.PolicyID) != newVersion.ID() {
|
|
t.Fatalf("pinned policy versions = %d (old attempt) and %d (new attempt), want the old and then %d", fastReview.PolicyVersion, controlReview.PolicyVersion, newVersion.Version())
|
|
}
|
|
if controlReview.Fast == 0 || controlReview.Alternations == 0 || controlReview.ExtraNetworks == 0 {
|
|
t.Fatalf("later-version review counted fast=%d alternations=%d extra networks=%d, want the facts kept even when the band is normal", controlReview.Fast, controlReview.Alternations, controlReview.ExtraNetworks)
|
|
}
|
|
|
|
// The band changes neither the result nor the category data: the same
|
|
// correct answers give the same result whatever the band.
|
|
fastResult := readReviewCandidateResult(t, harness, fast, fastAttempt.ID)
|
|
controlResult := readReviewCandidateResult(t, harness, control, controlAttempt.ID)
|
|
for _, field := range []string{"outcome", "basic_score", "limitations", "mode"} {
|
|
if stringMustJSON(t, fastResult[field]) != stringMustJSON(t, controlResult[field]) {
|
|
t.Errorf("result field %s differs between the attention and the normal attempt: %v vs %v", field, fastResult[field], controlResult[field])
|
|
}
|
|
}
|
|
if fastResult["outcome"] != "confirmed" {
|
|
t.Fatalf("attention attempt outcome = %v, want confirmed", fastResult["outcome"])
|
|
}
|
|
var bandColumns int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns
|
|
WHERE table_schema = 'public' AND table_name LIKE 'assessment\_%' AND table_name <> 'assessment_attempt_reviews'
|
|
AND (column_name LIKE '%band%' OR column_name LIKE '%attention%')`).Scan(&bandColumns); err != nil || bandColumns != 0 {
|
|
t.Fatalf("assessment tables other than the review table carry %d band columns (error %v), want none", bandColumns, err)
|
|
}
|
|
|
|
// Different seeds, identical answers: the first attempt has no duplicate
|
|
// flag until the other candidate has answered; then, when the second one
|
|
// ends, both are flagged.
|
|
oneItems := readAssessmentAnswerHTTPItems(t, ctx, harness, copyOneAttempt.ID)
|
|
twoItems := readAssessmentAnswerHTTPItems(t, ctx, harness, copyTwoAttempt.ID)
|
|
sameSeeds := 0
|
|
for index := range oneItems {
|
|
if oneItems[index].Variant.Seed == twoItems[index].Variant.Seed {
|
|
sameSeeds++
|
|
}
|
|
}
|
|
if sameSeeds == len(oneItems) {
|
|
t.Fatal("both copy attempts drew the same seeds; the test needs different seed variants")
|
|
}
|
|
oneDone := copyOne.answerAll(ctx, t, harness, copyOneAttempt, 1, []string{"192.0.4.40"}, copiedReviewAnswer(t), "review-copy-one-answer")
|
|
copyOne.finalize(t, harness, oneDone, "review-copy-one-finalize", "192.0.4.41:1234")
|
|
runReviewJobs(ctx, t, immediate)
|
|
firstAlone, found := readStoredReview(t, ctx, harness, copyOneAttempt.ID)
|
|
if !found || slices.Contains(firstAlone.Reasons, "duplicate_answers") {
|
|
t.Fatalf("first copied attempt review before the other answered = %+v (found %v), want no duplicate flag yet", firstAlone, found)
|
|
}
|
|
|
|
// A third attempt copies the same answers and is abandoned: it never
|
|
// finalizes. While it runs, a match with it does not flag it.
|
|
abandonedItems := readAssessmentAnswerHTTPItems(t, ctx, harness, abandonedAttempt.ID)
|
|
abandoned.answerFirst(ctx, t, harness, abandonedAttempt, len(abandonedItems)-1, 1, []string{"192.0.6.40"}, copiedReviewAnswer(t), "review-abandoned-answer")
|
|
twoDone := copyTwo.answerAll(ctx, t, harness, copyTwoAttempt, 1, []string{"192.0.5.40"}, copiedReviewAnswer(t), "review-copy-two-answer")
|
|
copyTwo.finalize(t, harness, twoDone, "review-copy-two-finalize", "192.0.5.41:1234")
|
|
runReviewJobs(ctx, t, immediate)
|
|
for name, attemptID := range map[string]uuid.UUID{"first": copyOneAttempt.ID, "second": copyTwoAttempt.ID} {
|
|
review, found := readStoredReview(t, ctx, harness, attemptID)
|
|
if !found || review.Band != "review" || !slices.Contains(review.Reasons, "duplicate_answers") || review.MatchedInt == 0 || review.Evidence < 6 {
|
|
t.Errorf("%s copied attempt review = %+v (found %v), want band review with a duplicate flag and at least 6 evidence bits", name, review, found)
|
|
}
|
|
}
|
|
if _, found := readStoredReview(t, ctx, harness, abandonedAttempt.ID); found {
|
|
t.Fatal("the running attempt was flagged before it ended; it is flagged by its own job when it ends")
|
|
}
|
|
|
|
// The abandoned attempt ends without being finalized (its state becomes
|
|
// terminal) and its job at the deadline reviews it. The clock of the worker
|
|
// is moved past the deadline.
|
|
terminalizeAttempt(t, ctx, harness.pool, abandonedAttempt.ID)
|
|
runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewFarFuture, 5))
|
|
abandonedReview, found := readStoredReview(t, ctx, harness, abandonedAttempt.ID)
|
|
if !found || abandonedReview.Band != "review" || !slices.Contains(abandonedReview.Reasons, "duplicate_answers") {
|
|
t.Fatalf("abandoned attempt review = %+v (found %v), want it flagged when it ended", abandonedReview, found)
|
|
}
|
|
var unfinished int
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status <> 'done'`).Scan(&unfinished); err != nil || unfinished != 0 {
|
|
t.Fatalf("unfinished review jobs = %d (error %v), want none", unfinished, err)
|
|
}
|
|
for name, attemptID := range map[string]uuid.UUID{"fast": fastAttempt.ID, "later-version": controlAttempt.ID} {
|
|
// Two honest attempts can coincide on a low-entropy answer by chance;
|
|
// the evidence stays below the attention level and raises no flag.
|
|
if review, _ := readStoredReview(t, ctx, harness, attemptID); slices.Contains(review.Reasons, "duplicate_answers") || review.Evidence >= oldSignals.DuplicateAttentionBits {
|
|
t.Errorf("%s attempt was flagged as a duplicate: %+v", name, review)
|
|
}
|
|
}
|
|
|
|
// No candidate read carries the band, its reasons, or the facts behind it.
|
|
candidates := map[string]struct {
|
|
candidate reviewCandidate
|
|
attemptID uuid.UUID
|
|
}{
|
|
"fast": {fast, fastAttempt.ID}, "later-version": {control, controlAttempt.ID},
|
|
"copy-one": {copyOne, copyOneAttempt.ID}, "copy-two": {copyTwo, copyTwoAttempt.ID},
|
|
}
|
|
for name, entry := range candidates {
|
|
for _, path := range []string{
|
|
"/api/v1/me/assessment-attempts/" + entry.attemptID.String(),
|
|
"/api/v1/me/assessment-attempts/" + entry.attemptID.String() + "/result",
|
|
"/api/v1/me/assessment-availability",
|
|
} {
|
|
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", entry.candidate.cookies[0].Value, "", "", "203.0.113.200:1234")
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("%s candidate read %s = %d %s", name, path, response.Code, response.Body.String())
|
|
}
|
|
lowered := strings.ToLower(response.Body.String())
|
|
for _, forbidden := range []string{`"band"`, "attention", `"reasons"`, "fingerprint", "parallel_sessions", "fast_answers", "duplicate_answers", "client_signals", "review_band", "extra_networks"} {
|
|
if strings.Contains(lowered, forbidden) {
|
|
t.Errorf("%s candidate read %s contains %q: %s", name, path, forbidden, response.Body.String())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// The operator command is the only reader, and every read is recorded.
|
|
operator, err := assessment.NewReviewOperator(postgresadapter.NewTransactor(harness.pool))
|
|
if err != nil {
|
|
t.Fatalf("NewReviewOperator() error = %v", err)
|
|
}
|
|
var output bytes.Buffer
|
|
command := assessmentreview.Command{AttemptID: domain.AssessmentAttemptID(fastAttempt.ID), Actor: "operator:integration"}
|
|
if err := assessmentreview.Execute(ctx, command, operator, &output); err != nil {
|
|
t.Fatalf("Execute(fast attempt) error = %v", err)
|
|
}
|
|
for _, want := range []string{"band: attention", fmt.Sprintf("policy_version: %d", fastReview.PolicyVersion), "fast_answers", "parallel_sessions", "extra_networks: 2"} {
|
|
if !strings.Contains(output.String(), want) {
|
|
t.Errorf("operator output lacks %q:\n%s", want, output.String())
|
|
}
|
|
}
|
|
missing := assessmentreview.Command{AttemptID: domain.AssessmentAttemptID(uuid.New()), Actor: "operator:integration"}
|
|
if err := assessmentreview.Execute(ctx, missing, operator, &output); err == nil {
|
|
t.Fatal("Execute(unknown attempt) succeeded")
|
|
}
|
|
if err := assessmentreview.Execute(ctx, assessmentreview.Command{AttemptID: command.AttemptID, Actor: "alice"}, operator, &output); err == nil {
|
|
t.Fatal("Execute(actor without the operator prefix) succeeded")
|
|
}
|
|
var reads, foundReads, missingReads int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*), count(*) FILTER (WHERE found), count(*) FILTER (WHERE NOT found) FROM assessment_review_reads WHERE actor = 'operator:integration'`).
|
|
Scan(&reads, &foundReads, &missingReads); err != nil || reads != 2 || foundReads != 1 || missingReads != 1 {
|
|
t.Fatalf("audit records = %d (found %d, missing %d), error %v; want one found read and one miss", reads, foundReads, missingReads, err)
|
|
}
|
|
|
|
// Facts, reviews, and the audit refuse edits, deletes, and truncation.
|
|
for _, statement := range []string{
|
|
"UPDATE assessment_answer_observations SET elapsed_ms = 0",
|
|
"DELETE FROM assessment_attempt_origin_marks",
|
|
"UPDATE assessment_attempt_reviews SET policy_version_id = '" + newVersion.ID().String() + "' WHERE attempt_id = '" + fastAttempt.ID.String() + "'",
|
|
"DELETE FROM assessment_attempt_reviews",
|
|
"UPDATE assessment_review_reads SET actor = 'operator:other'",
|
|
"DELETE FROM assessment_review_reads",
|
|
"TRUNCATE assessment_review_reads",
|
|
} {
|
|
if _, err := harness.pool.Exec(ctx, statement); err == nil {
|
|
t.Errorf("statement %q succeeded", statement)
|
|
}
|
|
}
|
|
|
|
// Origin marks are written when the session or the network changes, not for
|
|
// every request: the fast attempt alternates on every answer, the copied
|
|
// attempts keep one session and one network.
|
|
var oneMarks int
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempt_origin_marks WHERE attempt_id = $1`, copyOneAttempt.ID).Scan(&oneMarks); err != nil || oneMarks != 1 {
|
|
t.Fatalf("origin marks of an attempt with one session and one network = %d (error %v), want 1", oneMarks, err)
|
|
}
|
|
|
|
// Logs and stored rows carry no answer text, address, or session token.
|
|
privateValues := []string{
|
|
reviewAddressOne, reviewAddressTwo, reviewAddressThree, "192.0.2.", "192.0.3.", "192.0.4.", "192.0.5.", "192.0.6.",
|
|
fmt.Sprint(reviewDuplicateIntegerAnswer), fast.cookies[0].Value, fast.cookies[1].Value, fast.csrf[0],
|
|
}
|
|
logs := harness.logs.String()
|
|
for _, private := range privateValues {
|
|
if strings.Contains(logs, private) {
|
|
t.Errorf("logs contain %q", private)
|
|
}
|
|
}
|
|
for _, table := range []string{"assessment_answer_observations", "assessment_attempt_origin_marks", "assessment_attempt_reviews", "assessment_review_reads", "scheduled_jobs"} {
|
|
var document string
|
|
if err := harness.pool.QueryRow(ctx, fmt.Sprintf("SELECT COALESCE(string_agg(row_to_json(t)::text, ' '), '') FROM %s t", table)).Scan(&document); err != nil {
|
|
t.Fatalf("read %s as text: %v", table, err)
|
|
}
|
|
for _, private := range privateValues[:8] {
|
|
if strings.Contains(document, private) {
|
|
t.Errorf("table %s contains %q", table, private)
|
|
}
|
|
}
|
|
if table != "scheduled_jobs" && strings.Contains(document, fmt.Sprint(reviewDuplicateIntegerAnswer)) {
|
|
t.Errorf("table %s contains answer text", table)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Honest candidates with different seeds, answering correctly or not at random,
|
|
// are not flagged as duplicates, while a pair that copies the same answers is.
|
|
// A population of a few dozen carries little evidence per matched answer, so
|
|
// the thresholds are scaled down for the test; the demo thresholds are
|
|
// evaluated against ten thousand rivals by a unit test instead.
|
|
func TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag(t *testing.T) {
|
|
const honestCandidates = 30
|
|
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
|
defer cancel()
|
|
signals := domain.DemoAssessmentSignalPolicy()
|
|
signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 32, 44
|
|
harness := newReviewHarness(ctx, t, signals)
|
|
|
|
random := rand.New(rand.NewPCG(7, 11))
|
|
honest := make([]assessmentAnswerHTTPAttempt, 0, honestCandidates)
|
|
for index := range honestCandidates {
|
|
candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-honest-%02d@example.test", index), fmt.Sprintf("10.%d.0", index), 1)
|
|
attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-honest-create-%d", index), fmt.Sprintf("10.%d.0.30:1234", index))
|
|
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("10.%d.0.40", index)}, func(item assessmentAnswerHTTPItem) json.RawMessage {
|
|
return answerFromBody(t, 1, item, random.IntN(2) == 0)
|
|
}, fmt.Sprintf("review-honest-answer-%d", index))
|
|
candidate.finalize(t, harness, done, fmt.Sprintf("review-honest-finalize-%d", index), fmt.Sprintf("10.%d.0.41:1234", index))
|
|
honest = append(honest, attempt)
|
|
}
|
|
copies := make([]assessmentAnswerHTTPAttempt, 0, 2)
|
|
for index := range 2 {
|
|
candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-population-copy-%d@example.test", index), fmt.Sprintf("11.%d.0", index), 1)
|
|
attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-population-copy-create-%d", index), fmt.Sprintf("11.%d.0.30:1234", index))
|
|
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("11.%d.0.40", index)}, copiedReviewAnswer(t), fmt.Sprintf("review-population-copy-answer-%d", index))
|
|
candidate.finalize(t, harness, done, fmt.Sprintf("review-population-copy-finalize-%d", index), fmt.Sprintf("11.%d.0.41:1234", index))
|
|
copies = append(copies, attempt)
|
|
}
|
|
runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewNow, 10))
|
|
|
|
strongest := int32(0)
|
|
for index, attempt := range honest {
|
|
review, found := readStoredReview(t, ctx, harness, attempt.ID)
|
|
if !found {
|
|
t.Fatalf("honest attempt %d has no review", index)
|
|
}
|
|
strongest = max(strongest, review.Evidence)
|
|
if slices.Contains(review.Reasons, "duplicate_answers") {
|
|
t.Errorf("honest attempt %d is flagged as a duplicate: %+v", index, review)
|
|
}
|
|
}
|
|
t.Logf("strongest chance evidence among %d honest attempts: %d bits (attention level %d)", honestCandidates, strongest, signals.DuplicateAttentionBits)
|
|
for index, attempt := range copies {
|
|
review, found := readStoredReview(t, ctx, harness, attempt.ID)
|
|
if !found || !slices.Contains(review.Reasons, "duplicate_answers") || review.Evidence < signals.DuplicateAttentionBits {
|
|
t.Errorf("copied attempt %d review = %+v (found %v), want a duplicate flag in a population of %d", index, review, found, honestCandidates)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Several copied attempts end at the same moment and their jobs run on
|
|
// separate workers at once: no job deadlocks or retries, and every attempt is
|
|
// flagged.
|
|
func TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt(t *testing.T) {
|
|
const (
|
|
copiers = 4
|
|
honest = 8
|
|
)
|
|
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
|
defer cancel()
|
|
harness := newReviewHarness(ctx, t, reviewTestSignalPolicy())
|
|
|
|
// Honest attempts give the population its denominator: a value that every
|
|
// attempt of a tiny population shares carries no evidence at all.
|
|
for index := range honest {
|
|
candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-concurrent-honest-%d@example.test", index), fmt.Sprintf("13.%d.0", index), 1)
|
|
attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-concurrent-honest-create-%d", index), fmt.Sprintf("13.%d.0.30:1234", index))
|
|
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("13.%d.0.40", index)}, correctReviewAnswer(t), fmt.Sprintf("review-concurrent-honest-answer-%d", index))
|
|
candidate.finalize(t, harness, done, fmt.Sprintf("review-concurrent-honest-finalize-%d", index), fmt.Sprintf("13.%d.0.41:1234", index))
|
|
}
|
|
|
|
candidates := make([]reviewCandidate, copiers)
|
|
attempts := make([]assessmentAnswerHTTPAttempt, copiers)
|
|
done := make([]assessmentAnswerHTTPAttempt, copiers)
|
|
for index := range copiers {
|
|
candidates[index] = newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-concurrent-%d@example.test", index), fmt.Sprintf("12.%d.0", index), 1)
|
|
attempts[index] = candidates[index].createAttempt(t, harness, fmt.Sprintf("review-concurrent-create-%d", index), fmt.Sprintf("12.%d.0.30:1234", index))
|
|
}
|
|
for index := range copiers {
|
|
done[index] = candidates[index].answerAll(ctx, t, harness, attempts[index], 1, []string{fmt.Sprintf("12.%d.0.40", index)}, copiedReviewAnswer(t), fmt.Sprintf("review-concurrent-answer-%d", index))
|
|
}
|
|
var finalizing sync.WaitGroup
|
|
for index := range copiers {
|
|
finalizing.Add(1)
|
|
go func() {
|
|
defer finalizing.Done()
|
|
candidates[index].finalize(t, harness, done[index], fmt.Sprintf("review-concurrent-finalize-%d", index), fmt.Sprintf("12.%d.0.41:1234", index))
|
|
}()
|
|
}
|
|
finalizing.Wait()
|
|
|
|
var running sync.WaitGroup
|
|
start := make(chan struct{})
|
|
for range copiers {
|
|
running.Add(1)
|
|
worker := reviewJobWorker(t, harness, reviewNow, 1)
|
|
go func() {
|
|
defer running.Done()
|
|
<-start
|
|
runReviewJobs(ctx, t, worker)
|
|
}()
|
|
}
|
|
close(start)
|
|
running.Wait()
|
|
|
|
for index, attempt := range attempts {
|
|
review, found := readStoredReview(t, ctx, harness, attempt.ID)
|
|
if !found || review.Band != "review" || !slices.Contains(review.Reasons, "duplicate_answers") {
|
|
t.Errorf("copied attempt %d review = %+v (found %v), want it flagged", index, review, found)
|
|
}
|
|
}
|
|
var dead int
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND (status = 'dead' OR attempts > 1)`).Scan(&dead); err != nil || dead != 0 {
|
|
t.Fatalf("review jobs that failed or were retried = %d (error %v), want none", dead, err)
|
|
}
|
|
}
|
|
|
|
func readReviewCandidateResult(t *testing.T, harness *assessmentAttemptHTTPHarness, candidate reviewCandidate, attemptID uuid.UUID) map[string]any {
|
|
t.Helper()
|
|
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String()+"/result", "", "",
|
|
candidate.cookies[0].Value, "", "", "203.0.113.201:1234")
|
|
var result map[string]any
|
|
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &result) != nil {
|
|
t.Fatalf("read result = %d %s", response.Code, response.Body.String())
|
|
}
|
|
return result
|
|
}
|
|
|
|
// A review job takes the review lock of every attempt it writes before it reads
|
|
// any fact. While another writer holds the lock of an attempt, the job waits
|
|
// and does not read or write; after the writer commits, the job reads what was
|
|
// committed. This is what keeps a slow job from overwriting a newer review with
|
|
// an older evaluation.
|
|
func TestAssessmentSignalReviewJobWaitsForTheReviewLock(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
|
defer cancel()
|
|
harness := newReviewHarness(ctx, t, reviewTestSignalPolicy())
|
|
candidate := newReviewCandidate(ctx, t, harness, "review-lock@example.test", "14.0.0", 1)
|
|
attempt := candidate.createAttempt(t, harness, "review-lock-create", "14.0.0.30:1234")
|
|
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{"14.0.0.40"}, correctReviewAnswer(t), "review-lock-answer")
|
|
candidate.finalize(t, harness, done, "review-lock-finalize", "14.0.0.41:1234")
|
|
|
|
transactor := postgresadapter.NewTransactor(harness.pool)
|
|
locked, release, finished := make(chan struct{}), make(chan struct{}), make(chan error, 1)
|
|
go func() {
|
|
finished <- transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
if err := unit.AssessmentSignals().LockReview(ctx, domain.AssessmentAttemptID(attempt.ID)); err != nil {
|
|
return err
|
|
}
|
|
close(locked)
|
|
<-release
|
|
return nil
|
|
})
|
|
}()
|
|
<-locked
|
|
|
|
jobFinished := make(chan struct{})
|
|
go func() {
|
|
defer close(jobFinished)
|
|
runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewNow, 1))
|
|
}()
|
|
select {
|
|
case <-jobFinished:
|
|
t.Fatal("the review job finished while another writer held the review lock")
|
|
case <-time.After(1500 * time.Millisecond):
|
|
}
|
|
if _, found := readStoredReview(t, ctx, harness, attempt.ID); found {
|
|
t.Fatal("a review was written while the review lock was held elsewhere")
|
|
}
|
|
var running int
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status = 'running'`).Scan(&running); err != nil || running != 1 {
|
|
t.Fatalf("running review jobs = %d (error %v), want the one waiting for the lock", running, err)
|
|
}
|
|
close(release)
|
|
if err := <-finished; err != nil {
|
|
t.Fatalf("lock holder transaction error = %v", err)
|
|
}
|
|
select {
|
|
case <-jobFinished:
|
|
case <-time.After(30 * time.Second):
|
|
t.Fatal("the review job did not finish after the lock was released")
|
|
}
|
|
if review, found := readStoredReview(t, ctx, harness, attempt.ID); !found || review.Fast == 0 {
|
|
t.Fatalf("review after the lock was released = %+v (found %v), want it computed from the committed facts", review, found)
|
|
}
|
|
}
|