package assessment import ( "bytes" "context" "encoding/json" "errors" "fmt" "log/slog" "slices" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" ) // SignalDigester derives the keyed digests that stand for an answer, a login // session, and a client network in the stored server signals. No digest can be // turned back into what it stands for without the server secret. type SignalDigester interface { AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest // AssessmentDigestKeyVersion is the key generation of the digests above. AssessmentDigestKeyVersion() int16 } // SignalReviewJobKind is the scheduled job kind that computes reviews. const SignalReviewJobKind = "assessment.signal_review" const ( // signalReviewPairLimit bounds the other attempts one job refreshes. signalReviewPairLimit = 50 // signalReviewDeadlineGrace moves the deadline job past the deadline, so an // answer committed right at the deadline is in its facts. signalReviewDeadlineGrace = time.Minute signalReviewDeadlineKey = "deadline" signalReviewEndedKey = "ended" ) // RequestOrigin is what the HTTP adapter knows about the sender of an answer or // a signal batch: the authenticated session and the limiter key of the client // address. It is used only to make digests and is never stored or logged. An // empty ClientKey means the address could not be resolved. type RequestOrigin struct { SessionID uuid.UUID ClientKey string } // SignalObserver records server-side facts of real attempts and schedules the // computation of the manual-review band. The band has no effect on the result, // the category, or the quotas: it is written to its own tables by a scheduled // job and read by no candidate or employer operation. type SignalObserver struct { digester SignalDigester } // NewSignalObserver fails at startup when the digester is missing. func NewSignalObserver(digester SignalDigester) (*SignalObserver, error) { if digester == nil { return nil, errors.New("assessment.NewSignalObserver - digester must be set") } return &SignalObserver{digester: digester}, nil } // WithSignalObserver turns on the server signals of answers and the scheduling // of reviews. Without it the service records nothing. func (service *AttemptService) WithSignalObserver(observer *SignalObserver) *AttemptService { service.signalObserver = observer return service } // WithSignalObserver turns on the origin marks of accepted signal batches. func (service *SignalService) WithSignalObserver(observer *SignalObserver) *SignalService { service.observer = observer return service } func isRealAttemptKind(kind domain.AssessmentAttemptKind) bool { return kind == domain.AssessmentAttemptKindRoot || kind == domain.AssessmentAttemptKindCorrective } // observeAnswer stores the server time and the keyed answer fingerprint of an // answer that was just accepted and the origin of its request, and makes sure // a review job is due when the attempt reaches its deadline. It takes no lock // besides the attempt row the caller already holds. The time runs from the last // activity of the attempt, which is the previous answer or the start of the // current work session, to the answer. It is server time only. func (observer *SignalObserver) observeAnswer( ctx context.Context, unit outbound.UnitOfWork, before, after domain.AssessmentAttempt, itemID uuid.UUID, origin RequestOrigin, ) error { const location = "SignalObserver.observeAnswer" if observer == nil || !isRealAttemptKind(after.Kind()) { return nil } snapshot := after.Snapshot() previous := before.Snapshot() for _, item := range snapshot.Items { if item.ID != itemID { continue } answeredAt := item.AnsweredAt elapsed := answeredAt.Sub(previous.LastActivityAt).Milliseconds() elapsed = max(0, min(elapsed, int64(1<<31-1))) observation := domain.AssessmentAnswerObservation{ AttemptID: snapshot.ID, UserID: snapshot.UserID, ItemInstanceID: item.ID, FamilyID: item.Variant.FamilyID, FamilyVersion: item.Variant.FamilyVersion, Seed: item.Variant.Seed, AnswerFormat: item.Variant.AnswerFormat, Fingerprint: observer.digester.AssessmentAnswerFingerprint( uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer, ), KeyVersion: observer.digester.AssessmentDigestKeyVersion(), ElapsedMS: int32(elapsed), // The last activity is the previous answer when an item was answered // since the session started; then that answer is when this item was // shown. Otherwise the item is the first of the session. MeasuredFromAnswer: answeredSince(previous), ObservedAt: answeredAt, } repository := unit.AssessmentSignals() if err := repository.SaveAnswerObservation(ctx, observation); err != nil { return fmt.Errorf("%s - store answer observation: %w", location, err) } if err := observer.recordOrigin(ctx, repository, snapshot.ID, domain.AssessmentOriginAnswer, answeredAt, origin); err != nil { return fmt.Errorf("%s - record request origin: %w", location, err) } if err := scheduleSignalReview(ctx, unit, snapshot.ID, signalReviewDeadlineKey, snapshot.ExpiresAt.Add(signalReviewDeadlineGrace)); err != nil { return fmt.Errorf("%s - schedule the review at the deadline: %w", location, err) } return nil } return fmt.Errorf("%s - item is not part of the attempt: %w", location, domain.ErrInvalidAssessmentReview) } // answeredSince reports whether an item was answered at the last activity of // the attempt. func answeredSince(snapshot domain.AssessmentAttemptSnapshot) bool { for _, item := range snapshot.Items { if !item.AnsweredAt.IsZero() && item.AnsweredAt.Equal(snapshot.LastActivityAt) { return true } } return false } // recordOrigin stores the session and network digests of an accepted request // when they differ from the last stored mark, which is enough to count session // alternations and distinct networks. A request without a session is not // marked. The caller holds the attempt row lock, so the last mark is stable. func (observer *SignalObserver) recordOrigin( ctx context.Context, repository outbound.AssessmentSignalRepository, attemptID domain.AssessmentAttemptID, source domain.AssessmentOriginSource, at time.Time, origin RequestOrigin, ) error { const location = "SignalObserver.recordOrigin" if observer == nil || origin.SessionID == uuid.Nil { return nil } id, err := uuid.NewV7() if err != nil { return fmt.Errorf("%s - generate mark ID: %w", location, err) } mark := domain.AssessmentOriginMark{ ID: id, AttemptID: attemptID, Source: source, ObservedAt: at, SessionDigest: observer.digester.AssessmentSessionDigest(attemptID.UUID(), origin.SessionID), KeyVersion: observer.digester.AssessmentDigestKeyVersion(), } if origin.ClientKey != "" { mark.NetworkDigest = observer.digester.AssessmentNetworkDigest(attemptID.UUID(), origin.ClientKey) } last, found, err := repository.LastOriginMark(ctx, attemptID) if err != nil { return fmt.Errorf("%s - read last mark: %w", location, err) } if found && last.SessionDigest == mark.SessionDigest && last.NetworkDigest == mark.NetworkDigest && last.KeyVersion == mark.KeyVersion { return nil } if err := repository.SaveOriginMark(ctx, mark); err != nil { return fmt.Errorf("%s - store origin mark: %w", location, err) } return nil } // scheduleEndedReview makes a review due now for an attempt that just ended. // It runs in the transaction of the ending, so the job exists exactly when the // attempt ended; the review itself is computed later by the job and can never // block or change the result. func (observer *SignalObserver) scheduleEndedReview( ctx context.Context, unit outbound.UnitOfWork, attempt domain.AssessmentAttempt, at time.Time, ) error { if observer == nil || !isRealAttemptKind(attempt.Kind()) { return nil } return scheduleSignalReview(ctx, unit, attempt.ID(), signalReviewEndedKey, at) } func scheduleSignalReview( ctx context.Context, unit outbound.UnitOfWork, attemptID domain.AssessmentAttemptID, suffix string, dueAt time.Time, ) error { const location = "assessment.scheduleSignalReview" payload, err := json.Marshal(map[string]string{"attempt_id": attemptID.String()}) if err != nil { return fmt.Errorf("%s - encode payload: %w", location, err) } job, err := domain.NewScheduledJob(domain.ScheduledJobInput{ Kind: SignalReviewJobKind, Key: attemptID.String() + ":" + suffix, DueAt: dueAt, Payload: payload, }) if err != nil { return fmt.Errorf("%s - build job: %w", location, err) } if _, err := unit.ScheduledJobs().Schedule(ctx, job); err != nil { return fmt.Errorf("%s - schedule job: %w", location, err) } return nil } // SignalReviewJob computes the review of one attempt and refreshes the review // of every other ended attempt that shares answers with it, so that a match // flags both. It reads only committed facts and takes no lock apart from the // rows it writes, which it writes in ascending attempt order, so concurrent // jobs over shared attempts cannot deadlock. A job for an attempt that is still // running when the match is found is not needed: the running attempt has its // own job for its end and its deadline, and that job sees the other facts. type SignalReviewJob struct { logger *slog.Logger } // NewSignalReviewJob returns the handler of SignalReviewJobKind. The logger // receives one line per job with counts and the duration, never an answer, an // address, or a candidate. func NewSignalReviewJob(logger *slog.Logger) *SignalReviewJob { if logger == nil { logger = slog.New(slog.DiscardHandler) } return &SignalReviewJob{logger: logger} } // JobKind is the stable kind name. func (*SignalReviewJob) JobKind() string { return SignalReviewJobKind } // Handle computes the reviews. A malformed payload is final; any storage error // is retried by the runner with backoff. func (handler *SignalReviewJob) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error { const location = "SignalReviewJob.Handle" started := time.Now() attemptID, err := signalReviewJobAttempt(job) if err != nil { return fmt.Errorf("%s - read payload: %w", location, err) } repository := unit.AssessmentSignals() policyID, found, err := repository.ReviewSubject(ctx, attemptID) if err != nil { return fmt.Errorf("%s - read attempt: %w", location, err) } if !found { // The attempt is gone (its account was deleted) or is not a real attempt. return nil } policy, err := unit.Policies().GetByID(ctx, policyID) if err != nil { return fmt.Errorf("%s - read pinned policy: %w", location, err) } signals := policy.Policy().Assessment.Signals if signals == nil { return nil } now, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return fmt.Errorf("%s - read database time: %w", location, err) } now = now.UTC().Truncate(time.Microsecond) targets, err := reviewTargets(ctx, repository, attemptID, policyID, signals, now) if err != nil { return fmt.Errorf("%s - list matched attempts: %w", location, err) } if err := writeReviews(ctx, unit, targets, policy, now); err != nil { return fmt.Errorf("%s - write reviews: %w", location, err) } handler.logger.InfoContext(ctx, "assessment review job finished", slog.Int("reviews", len(targets)), slog.Int("matched_attempts", len(targets)-1), slog.Int64("duration_ms", time.Since(started).Milliseconds())) return nil } func signalReviewJobAttempt(job outbound.ClaimedJob) (domain.AssessmentAttemptID, error) { var payload struct { AttemptID string `json:"attempt_id"` } if err := json.Unmarshal(job.Payload, &payload); err != nil { return domain.AssessmentAttemptID{}, fmt.Errorf("decode payload: %w", inbound.ErrJobRejected) } parsed, err := uuid.Parse(payload.AttemptID) if err != nil || parsed == uuid.Nil { return domain.AssessmentAttemptID{}, fmt.Errorf("payload names no attempt: %w", inbound.ErrJobRejected) } return domain.AssessmentAttemptID(parsed), nil } // writeReviews locks every review it will write, in ascending attempt order, // before any fact is read. The later of two jobs over one attempt then waits // here and reads what the earlier one committed, so no job overwrites a newer // review with an older evaluation, and no lock order can form a cycle. func writeReviews( ctx context.Context, unit outbound.UnitOfWork, targets []reviewTarget, own domain.PolicyVersion, now time.Time, ) error { repository := unit.AssessmentSignals() for _, entry := range targets { if err := repository.LockReview(ctx, entry.id); err != nil { return fmt.Errorf("lock review: %w", err) } } for _, entry := range targets { pinned := own if entry.policy != own.ID() { var err error if pinned, err = unit.Policies().GetByID(ctx, entry.policy); err != nil { return fmt.Errorf("read pinned policy of a matched attempt: %w", err) } } if err := evaluateReview(ctx, repository, entry.id, pinned, now); err != nil { return fmt.Errorf("evaluate attempt: %w", err) } } return nil } type reviewTarget struct { id domain.AssessmentAttemptID policy domain.PolicyVersionID } // reviewTargets lists the attempt itself and the ended attempts whose pair with // it reaches the attention level, in ascending attempt order. Two jobs over the // same pair therefore lock the review rows in the same order. func reviewTargets( ctx context.Context, repository outbound.AssessmentSignalRepository, attemptID domain.AssessmentAttemptID, policyID domain.PolicyVersionID, signals *domain.AssessmentSignalPolicy, now time.Time, ) ([]reviewTarget, error) { pairs, err := repository.DuplicatePairs(ctx, attemptID, outbound.AssessmentDuplicateQuery{ IntegerCapBits: signals.DuplicateIntegerCapBits, SequenceCapBits: signals.DuplicateSequenceCapBits, MinBits: signals.DuplicateAttentionBits, EndedOnly: true, Now: now, Limit: signalReviewPairLimit, }) if err != nil { return nil, err } targets := []reviewTarget{{id: attemptID, policy: policyID}} for _, pair := range pairs { if pair.AttemptID != attemptID { targets = append(targets, reviewTarget{id: pair.AttemptID, policy: pair.PolicyVersionID}) } } slices.SortFunc(targets, func(left, right reviewTarget) int { return bytes.Compare(left.id[:], right.id[:]) }) return targets, nil } // evaluateReview computes and stores the review of one attempt under the // signal thresholds of the policy version that attempt is pinned to. A version // without a signal section produces no review. func evaluateReview( ctx context.Context, repository outbound.AssessmentSignalRepository, attemptID domain.AssessmentAttemptID, policy domain.PolicyVersion, now time.Time, ) error { const location = "assessment.evaluateReview" signals := policy.Policy().Assessment.Signals if signals == nil { return nil } inputs, err := repository.ReviewInputs(ctx, attemptID) if err != nil { return fmt.Errorf("%s - read stored facts: %w", location, err) } best, err := repository.DuplicatePairs(ctx, attemptID, outbound.AssessmentDuplicateQuery{ IntegerCapBits: signals.DuplicateIntegerCapBits, SequenceCapBits: signals.DuplicateSequenceCapBits, Limit: 1, }) if err != nil { return fmt.Errorf("%s - find the strongest pair: %w", location, err) } times := signals.ClassifyResponseTimes(inputs.Answers) anomalies := domain.CountOriginAnomalies(inputs.Marks) measures := domain.AssessmentReviewMeasures{ AnsweredItems: times.Answered, FastAnswers: times.Fast, DeviatingAnswers: times.Deviating, ParallelAlternations: anomalies.ParallelAlternations, ExtraNetworks: anomalies.ExtraNetworks, ClientFocusLossMS: inputs.ClientFocusLossMS, ClientClipboardEvents: inputs.ClientClipboardCount, ClientFullscreenExits: inputs.ClientFullscreenExit, } if len(best) > 0 { measures.DuplicateEvidenceBits = best[0].EvidenceBits measures.MatchedIntegerItems, measures.MatchedSequenceItems = best[0].IntegerItems, best[0].SequenceItems } review := domain.AssessmentAttemptReview{ AttemptID: attemptID, PolicyVersionID: policy.ID(), PolicyVersion: policy.Version(), Measures: measures, Outcome: signals.Evaluate(measures), EvaluatedAt: now, UpdatedAt: now, } if err := repository.SaveReview(ctx, review); err != nil { return fmt.Errorf("%s - store review: %w", location, err) } return nil } // ReviewOperator lets an operator read the stored review of one attempt. Every // read is recorded with the operator handle. Until staff roles exist this is // the only way to read a band. type ReviewOperator struct { transactor outbound.Transactor } func NewReviewOperator(transactor outbound.Transactor) (*ReviewOperator, error) { if transactor == nil { return nil, errors.New("assessment.NewReviewOperator - transactor must be set") } return &ReviewOperator{transactor: transactor}, nil } // Inspect returns the review of an attempt and records the read, also when the // attempt has no review. The actor is an audit handle, not authentication. func (operator *ReviewOperator) Inspect( ctx context.Context, attemptID domain.AssessmentAttemptID, actor string, ) (domain.AssessmentAttemptReview, error) { const location = "ReviewOperator.Inspect" parsed, err := domain.ParseAssessmentReviewActor(actor) if err != nil { return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - parse actor: %w", location, err) } if attemptID.IsZero() { return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) } readID, err := uuid.NewV7() if err != nil { return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - generate read ID: %w", location, err) } var review domain.AssessmentAttemptReview missing := false err = operator.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { repository := unit.AssessmentSignals() stored, err := repository.GetReview(ctx, attemptID) switch { case errors.Is(err, outbound.ErrAssessmentReviewNotFound): missing = true case err != nil: return fmt.Errorf("%s - read review: %w", location, err) default: review = stored } at, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return fmt.Errorf("%s - read database time: %w", location, err) } if err := repository.RecordReviewRead(ctx, readID, attemptID, parsed, !missing, at.UTC().Truncate(time.Microsecond)); err != nil { return fmt.Errorf("%s - record read: %w", location, err) } return nil }) if err != nil { return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - transaction: %w", location, err) } if missing { return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt has no review: %w", location, outbound.ErrAssessmentReviewNotFound) } return review, nil }