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