feat(assessment): add the review band of attempt signals and the disclosed collector
This commit is contained in:
1 parent
68286af8b7
commit
b3c6dc870b
124 files changed
+13522
-633
No files matched your search
@@ -24,6 +24,9 @@ type SubmitAttemptAnswerCommand struct {
|
||||
ExpectedVersion int64
|
||||
IdempotencyKey string
|
||||
Answer json.RawMessage
|
||||
// Origin is the sender of the request. It feeds the server signals only and
|
||||
// is not part of the idempotency fingerprint.
|
||||
Origin RequestOrigin
|
||||
}
|
||||
|
||||
type canonicalAttemptAnswerBody struct {
|
||||
@@ -132,7 +135,7 @@ func (service *AttemptService) submitNewAnswer(
|
||||
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
|
||||
}
|
||||
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
|
||||
return service.persistSubmittedAnswer(ctx, repository, scope, command, current, databaseTime, result)
|
||||
return service.persistSubmittedAnswer(ctx, unit, repository, scope, command, current, databaseTime, result)
|
||||
}
|
||||
|
||||
func lockAttemptForAnswer(
|
||||
@@ -168,6 +171,7 @@ func lockAttemptForAnswer(
|
||||
|
||||
func (service *AttemptService) persistSubmittedAnswer(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command SubmitAttemptAnswerCommand,
|
||||
@@ -199,6 +203,11 @@ func (service *AttemptService) persistSubmittedAnswer(
|
||||
if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil {
|
||||
return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err)
|
||||
}
|
||||
if err := service.signalObserver.observeAnswer(
|
||||
ctx, unit, current, updated, command.ItemID, command.Origin,
|
||||
); err != nil {
|
||||
return fmt.Errorf("%s - observe accepted answer: %w", location, err)
|
||||
}
|
||||
}
|
||||
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
|
||||
if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil {
|
||||
|
||||
@@ -64,6 +64,7 @@ type AttemptService struct {
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
categoryDecisions AssessmentCategoryDecisionService
|
||||
signalObserver *SignalObserver
|
||||
}
|
||||
|
||||
// NewAttemptService fails at startup when a required dependency is missing.
|
||||
|
||||
@@ -244,7 +244,16 @@ func (service *AttemptService) finalizeActiveAttempt(
|
||||
}
|
||||
return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr)
|
||||
}
|
||||
return service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result)
|
||||
if err := service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result); err != nil {
|
||||
return err
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
if err := service.signalObserver.scheduleEndedReview(ctx, unit, updated, databaseTime); err != nil {
|
||||
return fmt.Errorf("%s - schedule review: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *AttemptService) persistFinalizedAttempt(
|
||||
|
||||
@@ -51,6 +51,7 @@ type SignalService struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
observer *SignalObserver
|
||||
}
|
||||
|
||||
func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) {
|
||||
@@ -65,6 +66,9 @@ type RecordSignalsCommand struct {
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
IdempotencyKey string
|
||||
Events []domain.AssessmentSignalEvent
|
||||
// Origin is the sender of the batch. It feeds the server signals only and
|
||||
// is not part of the idempotency fingerprint.
|
||||
Origin RequestOrigin
|
||||
}
|
||||
|
||||
type canonicalSignalRequest struct {
|
||||
@@ -191,6 +195,11 @@ func (service *SignalService) recordNewSignals(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - persist bounded event batch: %w", location, err)
|
||||
}
|
||||
if status == domain.AssessmentSignalReceiptAccepted {
|
||||
if err := service.observer.recordOrigin(ctx, repository, attempt.ID(), domain.AssessmentOriginSignals, databaseTime, command.Origin); err != nil {
|
||||
return fmt.Errorf("%s - record request origin: %w", location, err)
|
||||
}
|
||||
}
|
||||
newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build receipt: %w", location, err)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// CurrentSignalNoticeVersion is the version of the notice text that lists the
|
||||
// collected assessment signals. Change it together with the client text so that
|
||||
// every candidate acknowledges the new wording.
|
||||
const CurrentSignalNoticeVersion int32 = 1
|
||||
|
||||
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
|
||||
// version other than the one the server requires.
|
||||
var ErrSignalNoticeVersionMismatch = errors.New("assessment signal notice version is not current")
|
||||
|
||||
// SignalNoticeState is the acknowledgement state of the current notice version.
|
||||
type SignalNoticeState struct {
|
||||
Version int32
|
||||
Acknowledged bool
|
||||
AcknowledgedAt time.Time
|
||||
}
|
||||
|
||||
// GetSignalNotice reads whether the candidate acknowledged the current notice.
|
||||
// The record is not a consent and does not influence signal storage.
|
||||
func (service *SignalService) GetSignalNotice(ctx context.Context, actorID uuid.UUID) (SignalNoticeState, error) {
|
||||
const location = "SignalService.GetSignalNotice"
|
||||
state := SignalNoticeState{Version: CurrentSignalNoticeVersion}
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, actorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
acknowledgedAt, err := unit.AssessmentSignalNotices().Get(ctx, actorID, CurrentSignalNoticeVersion)
|
||||
if errors.Is(err, outbound.ErrAssessmentSignalNoticeNotAcknowledged) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read acknowledgement: %w", location, err)
|
||||
}
|
||||
state.Acknowledged, state.AcknowledgedAt = true, acknowledgedAt
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return SignalNoticeState{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// AcknowledgeSignalNotice records the first acknowledgement of the current
|
||||
// notice version. A repeat keeps the stored time, so a retry after a lost
|
||||
// response succeeds. Another version is refused without storing anything.
|
||||
func (service *SignalService) AcknowledgeSignalNotice(
|
||||
ctx context.Context,
|
||||
actorID uuid.UUID,
|
||||
version int32,
|
||||
) (SignalNoticeState, error) {
|
||||
const location = "SignalService.AcknowledgeSignalNotice"
|
||||
if version != CurrentSignalNoticeVersion {
|
||||
return SignalNoticeState{}, fmt.Errorf("%s - compare version: %w", location, ErrSignalNoticeVersionMismatch)
|
||||
}
|
||||
state := SignalNoticeState{Version: CurrentSignalNoticeVersion, Acknowledged: true}
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, actorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
now, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time: %w", location, err)
|
||||
}
|
||||
state.AcknowledgedAt, err = unit.AssessmentSignalNotices().Acknowledge(
|
||||
ctx, actorID, CurrentSignalNoticeVersion, now.UTC().Truncate(time.Microsecond),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - store acknowledgement: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return SignalNoticeState{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,700 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var signalReviewTestTime = time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
// signalDigesterFake derives plain SHA-256 values so a test can compare them;
|
||||
// the production keyring uses HMAC under a server secret.
|
||||
type signalDigesterFake struct{}
|
||||
|
||||
func (signalDigesterFake) AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, answer []byte) domain.AssessmentDigest {
|
||||
return domain.AssessmentDigest(sha256.Sum256(append(append(familyID[:], binary.BigEndian.AppendUint32(nil, uint32(familyVersion))...), answer...)))
|
||||
}
|
||||
|
||||
func (signalDigesterFake) AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest {
|
||||
return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], sessionID[:]...)))
|
||||
}
|
||||
|
||||
func (signalDigesterFake) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest {
|
||||
return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], clientKey...)))
|
||||
}
|
||||
|
||||
func (signalDigesterFake) AssessmentDigestKeyVersion() int16 { return 7 }
|
||||
|
||||
// signalRepositoryFake records the writes of the observer and the job. The
|
||||
// embedded interface is nil, so a call the test does not expect panics.
|
||||
type signalRepositoryFake struct {
|
||||
outbound.AssessmentSignalRepository
|
||||
|
||||
observations []domain.AssessmentAnswerObservation
|
||||
marks []domain.AssessmentOriginMark
|
||||
reviews []domain.AssessmentAttemptReview
|
||||
inputs outbound.AssessmentReviewInputs
|
||||
pairs map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair
|
||||
subjects map[domain.AssessmentAttemptID]domain.PolicyVersionID
|
||||
queries []outbound.AssessmentDuplicateQuery
|
||||
// events records the order of locks and reads of a job.
|
||||
events []string
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) SaveAnswerObservation(_ context.Context, observation domain.AssessmentAnswerObservation) error {
|
||||
repository.observations = append(repository.observations, observation)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) SaveOriginMark(_ context.Context, mark domain.AssessmentOriginMark) error {
|
||||
repository.marks = append(repository.marks, mark)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) LastOriginMark(context.Context, domain.AssessmentAttemptID) (domain.AssessmentOriginMark, bool, error) {
|
||||
if len(repository.marks) == 0 {
|
||||
return domain.AssessmentOriginMark{}, false, nil
|
||||
}
|
||||
return repository.marks[len(repository.marks)-1], true, nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) ReviewInputs(context.Context, domain.AssessmentAttemptID) (outbound.AssessmentReviewInputs, error) {
|
||||
repository.events = append(repository.events, "read")
|
||||
return repository.inputs, nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) LockReview(_ context.Context, attemptID domain.AssessmentAttemptID) error {
|
||||
repository.events = append(repository.events, "lock:"+attemptID.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) DuplicatePairs(
|
||||
_ context.Context,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
query outbound.AssessmentDuplicateQuery,
|
||||
) ([]outbound.AssessmentDuplicatePair, error) {
|
||||
repository.queries = append(repository.queries, query)
|
||||
pairs := repository.pairs[attemptID]
|
||||
if query.MinBits > 0 {
|
||||
pairs = slices.DeleteFunc(slices.Clone(pairs), func(pair outbound.AssessmentDuplicatePair) bool { return pair.EvidenceBits < query.MinBits })
|
||||
}
|
||||
return pairs, nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) ReviewSubject(_ context.Context, attemptID domain.AssessmentAttemptID) (domain.PolicyVersionID, bool, error) {
|
||||
id, found := repository.subjects[attemptID]
|
||||
return id, found, nil
|
||||
}
|
||||
|
||||
func (repository *signalRepositoryFake) SaveReview(_ context.Context, review domain.AssessmentAttemptReview) error {
|
||||
repository.reviews = append(repository.reviews, review)
|
||||
return nil
|
||||
}
|
||||
|
||||
type jobSchedulerFake struct {
|
||||
jobs []domain.ScheduledJob
|
||||
}
|
||||
|
||||
func (scheduler *jobSchedulerFake) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) {
|
||||
scheduler.jobs = append(scheduler.jobs, job)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (*jobSchedulerFake) Cancel(context.Context, string, string) (bool, error) { return false, nil }
|
||||
|
||||
type policiesFake struct {
|
||||
outbound.PolicyRepository
|
||||
|
||||
versions map[domain.PolicyVersionID]domain.PolicyVersion
|
||||
}
|
||||
|
||||
func (policies policiesFake) GetByID(_ context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
return policies.versions[id], nil
|
||||
}
|
||||
|
||||
type bankClockFake struct {
|
||||
outbound.AssessmentBankRepository
|
||||
}
|
||||
|
||||
func (bankClockFake) DatabaseTime(context.Context) (time.Time, error) {
|
||||
return signalReviewTestTime, nil
|
||||
}
|
||||
|
||||
type signalUnitFake struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
repository *signalRepositoryFake
|
||||
scheduler *jobSchedulerFake
|
||||
policies policiesFake
|
||||
}
|
||||
|
||||
func newSignalUnitFake() *signalUnitFake {
|
||||
return &signalUnitFake{repository: &signalRepositoryFake{}, scheduler: &jobSchedulerFake{}}
|
||||
}
|
||||
|
||||
func (unit *signalUnitFake) AssessmentSignals() outbound.AssessmentSignalRepository {
|
||||
return unit.repository
|
||||
}
|
||||
func (unit *signalUnitFake) ScheduledJobs() outbound.JobScheduler { return unit.scheduler }
|
||||
func (unit *signalUnitFake) Policies() outbound.PolicyRepository { return unit.policies }
|
||||
func (unit *signalUnitFake) AssessmentBank() outbound.AssessmentBankRepository {
|
||||
return bankClockFake{}
|
||||
}
|
||||
|
||||
func signalReviewFamily(t *testing.T, draft domain.AssessmentFamilyDraft) domain.AssessmentFamily {
|
||||
t.Helper()
|
||||
core, hash := draft.Core(), draft.ContentHash()
|
||||
generator, err := draft.SeedGeneratorJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("SeedGeneratorJSON() error = %v", err)
|
||||
}
|
||||
answerKey, err := draft.AnswerKeyJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("AnswerKeyJSON() error = %v", err)
|
||||
}
|
||||
rubric, err := draft.RubricJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("RubricJSON() error = %v", err)
|
||||
}
|
||||
family, err := domain.RestoreAssessmentFamily(domain.StoredAssessmentFamily{
|
||||
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
|
||||
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName),
|
||||
Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus),
|
||||
SeedGenerator: generator, AnswerKey: answerKey, Rubric: rubric, ContentHash: hash[:],
|
||||
HashScheme: draft.HashScheme(), Lifecycle: string(domain.AssessmentLifecycleDraft), CreatedAt: signalReviewTestTime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
|
||||
}
|
||||
return family
|
||||
}
|
||||
|
||||
func signalReviewDemoFamilies(t *testing.T) []domain.AssessmentFamily {
|
||||
t.Helper()
|
||||
drafts, err := loadDemoBundle(t).Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
families := make([]domain.AssessmentFamily, 0, len(drafts))
|
||||
for _, draft := range drafts {
|
||||
families = append(families, signalReviewFamily(t, draft))
|
||||
}
|
||||
return families
|
||||
}
|
||||
|
||||
func signalReviewPolicyVersion(t *testing.T, number int32, policy domain.ProductPolicy) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor,
|
||||
EffectiveAt: signalReviewTestTime, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(number)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash := numbered.DocumentHash()
|
||||
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
|
||||
Author: string(numbered.Author()), EffectiveAt: signalReviewTestTime, CreatedAt: signalReviewTestTime,
|
||||
Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
func signalReviewAttempt(t *testing.T, policy domain.PolicyVersion, kind domain.AssessmentAttemptKind) domain.AssessmentAttempt {
|
||||
t.Helper()
|
||||
families := signalReviewDemoFamilies(t)
|
||||
items := make([]domain.AssessmentAttemptItemInput, len(families))
|
||||
for index, family := range families {
|
||||
variant, err := family.NewVariant(domain.VariantSeed(1000 + index))
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant() error = %v", err)
|
||||
}
|
||||
items[index] = domain.AssessmentAttemptItemInput{Variant: variant}
|
||||
}
|
||||
versions := domain.AssessmentAttemptVersions{
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
BankVersion: "backend-demo.v1", AlgorithmVersion: "assessment.v1",
|
||||
}
|
||||
input := domain.NewAssessmentAttemptInput{
|
||||
UserID: uuid.New(), Kind: kind, BankCategory: "backend", Versions: versions, Policy: policy,
|
||||
CreatedAt: signalReviewTestTime, Items: items,
|
||||
}
|
||||
if kind == domain.AssessmentAttemptKindDemoExpress {
|
||||
input.BankCategory = "training-demo"
|
||||
input.Items = items[:policy.Policy().Assessment.Training.DemoExpressItemCount]
|
||||
input.Versions.TrainingBindingID, input.Versions.TrainingManifestHash = uuid.New(), [32]byte{2}
|
||||
} else {
|
||||
specialization, grade := domain.SpecializationBackend, domain.GradeJunior
|
||||
input.Specialization, input.TargetGrade = &specialization, &grade
|
||||
input.Versions.GradingPolicyVersionID, input.Versions.OpeningID = policy.ID(), uuid.New()
|
||||
input.Versions.OpeningManifestHash = [32]byte{1}
|
||||
}
|
||||
attempt, err := domain.NewAssessmentAttempt(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
return attempt
|
||||
}
|
||||
|
||||
func signalReviewFirstAnswer(t *testing.T, attempt domain.AssessmentAttempt, at time.Time) (domain.AssessmentAttempt, domain.AssessmentAttemptItemSnapshot) {
|
||||
t.Helper()
|
||||
item := attempt.Snapshot().Items[0]
|
||||
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, json.RawMessage(`{"format":"number","number":424242}`), at)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer() = changed %v, error %v", changed, err)
|
||||
}
|
||||
return updated, updated.Snapshot().Items[0]
|
||||
}
|
||||
|
||||
func signalReviewSecondAnswer(t *testing.T, attempt domain.AssessmentAttempt, at time.Time) (domain.AssessmentAttempt, domain.AssessmentAttemptItemSnapshot) {
|
||||
t.Helper()
|
||||
item := attempt.Snapshot().Items[1]
|
||||
tasks := item.Variant.Parameters["tasks"]
|
||||
elements := make([]string, 0, tasks)
|
||||
for task := int32(1); task <= tasks; 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 order answer: %v", err)
|
||||
}
|
||||
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, at)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer(second) = changed %v, error %v", changed, err)
|
||||
}
|
||||
return updated, updated.Snapshot().Items[1]
|
||||
}
|
||||
|
||||
func TestObserveAnswerStoresServerTimeAndKeyedFingerprintOnly(t *testing.T) {
|
||||
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
answeredAt := signalReviewTestTime.Add(12*time.Second + 340*time.Millisecond)
|
||||
updated, item := signalReviewFirstAnswer(t, attempt, answeredAt)
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
unit := newSignalUnitFake()
|
||||
origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77"}
|
||||
if err := observer.observeAnswer(context.Background(), unit, attempt, updated, item.ID, origin); err != nil {
|
||||
t.Fatalf("observeAnswer() error = %v", err)
|
||||
}
|
||||
if len(unit.repository.observations) != 1 || len(unit.repository.marks) != 1 {
|
||||
t.Fatalf("stored %d observations and %d marks, want one of each", len(unit.repository.observations), len(unit.repository.marks))
|
||||
}
|
||||
observation := unit.repository.observations[0]
|
||||
if observation.ElapsedMS != 12340 || observation.ItemInstanceID != item.ID || observation.FamilyID != item.Variant.FamilyID ||
|
||||
observation.Seed != item.Variant.Seed || observation.AnswerFormat != item.Variant.AnswerFormat {
|
||||
t.Fatalf("observation = %+v, want 12340 ms from the attempt start for the answered item", observation)
|
||||
}
|
||||
if observation.MeasuredFromAnswer {
|
||||
t.Fatal("the first item of a session was measured from an answer; it is measured from the session start")
|
||||
}
|
||||
if observation.KeyVersion != 7 || unit.repository.marks[0].KeyVersion != 7 {
|
||||
t.Fatalf("key versions = %d and %d, want the digester generation 7", observation.KeyVersion, unit.repository.marks[0].KeyVersion)
|
||||
}
|
||||
if want := (signalDigesterFake{}).AssessmentAnswerFingerprint(uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer); observation.Fingerprint != want {
|
||||
t.Fatal("fingerprint is not the keyed digest of the canonical answer")
|
||||
}
|
||||
mark := unit.repository.marks[0]
|
||||
if mark.Source != domain.AssessmentOriginAnswer || mark.NetworkDigest.IsZero() || mark.SessionDigest.IsZero() {
|
||||
t.Fatalf("origin mark = %+v, want an answer mark with session and network digests", mark)
|
||||
}
|
||||
stored := fmt.Sprintf("%+v %+v", observation, mark)
|
||||
for _, secret := range []string{"424242", "198.51.100.77", origin.SessionID.String()} {
|
||||
if strings.Contains(stored, secret) {
|
||||
t.Fatalf("stored facts contain %q", secret)
|
||||
}
|
||||
}
|
||||
|
||||
// A review is due when the attempt reaches its deadline, however it ends.
|
||||
if len(unit.scheduler.jobs) != 1 {
|
||||
t.Fatalf("scheduled %d jobs, want the review at the deadline", len(unit.scheduler.jobs))
|
||||
}
|
||||
job := unit.scheduler.jobs[0]
|
||||
if job.Kind() != SignalReviewJobKind || job.Key() != attempt.ID().String()+":deadline" || !job.DueAt().Equal(attempt.ExpiresAt().Add(time.Minute)) {
|
||||
t.Fatalf("job = %s %s due %s, want the deadline job of the attempt due a minute after its expiry", job.Kind(), job.Key(), job.DueAt())
|
||||
}
|
||||
if strings.Contains(string(job.Payload()), "424242") || !strings.Contains(string(job.Payload()), attempt.ID().String()) {
|
||||
t.Fatalf("job payload = %s, want the attempt ID only", job.Payload())
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveAnswerMeasuresLaterItemsFromThePreviousAnswerAndMarksOnlyChanges(t *testing.T) {
|
||||
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
first := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
firstUpdated, firstItem := signalReviewFirstAnswer(t, first, signalReviewTestTime.Add(20*time.Second))
|
||||
secondUpdated, secondItem := signalReviewSecondAnswer(t, firstUpdated, signalReviewTestTime.Add(24*time.Second))
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
unit := newSignalUnitFake()
|
||||
origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77"}
|
||||
if err := observer.observeAnswer(context.Background(), unit, first, firstUpdated, firstItem.ID, origin); err != nil {
|
||||
t.Fatalf("observeAnswer(first) error = %v", err)
|
||||
}
|
||||
if err := observer.observeAnswer(context.Background(), unit, firstUpdated, secondUpdated, secondItem.ID, origin); err != nil {
|
||||
t.Fatalf("observeAnswer(second) error = %v", err)
|
||||
}
|
||||
second := unit.repository.observations[1]
|
||||
if second.ElapsedMS != 4000 || !second.MeasuredFromAnswer {
|
||||
t.Fatalf("second observation = %+v, want 4000 ms measured from the previous answer", second)
|
||||
}
|
||||
if len(unit.repository.marks) != 1 {
|
||||
t.Fatalf("stored %d marks for two requests from one session and network, want 1", len(unit.repository.marks))
|
||||
}
|
||||
|
||||
// Writing a mark for every request would grow without bound; a change of the
|
||||
// session or the network writes one.
|
||||
thirdOrigin := RequestOrigin{SessionID: origin.SessionID, ClientKey: "203.0.113.5"}
|
||||
if err := observer.recordOrigin(context.Background(), unit.repository, first.ID(), domain.AssessmentOriginSignals, signalReviewTestTime, thirdOrigin); err != nil {
|
||||
t.Fatalf("recordOrigin(new network) error = %v", err)
|
||||
}
|
||||
if err := observer.recordOrigin(context.Background(), unit.repository, first.ID(), domain.AssessmentOriginSignals, signalReviewTestTime, thirdOrigin); err != nil {
|
||||
t.Fatalf("recordOrigin(repeat) error = %v", err)
|
||||
}
|
||||
if len(unit.repository.marks) != 2 {
|
||||
t.Fatalf("stored %d marks after a network change and a repeat, want 2", len(unit.repository.marks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveAnswerSkipsTrainingAttemptsAndMarksNothingWithoutASession(t *testing.T) {
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
|
||||
training := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindDemoExpress)
|
||||
trainingUpdated, trainingItem := signalReviewFirstAnswer(t, training, signalReviewTestTime.Add(time.Second))
|
||||
unit := newSignalUnitFake()
|
||||
if err := observer.observeAnswer(context.Background(), unit, training, trainingUpdated, trainingItem.ID, RequestOrigin{SessionID: uuid.New()}); err != nil {
|
||||
t.Fatalf("observeAnswer(training) error = %v", err)
|
||||
}
|
||||
if err := observer.scheduleEndedReview(context.Background(), unit, trainingUpdated, signalReviewTestTime); err != nil {
|
||||
t.Fatalf("scheduleEndedReview(training) error = %v", err)
|
||||
}
|
||||
if len(unit.repository.observations)+len(unit.repository.marks)+len(unit.scheduler.jobs) != 0 {
|
||||
t.Fatal("a training attempt produced server signals or a review job")
|
||||
}
|
||||
|
||||
root := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
rootUpdated, rootItem := signalReviewFirstAnswer(t, root, signalReviewTestTime.Add(time.Second))
|
||||
if err := observer.observeAnswer(context.Background(), unit, root, rootUpdated, rootItem.ID, RequestOrigin{}); err != nil {
|
||||
t.Fatalf("observeAnswer(no session) error = %v", err)
|
||||
}
|
||||
if len(unit.repository.observations) != 1 || len(unit.repository.marks) != 0 {
|
||||
t.Fatalf("no-session request stored %d observations and %d marks, want 1 and 0", len(unit.repository.observations), len(unit.repository.marks))
|
||||
}
|
||||
|
||||
var disabled *SignalObserver
|
||||
if err := disabled.observeAnswer(context.Background(), unit, root, rootUpdated, rootItem.ID, RequestOrigin{SessionID: uuid.New()}); err != nil {
|
||||
t.Fatalf("observeAnswer(disabled observer) error = %v", err)
|
||||
}
|
||||
if err := disabled.scheduleEndedReview(context.Background(), unit, rootUpdated, signalReviewTestTime); err != nil {
|
||||
t.Fatalf("scheduleEndedReview(disabled observer) error = %v", err)
|
||||
}
|
||||
if len(unit.repository.observations) != 1 {
|
||||
t.Fatal("a disabled observer stored an observation")
|
||||
}
|
||||
if _, err := NewSignalObserver(nil); err == nil {
|
||||
t.Fatal("NewSignalObserver(nil) accepted a missing digester")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleEndedReviewIsKeyedByTheAttemptEnding(t *testing.T) {
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
attempt := signalReviewAttempt(t, signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()), domain.AssessmentAttemptKindRoot)
|
||||
unit := newSignalUnitFake()
|
||||
if err := observer.scheduleEndedReview(context.Background(), unit, attempt, signalReviewTestTime); err != nil {
|
||||
t.Fatalf("scheduleEndedReview() error = %v", err)
|
||||
}
|
||||
job := unit.scheduler.jobs[0]
|
||||
if job.Key() != attempt.ID().String()+":ended" || !job.DueAt().Equal(signalReviewTestTime) {
|
||||
t.Fatalf("job = %s due %s, want the ended job due at the ending", job.Key(), job.DueAt())
|
||||
}
|
||||
}
|
||||
|
||||
func signalJob(attemptID domain.AssessmentAttemptID) outbound.ClaimedJob {
|
||||
return outbound.ClaimedJob{
|
||||
Kind: SignalReviewJobKind, Key: attemptID.String() + ":ended",
|
||||
Payload: json.RawMessage(`{"attempt_id":"` + attemptID.String() + `"}`),
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignalReviewJobRefusesBrokenPayloadsAndIgnoresMissingAttempts(t *testing.T) {
|
||||
job := NewSignalReviewJob(nil)
|
||||
if job.JobKind() != "assessment.signal_review" {
|
||||
t.Fatalf("JobKind() = %q", job.JobKind())
|
||||
}
|
||||
unit := newSignalUnitFake()
|
||||
for _, payload := range []string{``, `{}`, `{"attempt_id":"not-a-uuid"}`, `{"attempt_id":"00000000-0000-0000-0000-000000000000"}`} {
|
||||
err := job.Handle(context.Background(), unit, outbound.ClaimedJob{Payload: json.RawMessage(payload)})
|
||||
if !errors.Is(err, inbound.ErrJobRejected) {
|
||||
t.Errorf("Handle(%q) error = %v, want a rejected job", payload, err)
|
||||
}
|
||||
}
|
||||
if err := job.Handle(context.Background(), unit, signalJob(domain.AssessmentAttemptID(uuid.New()))); err != nil {
|
||||
t.Fatalf("Handle(unknown attempt) error = %v, want a finished job", err)
|
||||
}
|
||||
if len(unit.repository.reviews) != 0 {
|
||||
t.Fatal("a review was stored for an unknown attempt")
|
||||
}
|
||||
}
|
||||
|
||||
// A job writes the reviews of its attempt and of the matched ended attempts in
|
||||
// ascending attempt order, each under the policy version that attempt is pinned
|
||||
// to, so two concurrent jobs over the same pair take row locks in one order.
|
||||
func TestSignalReviewJobWritesPairsInAscendingOrderUnderTheirOwnPolicies(t *testing.T) {
|
||||
strictSignals := domain.DemoAssessmentSignalPolicy()
|
||||
strictSignals.FastAnswersAttention, strictSignals.FastAnswersReview = 1, 2
|
||||
strict := domain.DemoProductPolicyV3()
|
||||
strict.Assessment.Signals = &strictSignals
|
||||
relaxedSignals := domain.DemoAssessmentSignalPolicy()
|
||||
relaxedSignals.FastAnswersAttention, relaxedSignals.FastAnswersReview = 100, 200
|
||||
relaxed := domain.DemoProductPolicyV3()
|
||||
relaxed.Assessment.Signals = &relaxedSignals
|
||||
strictVersion := signalReviewPolicyVersion(t, 4, strict)
|
||||
relaxedVersion := signalReviewPolicyVersion(t, 5, relaxed)
|
||||
legacyVersion := signalReviewPolicyVersion(t, 2, domain.DemoProductPolicyV2())
|
||||
|
||||
low := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000001"))
|
||||
middle := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000002"))
|
||||
high := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000003"))
|
||||
legacy := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000004"))
|
||||
unit := newSignalUnitFake()
|
||||
unit.policies = policiesFake{versions: map[domain.PolicyVersionID]domain.PolicyVersion{
|
||||
strictVersion.ID(): strictVersion, relaxedVersion.ID(): relaxedVersion, legacyVersion.ID(): legacyVersion,
|
||||
}}
|
||||
unit.repository.subjects = map[domain.AssessmentAttemptID]domain.PolicyVersionID{high: strictVersion.ID()}
|
||||
unit.repository.inputs = outbound.AssessmentReviewInputs{Answers: []domain.AssessmentResponseSample{
|
||||
answerSampleForJob(100), answerSampleForJob(100),
|
||||
}}
|
||||
unit.repository.pairs = map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair{high: {
|
||||
{AttemptID: middle, PolicyVersionID: relaxedVersion.ID(), EvidenceBits: 90},
|
||||
{AttemptID: low, PolicyVersionID: strictVersion.ID(), EvidenceBits: 80},
|
||||
{AttemptID: legacy, PolicyVersionID: legacyVersion.ID(), EvidenceBits: 70},
|
||||
// Below the attention level of the evaluated policy: not refreshed.
|
||||
{AttemptID: domain.AssessmentAttemptID(uuid.New()), PolicyVersionID: strictVersion.ID(), EvidenceBits: 1},
|
||||
}}
|
||||
if err := NewSignalReviewJob(nil).Handle(context.Background(), unit, signalJob(high)); err != nil {
|
||||
t.Fatalf("Handle() error = %v", err)
|
||||
}
|
||||
reviews := unit.repository.reviews
|
||||
if len(reviews) != 3 {
|
||||
t.Fatalf("stored %d reviews, want the attempt, its two matched attempts, and none for a version without a signal section", len(reviews))
|
||||
}
|
||||
if reviews[0].AttemptID != low || reviews[1].AttemptID != middle || reviews[2].AttemptID != high {
|
||||
t.Fatalf("review order = %s %s %s, want ascending attempt IDs", reviews[0].AttemptID, reviews[1].AttemptID, reviews[2].AttemptID)
|
||||
}
|
||||
if reviews[0].Outcome.Band != domain.AssessmentReviewBandReview || reviews[1].Outcome.Band != domain.AssessmentReviewBandNormal ||
|
||||
reviews[1].PolicyVersionID != relaxedVersion.ID() {
|
||||
t.Fatalf("bands = %s/%s, want each attempt judged by its own pinned policy", reviews[0].Outcome.Band, reviews[1].Outcome.Band)
|
||||
}
|
||||
// All locks come first, in ascending order, before any fact is read.
|
||||
wantEvents := []string{"lock:" + low.String(), "lock:" + middle.String(), "lock:" + high.String(), "lock:" + legacy.String()}
|
||||
if len(unit.repository.events) < 5 || !slices.Equal(unit.repository.events[:4], wantEvents) || unit.repository.events[4] != "read" {
|
||||
t.Fatalf("job events = %v, want the four review locks in ascending order before the first read", unit.repository.events)
|
||||
}
|
||||
queried := unit.repository.queries[0]
|
||||
if !queried.EndedOnly || queried.Limit != signalReviewPairLimit || queried.MinBits != strictSignals.DuplicateAttentionBits {
|
||||
t.Fatalf("pair query = %+v, want ended attempts only, bounded, from the attention level", queried)
|
||||
}
|
||||
}
|
||||
|
||||
func answerSampleForJob(elapsed int32) domain.AssessmentResponseSample {
|
||||
return domain.AssessmentResponseSample{AnswerFormat: domain.AnswerFormatInteger, ElapsedMS: elapsed, MeasuredFromAnswer: true}
|
||||
}
|
||||
|
||||
func TestEvaluateReviewTakesTheStrongestPair(t *testing.T) {
|
||||
version := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
repository := &signalRepositoryFake{pairs: map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair{}}
|
||||
attemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
repository.pairs[attemptID] = []outbound.AssessmentDuplicatePair{
|
||||
{AttemptID: domain.AssessmentAttemptID(uuid.New()), EvidenceBits: 66, IntegerItems: 8, SequenceItems: 1},
|
||||
{AttemptID: domain.AssessmentAttemptID(uuid.New()), EvidenceBits: 20, IntegerItems: 3},
|
||||
}
|
||||
if err := evaluateReview(context.Background(), repository, attemptID, version, signalReviewTestTime); err != nil {
|
||||
t.Fatalf("evaluateReview() error = %v", err)
|
||||
}
|
||||
review := repository.reviews[0]
|
||||
if review.Measures.DuplicateEvidenceBits != 66 || review.Measures.MatchedIntegerItems != 8 || review.Measures.MatchedSequenceItems != 1 ||
|
||||
review.Outcome.Band != domain.AssessmentReviewBandReview {
|
||||
t.Fatalf("review = %+v, want the strongest pair and the review band", review)
|
||||
}
|
||||
if query := repository.queries[0]; query.Limit != 1 || query.MinBits != 0 || query.EndedOnly {
|
||||
t.Fatalf("pair query = %+v, want the single strongest pair among all attempts", query)
|
||||
}
|
||||
}
|
||||
|
||||
// The duplicate thresholds are sums of bits over one pair of attempts, and a
|
||||
// matched answer carries -log2 of the share of attempts that hold its value. The
|
||||
// test measures, for the four demo families, how likely two independent
|
||||
// candidates are to give the same correct answer and which values they share,
|
||||
// and from that computes the probability that one pair of honest candidates
|
||||
// reaches each threshold on a 23-item attempt. Since an attempt is compared with
|
||||
// every other one, the per-attempt rate is that probability times the number of
|
||||
// rivals. The measurement covers four AI-drafted families; it is not a
|
||||
// calibration, and a real bank needs its own run.
|
||||
func TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow(t *testing.T) {
|
||||
const (
|
||||
seedsPerFamily = 4000
|
||||
rivals = 1e4
|
||||
items = 23
|
||||
// Targets for one honest attempt facing all rivals.
|
||||
attentionTarget = 1e-3
|
||||
reviewTarget = 1e-8
|
||||
)
|
||||
policy := domain.DemoAssessmentSignalPolicy()
|
||||
type outcome struct {
|
||||
probability float64
|
||||
bits int
|
||||
}
|
||||
families := signalReviewDemoFamilies(t)
|
||||
perFamily := make([][]outcome, 0, len(families))
|
||||
for _, family := range families {
|
||||
counts := map[string]int{}
|
||||
var format string
|
||||
for seed := 1; seed <= seedsPerFamily; seed++ {
|
||||
variant, err := family.NewVariant(domain.VariantSeed(seed))
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant(%d) error = %v", seed, err)
|
||||
}
|
||||
counts[variant.ReferenceAnswer]++
|
||||
format = variant.AnswerFormat
|
||||
}
|
||||
capBits := float64(policy.DuplicateIntegerCapBits)
|
||||
if format == domain.AnswerFormatIntegerSequence {
|
||||
capBits = float64(policy.DuplicateSequenceCapBits)
|
||||
}
|
||||
matched := 0.0
|
||||
outcomes := make([]outcome, 0, len(counts)+1)
|
||||
for _, count := range counts {
|
||||
share := float64(count) / seedsPerFamily
|
||||
// Rounded up, so the computed probability is not understated.
|
||||
bits := int(math.Ceil(math.Min(capBits, -math.Log2(share))))
|
||||
outcomes = append(outcomes, outcome{probability: share * share, bits: bits})
|
||||
matched += share * share
|
||||
}
|
||||
perFamily = append(perFamily, append(outcomes, outcome{probability: 1 - matched}))
|
||||
}
|
||||
tail := func(threshold int) float64 {
|
||||
distribution := make([]float64, threshold+1)
|
||||
distribution[0] = 1
|
||||
for item := range items {
|
||||
next := make([]float64, threshold+1)
|
||||
for sum, mass := range distribution {
|
||||
if mass == 0 {
|
||||
continue
|
||||
}
|
||||
for _, entry := range perFamily[item%len(perFamily)] {
|
||||
next[min(sum+entry.bits, threshold)] += mass * entry.probability
|
||||
}
|
||||
}
|
||||
distribution = next
|
||||
}
|
||||
return distribution[threshold]
|
||||
}
|
||||
attention := tail(int(policy.DuplicateAttentionBits)) * rivals
|
||||
review := tail(int(policy.DuplicateReviewBits)) * rivals
|
||||
t.Logf("per-attempt false flag rate against %.0f rivals: attention %.3g, review %.3g", rivals, attention, review)
|
||||
if attention > attentionTarget || review > reviewTarget {
|
||||
t.Fatalf("per-attempt false flag rate attention %.3g (target %.0e), review %.3g (target %.0e)", attention, attentionTarget, review, reviewTarget)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignalLogsAndErrorsCarryNoAnswerOrAddress(t *testing.T) {
|
||||
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
updated, item := signalReviewFirstAnswer(t, attempt, signalReviewTestTime.Add(time.Second))
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
// An observation for an item the attempt does not hold is refused with an
|
||||
// error that names neither the answer nor the origin.
|
||||
err = observer.observeAnswer(context.Background(), newSignalUnitFake(), attempt, updated, uuid.New(), RequestOrigin{SessionID: uuid.New(), ClientKey: "203.0.113.9"})
|
||||
if err == nil {
|
||||
t.Fatal("observeAnswer(foreign item) succeeded")
|
||||
}
|
||||
for _, secret := range []string{"424242", "203.0.113.9", string(item.Answer)} {
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("error text contains %q: %v", secret, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// copiedPairEvidence is the evidence of a pair that copies every answer of an
|
||||
// attempt of the given length in a population of the given number of answers
|
||||
// per family: each shared value is held by the two copiers only, so a matched
|
||||
// answer carries log2(population / 2) bits up to the cap of its format. The
|
||||
// items follow the demo bank: three integer families for one order family.
|
||||
func copiedPairEvidence(policy domain.AssessmentSignalPolicy, items, population int) float64 {
|
||||
bits := math.Log2(float64(population) / 2)
|
||||
total := 0.0
|
||||
for item := range items {
|
||||
capBits := float64(policy.DuplicateIntegerCapBits)
|
||||
if item%4 == 1 {
|
||||
capBits = float64(policy.DuplicateSequenceCapBits)
|
||||
}
|
||||
total += math.Min(capBits, bits)
|
||||
}
|
||||
return math.Floor(total)
|
||||
}
|
||||
|
||||
// The demo thresholds are tuned against ten thousand rivals, so a copied pair
|
||||
// is only flagged once enough attempts exist for its shared values to be rare.
|
||||
// This test calculates how many answers per family that takes, so the figure in
|
||||
// the documentation is not an estimate; to try the feature on a small stand,
|
||||
// publish a policy with lower thresholds instead of changing the demo values.
|
||||
func TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged(t *testing.T) {
|
||||
policy := domain.DemoAssessmentSignalPolicy()
|
||||
needed := func(items int, threshold int32) int {
|
||||
for population := 2; population <= 1<<20; population++ {
|
||||
if copiedPairEvidence(policy, items, population) >= float64(threshold) {
|
||||
return population
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
for _, test := range []struct {
|
||||
items int
|
||||
wantAttention, wantReview int
|
||||
}{
|
||||
{items: 13, wantAttention: 26, wantReview: 61},
|
||||
{items: 23, wantAttention: 9, wantReview: 14},
|
||||
} {
|
||||
attention := needed(test.items, policy.DuplicateAttentionBits)
|
||||
review := needed(test.items, policy.DuplicateReviewBits)
|
||||
t.Logf("%d items: a copied pair reaches attention from %d answers per family and review from %d", test.items, attention, review)
|
||||
if attention != test.wantAttention || review != test.wantReview {
|
||||
t.Errorf("%d items: attention at %d and review at %d answers per family, want %d and %d", test.items, attention, review, test.wantAttention, test.wantReview)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user