feat(assessment): add the review band of attempt signals and the disclosed collector

This commit is contained in:
shira committed 2026-10-08 23:04:57 +03:00
1 parent 68286af8b7
commit b3c6dc870b
124 files changed
+13522 -633

No files matched your search

@@ -0,0 +1,137 @@
package domain
// AssessmentSignalPolicy holds the versioned thresholds that turn the server
// observations of an attempt into a review band. The band is a hint for a
// manual check: it never changes a result, a category, or a quota. The section
// is optional; a policy version without it makes no band, and an absent
// section never acquires defaults.
//
// Counts are numbers of items or events, durations carry their unit in the
// field name, and the duplicate thresholds are evidence bits: a matched answer
// adds the number of bits that the policy assumes for its format, and a pair of
// candidates that coincides by chance reaches N bits with a probability of
// about 2^-N when every matched answer is independent.
type AssessmentSignalPolicy struct {
// FastFloorIntegerMS and FastFloorSequenceMS are the shortest server time
// from the previous answer or session start to the answer that is still
// plausible for the answer format. A shorter time is a fast answer.
FastFloorIntegerMS int32
FastFloorSequenceMS int32
// FastAnswersAttention and FastAnswersReview are the numbers of fast
// answers that raise the band.
FastAnswersAttention int32
FastAnswersReview int32
// DeviationRatio is the factor by which an answer time may differ from the
// median answer time of the same attempt, in both directions, before it is
// an anomalous deviation. 50000 means five times. It applies only to an
// attempt with at least DeviationMinAnswers answers.
DeviationRatio BasisPoints
DeviationMinAnswers int32
DeviatingAnswersAttention int32
DeviatingAnswersReview int32
ParallelAlternationsAttention int32
ParallelAlternationsReview int32
// ExtraNetworks counts the distinct client networks of the attempt beyond
// the first. Going from one network to another and back adds one, however
// often it happens.
ExtraNetworksAttention int32
ExtraNetworksReview int32
// A matched answer carries -log2 of the share of attempts that hold the
// same fingerprint for the family version, so a popular value, such as the
// correct answer of a variant, carries little. DuplicateIntegerCapBits and
// DuplicateSequenceCapBits cap what one answer of the format can carry; an
// integer answer has a small answer space and is capped lower. The bits of
// the matched answers of one pair of attempts add up, and the highest pair
// decides: an attempt is compared with every other one, not with the whole
// population at once.
DuplicateIntegerCapBits int32
DuplicateSequenceCapBits int32
DuplicateAttentionBits int32
DuplicateReviewBits int32
// The client thresholds can raise a normal band to attention only, because
// a browser reports them and anyone can forge or suppress them.
ClientFocusLossAttentionMS int32
ClientClipboardEventsAttention int32
ClientFullscreenExitsAttention int32
}
// Sanity bounds of the signal section. They reject a value in the wrong unit;
// the demo values themselves are recorded in DemoAssessmentSignalPolicy.
const (
minSignalFloorMS = 1000
maxSignalFloorMS = 10 * 60 * 1000
maxSignalCount = 1000
minSignalDeviationRatio = BasisPoints(20000)
maxSignalDeviationRatio = BasisPoints(1000000)
minSignalDeviationAnswers = 3
maxSignalDeviationAnswers = maxAssessmentAttemptItems
maxSignalEvidenceBits = 64
maxSignalThresholdBits = 4096
minSignalClientFocusLossMS = 1000
maxSignalClientFocusLossMS = 24 * 60 * 60 * 1000
)
// DemoAssessmentSignalPolicy returns the initial thresholds. They are agreed
// starting values for verifying the flow, not measured results: no study of
// real candidates supports them, and a calibrated policy must replace them.
func DemoAssessmentSignalPolicy() AssessmentSignalPolicy {
return AssessmentSignalPolicy{
FastFloorIntegerMS: 5000,
FastFloorSequenceMS: 8000,
FastAnswersAttention: 3,
FastAnswersReview: 6,
DeviationRatio: 50000,
DeviationMinAnswers: 5,
DeviatingAnswersAttention: 3,
DeviatingAnswersReview: 6,
ParallelAlternationsAttention: 2,
ParallelAlternationsReview: 6,
ExtraNetworksAttention: 2, ExtraNetworksReview: 5,
DuplicateIntegerCapBits: 8, DuplicateSequenceCapBits: 12,
DuplicateAttentionBits: 48,
DuplicateReviewBits: 64,
ClientFocusLossAttentionMS: 120000,
ClientClipboardEventsAttention: 3,
ClientFullscreenExitsAttention: 3,
}
}
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy AssessmentSignalPolicy) Validate() error {
const location = "AssessmentSignalPolicy.Validate"
if err := firstError(
checkRange(location, "assessment.signals.fast_floor_integer_ms", policy.FastFloorIntegerMS, minSignalFloorMS, maxSignalFloorMS),
checkRange(location, "assessment.signals.fast_floor_sequence_ms", policy.FastFloorSequenceMS, minSignalFloorMS, maxSignalFloorMS),
checkRange(location, "assessment.signals.deviation_ratio_bp", policy.DeviationRatio, minSignalDeviationRatio, maxSignalDeviationRatio),
checkRange(location, "assessment.signals.deviation_min_answers", policy.DeviationMinAnswers, minSignalDeviationAnswers, maxSignalDeviationAnswers),
checkRange(location, "assessment.signals.duplicate_integer_cap_bits", policy.DuplicateIntegerCapBits, 1, maxSignalEvidenceBits),
checkRange(location, "assessment.signals.duplicate_sequence_cap_bits", policy.DuplicateSequenceCapBits, 1, maxSignalEvidenceBits),
checkRange(location, "assessment.signals.client_focus_loss_attention_ms", policy.ClientFocusLossAttentionMS, minSignalClientFocusLossMS, maxSignalClientFocusLossMS),
checkRange(location, "assessment.signals.client_clipboard_events_attention", policy.ClientClipboardEventsAttention, 1, maxSignalCount),
checkRange(location, "assessment.signals.client_fullscreen_exits_attention", policy.ClientFullscreenExitsAttention, 1, maxSignalCount),
); err != nil {
return err
}
for _, pair := range []struct {
field string
attention, review int32
maximum int32
}{
{"fast_answers", policy.FastAnswersAttention, policy.FastAnswersReview, maxSignalCount},
{"deviating_answers", policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview, maxSignalCount},
{"parallel_alternations", policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview, maxSignalCount},
{"extra_networks", policy.ExtraNetworksAttention, policy.ExtraNetworksReview, maxSignalCount},
{"duplicate_bits", policy.DuplicateAttentionBits, policy.DuplicateReviewBits, maxSignalThresholdBits},
} {
if err := checkRange(location, "assessment.signals."+pair.field+"_attention", pair.attention, 1, pair.maximum); err != nil {
return err
}
if err := checkRange(location, "assessment.signals."+pair.field+"_review", pair.review, pair.attention, pair.maximum); err != nil {
return err
}
}
return nil
}
@@ -0,0 +1,80 @@
package domain
import (
"errors"
"testing"
)
func TestDemoSignalPolicyIsValidAndRoundTripsThroughTheDocument(t *testing.T) {
policy := DemoProductPolicyV3()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV3().Validate() error = %v", err)
}
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Assessment.Signals == nil || *decoded.Assessment.Signals != DemoAssessmentSignalPolicy() {
t.Fatalf("decoded signals = %+v, want the demo values", decoded.Assessment.Signals)
}
if DemoProductPolicyV2().Assessment.Signals != nil {
t.Fatal("DemoProductPolicyV2 gained a signal section; a stored version must not change")
}
}
func TestSignalSectionAloneIsASchemaTwoExtensionAndNeverAcquiresDefaults(t *testing.T) {
signals := DemoAssessmentSignalPolicy()
policy := DemoProductPolicyV1()
policy.Assessment.Signals = &signals
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil || decoded.Assessment.Signals == nil || decoded.Assessment.Attempt != nil || decoded.Support != nil {
t.Fatalf("decode signals-only schema 2 = %+v, error %v", decoded.Assessment, err)
}
legacy := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
policySection(t, document, "assessment")["signals"] = nil
})
if _, err := decodeProductPolicy(legacy); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 1 with a signals key) error = %v, want ErrInvalidPolicy", err)
}
missingField := editPolicySchemaDocument(t, encoded, func(document map[string]any) {
delete(policySection(t, policySection(t, document, "assessment"), "signals"), "fast_floor_integer_ms")
})
if _, err := decodeProductPolicy(missingField); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(missing signal field) error = %v, want ErrInvalidPolicy", err)
}
}
func TestSignalPolicyRejectsOutOfRangeAndInconsistentValues(t *testing.T) {
tests := []struct {
name string
change func(*AssessmentSignalPolicy)
}{
{"zero section", func(policy *AssessmentSignalPolicy) { *policy = AssessmentSignalPolicy{} }},
{"floor in seconds instead of milliseconds", func(policy *AssessmentSignalPolicy) { policy.FastFloorIntegerMS = 5 }},
{"review below attention", func(policy *AssessmentSignalPolicy) { policy.FastAnswersReview = policy.FastAnswersAttention - 1 }},
{"duplicate review below attention", func(policy *AssessmentSignalPolicy) { policy.DuplicateReviewBits = policy.DuplicateAttentionBits - 1 }},
{"deviation ratio below two", func(policy *AssessmentSignalPolicy) { policy.DeviationRatio = 15000 }},
{"deviation needs several answers", func(policy *AssessmentSignalPolicy) { policy.DeviationMinAnswers = 2 }},
{"evidence bits beyond a hash", func(policy *AssessmentSignalPolicy) { policy.DuplicateSequenceCapBits = 65 }},
{"client threshold zero", func(policy *AssessmentSignalPolicy) { policy.ClientClipboardEventsAttention = 0 }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
test.change(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
@@ -0,0 +1,387 @@
package domain
import (
"crypto/sha256"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
)
// ErrInvalidAssessmentReview reports a malformed server observation or review.
// Its text never includes an answer, an address, or a session identifier.
var ErrInvalidAssessmentReview = errors.New("invalid assessment review")
// AssessmentReviewBand is the manual-check hint of one attempt. It is stored
// for an operator only. It has no effect on the result, the category, or a
// quota, and no candidate or employer read carries it.
type AssessmentReviewBand string
const (
AssessmentReviewBandNormal AssessmentReviewBand = "normal"
AssessmentReviewBandAttention AssessmentReviewBand = "attention"
AssessmentReviewBandReview AssessmentReviewBand = "review"
)
func (band AssessmentReviewBand) rank() int {
switch band {
case AssessmentReviewBandNormal:
return 0
case AssessmentReviewBandAttention:
return 1
case AssessmentReviewBandReview:
return 2
default:
return -1
}
}
// IsKnown reports whether the band is one of the three stored values.
func (band AssessmentReviewBand) IsKnown() bool { return band.rank() >= 0 }
// AssessmentReviewReason names a signal group that raised the band.
type AssessmentReviewReason string
const (
AssessmentReviewReasonFastAnswers AssessmentReviewReason = "fast_answers"
AssessmentReviewReasonDeviatingAnswers AssessmentReviewReason = "deviating_answers"
AssessmentReviewReasonParallelSessions AssessmentReviewReason = "parallel_sessions"
AssessmentReviewReasonExtraNetworks AssessmentReviewReason = "extra_networks"
AssessmentReviewReasonDuplicateAnswers AssessmentReviewReason = "duplicate_answers"
AssessmentReviewReasonClientSignals AssessmentReviewReason = "client_signals"
)
// IsKnown reports whether the reason is a stored value.
func (reason AssessmentReviewReason) IsKnown() bool {
switch reason {
case AssessmentReviewReasonFastAnswers, AssessmentReviewReasonDeviatingAnswers,
AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks,
AssessmentReviewReasonDuplicateAnswers, AssessmentReviewReasonClientSignals:
return true
default:
return false
}
}
// AssessmentDigest is a keyed 32-byte digest. It stands for an answer, a
// session, or a network address without carrying any of them.
type AssessmentDigest [sha256.Size]byte
// IsZero reports an unset digest.
func (digest AssessmentDigest) IsZero() bool { return digest == AssessmentDigest{} }
// AssessmentAnswerObservation is the server-side record of one accepted
// answer: how long it took, and a keyed fingerprint of the normalized answer
// that allows comparing answers of different candidates without storing them.
type AssessmentAnswerObservation struct {
AttemptID AssessmentAttemptID
UserID uuid.UUID
ItemInstanceID uuid.UUID
FamilyID AssessmentFamilyID
FamilyVersion int32
Seed VariantSeed
AnswerFormat string
Fingerprint AssessmentDigest
// KeyVersion names the key generation of Fingerprint, so a rotation is
// explicit and fingerprints of different generations are never compared.
KeyVersion int16
ElapsedMS int32
// MeasuredFromAnswer is true when ElapsedMS starts at the previous answer,
// which is when this item was shown. The first item of a work session starts
// at the session start, which is only an upper bound of the time the item
// was on screen, so such a time is not used for the speed signals.
MeasuredFromAnswer bool
ObservedAt time.Time
}
// Validate checks that the observation can be stored.
func (observation AssessmentAnswerObservation) Validate() error {
const location = "AssessmentAnswerObservation.Validate"
switch {
case observation.AttemptID.IsZero(), observation.UserID == uuid.Nil, observation.ItemInstanceID == uuid.Nil,
uuid.UUID(observation.FamilyID) == uuid.Nil, observation.FamilyVersion < 1:
return fmt.Errorf("%s - identifiers are required: %w", location, ErrInvalidAssessmentReview)
case observation.AnswerFormat != AnswerFormatInteger && observation.AnswerFormat != AnswerFormatIntegerSequence:
return fmt.Errorf("%s - answer format is unsupported: %w", location, ErrInvalidAssessmentReview)
case observation.Fingerprint.IsZero(), observation.KeyVersion < 1:
return fmt.Errorf("%s - fingerprint and its key version are required: %w", location, ErrInvalidAssessmentReview)
case observation.ElapsedMS < 0, observation.ObservedAt.IsZero():
return fmt.Errorf("%s - elapsed time and observation time are required: %w", location, ErrInvalidAssessmentReview)
}
return nil
}
// AssessmentOriginSource says which request produced an origin mark.
type AssessmentOriginSource string
const (
AssessmentOriginAnswer AssessmentOriginSource = "answer"
AssessmentOriginSignals AssessmentOriginSource = "signals"
)
// AssessmentOriginMark records, for one accepted request, keyed digests of the
// authenticated session and of the client network. The digests are bound to
// the attempt, so they cannot be correlated between attempts, and they are
// useless without the server secret. NetworkDigest is absent when the client
// address could not be resolved.
type AssessmentOriginMark struct {
ID uuid.UUID
AttemptID AssessmentAttemptID
Source AssessmentOriginSource
ObservedAt time.Time
SessionDigest AssessmentDigest
NetworkDigest AssessmentDigest
KeyVersion int16
}
// Validate checks that the mark can be stored.
func (mark AssessmentOriginMark) Validate() error {
const location = "AssessmentOriginMark.Validate"
if mark.ID == uuid.Nil || mark.AttemptID.IsZero() || mark.ObservedAt.IsZero() || mark.SessionDigest.IsZero() || mark.KeyVersion < 1 {
return fmt.Errorf("%s - identifiers, time, session digest, and key version are required: %w", location, ErrInvalidAssessmentReview)
}
if mark.Source != AssessmentOriginAnswer && mark.Source != AssessmentOriginSignals {
return fmt.Errorf("%s - source is unknown: %w", location, ErrInvalidAssessmentReview)
}
return nil
}
// AssessmentResponseSample is the server time of one answer.
type AssessmentResponseSample struct {
AnswerFormat string
ElapsedMS int32
MeasuredFromAnswer bool
}
// AssessmentResponseTimes counts the answers and the answers that the policy
// calls fast or anomalously fast. Only server time is used: the client may
// report durations of its own, but they never replace it.
type AssessmentResponseTimes struct {
Answered int32
Fast int32
Deviating int32
}
// ClassifyResponseTimes applies the fast floors and the median deviation of
// the policy. Only answers measured from the previous answer count. The
// deviation is computed within one answer format, so a slow format does not
// make a quick one look anomalous, and only on the fast side: a slow answer is
// not suspicious by itself. One answer contributes to at most one counter: an
// answer under its floor is fast and is not counted again as a deviation.
func (policy AssessmentSignalPolicy) ClassifyResponseTimes(samples []AssessmentResponseSample) AssessmentResponseTimes {
result := AssessmentResponseTimes{Answered: int32(min(len(samples), maxAssessmentAttemptItems))}
byFormat := map[string][]int64{}
for _, sample := range samples {
if !sample.MeasuredFromAnswer {
continue
}
floor := policy.fastFloor(sample.AnswerFormat)
if sample.ElapsedMS < floor {
result.Fast++
// Kept for the median, but marked so it is not a deviation too.
byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], -int64(sample.ElapsedMS)-1)
continue
}
byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], int64(sample.ElapsedMS))
}
ratio := int64(policy.DeviationRatio)
for _, marked := range byFormat {
if len(marked) < int(policy.DeviationMinAnswers) {
continue
}
elapsed := make([]int64, len(marked))
for index, value := range marked {
elapsed[index] = value
if value < 0 {
elapsed[index] = -value - 1
}
}
slices.Sort(elapsed)
median := elapsed[len(elapsed)/2]
if len(elapsed)%2 == 0 {
median = (elapsed[len(elapsed)/2-1] + elapsed[len(elapsed)/2]) / 2
}
median = max(median, 1)
for _, value := range marked {
// value is more than ratio times below the median, in basis points.
if value >= 0 && max(value, 1)*ratio < median*int64(basisPointsPerUnit) {
result.Deviating++
}
}
}
return result
}
func (policy AssessmentSignalPolicy) fastFloor(format string) int32 {
if format == AnswerFormatIntegerSequence {
return policy.FastFloorSequenceMS
}
return policy.FastFloorIntegerMS
}
// AssessmentOriginAnomalies counts the origin changes of an attempt.
type AssessmentOriginAnomalies struct {
// ParallelAlternations counts requests that came back to an earlier
// session after another session had been used, as when two logged-in
// sessions work on one attempt in turn. A single move from one session to
// another is not counted.
ParallelAlternations int32
// ExtraNetworks counts the distinct network digests beyond the first. A
// move to another network and back is one extra network.
ExtraNetworks int32
}
// CountOriginAnomalies orders the marks by time and then by ID and counts
// alternations between sessions and distinct client networks.
func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalies {
ordered := slices.Clone(marks)
slices.SortStableFunc(ordered, func(left, right AssessmentOriginMark) int {
if byTime := left.ObservedAt.Compare(right.ObservedAt); byTime != 0 {
return byTime
}
return slices.Compare(left.ID[:], right.ID[:])
})
var anomalies AssessmentOriginAnomalies
seenSessions := map[AssessmentDigest]struct{}{}
networks := map[AssessmentDigest]struct{}{}
var previousSession AssessmentDigest
for _, mark := range ordered {
_, seen := seenSessions[mark.SessionDigest]
if seen && mark.SessionDigest != previousSession {
anomalies.ParallelAlternations++
}
seenSessions[mark.SessionDigest] = struct{}{}
previousSession = mark.SessionDigest
if !mark.NetworkDigest.IsZero() {
networks[mark.NetworkDigest] = struct{}{}
}
}
anomalies.ExtraNetworks = int32(max(len(networks)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list.
return anomalies
}
// AssessmentReviewMeasures is everything the band is computed from. Every
// field is a count or a duration; none of them holds an answer or an address.
// The duplicate fields describe the pair of attempts with the most evidence.
type AssessmentReviewMeasures struct {
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMS int64
ClientClipboardEvents int32
ClientFullscreenExits int32
}
// AssessmentReviewOutcome is the computed band with the groups behind it.
type AssessmentReviewOutcome struct {
Band AssessmentReviewBand
Reasons []AssessmentReviewReason
}
// Evaluate computes the band. Server signals decide it. Parallel sessions and
// extra networks are weak and correlated (a phone and a laptop produce both), so
// they are one group: alone it reaches attention at most, and review only
// together with a strong signal (fast answers, deviating answers, or duplicate
// answers) at attention or above. Client signals can only raise a normal band
// to attention, because a browser reports them.
func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures) AssessmentReviewOutcome {
type signal struct {
reason AssessmentReviewReason
band AssessmentReviewBand
weak bool
}
signals := []signal{
{AssessmentReviewReasonFastAnswers, signalLevel(measures.FastAnswers, policy.FastAnswersAttention, policy.FastAnswersReview), false},
{AssessmentReviewReasonDeviatingAnswers, signalLevel(measures.DeviatingAnswers, policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview), false},
{AssessmentReviewReasonParallelSessions, signalLevel(measures.ParallelAlternations, policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview), true},
{AssessmentReviewReasonExtraNetworks, signalLevel(measures.ExtraNetworks, policy.ExtraNetworksAttention, policy.ExtraNetworksReview), true},
{AssessmentReviewReasonDuplicateAnswers, signalLevel(measures.DuplicateEvidenceBits, policy.DuplicateAttentionBits, policy.DuplicateReviewBits), false},
}
strongRaised := false
for _, entry := range signals {
if !entry.weak && entry.band.rank() > 0 {
strongRaised = true
}
}
outcome := AssessmentReviewOutcome{Band: AssessmentReviewBandNormal}
for _, entry := range signals {
band := entry.band
if entry.weak && band == AssessmentReviewBandReview && !strongRaised {
band = AssessmentReviewBandAttention
}
if band.rank() == 0 {
continue
}
outcome.Reasons = append(outcome.Reasons, entry.reason)
if band.rank() > outcome.Band.rank() {
outcome.Band = band
}
}
if measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) ||
measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention ||
measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention {
outcome.Reasons = append(outcome.Reasons, AssessmentReviewReasonClientSignals)
if outcome.Band == AssessmentReviewBandNormal {
outcome.Band = AssessmentReviewBandAttention
}
}
return outcome
}
func signalLevel(value, attention, review int32) AssessmentReviewBand {
switch {
case value >= review:
return AssessmentReviewBandReview
case value >= attention:
return AssessmentReviewBandAttention
default:
return AssessmentReviewBandNormal
}
}
// AssessmentAttemptReview is the stored review of an attempt. PolicyVersionID
// pins the policy version that computed it, which is the version the attempt
// itself is pinned to.
type AssessmentAttemptReview struct {
AttemptID AssessmentAttemptID
PolicyVersionID PolicyVersionID
PolicyVersion int32
Measures AssessmentReviewMeasures
Outcome AssessmentReviewOutcome
EvaluatedAt time.Time
UpdatedAt time.Time
}
// Validate checks that the review can be stored.
func (review AssessmentAttemptReview) Validate() error {
const location = "AssessmentAttemptReview.Validate"
if review.AttemptID.IsZero() || review.PolicyVersionID.IsZero() || !review.Outcome.Band.IsKnown() ||
review.EvaluatedAt.IsZero() || review.UpdatedAt.IsZero() {
return fmt.Errorf("%s - attempt, policy, band, and times are required: %w", location, ErrInvalidAssessmentReview)
}
for _, reason := range review.Outcome.Reasons {
if !reason.IsKnown() {
return fmt.Errorf("%s - reason is unknown: %w", location, ErrInvalidAssessmentReview)
}
}
return nil
}
// AssessmentReviewActor is the audit handle of an operator who reads a
// review, written as operator:<handle>. It is not authentication.
type AssessmentReviewActor string
// ParseAssessmentReviewActor accepts operator:<handle>.
func ParseAssessmentReviewActor(value string) (AssessmentReviewActor, error) {
if len(value) > 128 || !assessmentOperatorPattern.MatchString(value) {
return "", fmt.Errorf("domain.ParseAssessmentReviewActor - actor must be operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-': %w", ErrInvalidAssessmentReview)
}
return AssessmentReviewActor(value), nil
}
@@ -0,0 +1,167 @@
package domain
import (
"slices"
"testing"
"time"
"github.com/google/uuid"
)
func answerSample(format string, elapsedMS int32, fromAnswer bool) AssessmentResponseSample {
return AssessmentResponseSample{AnswerFormat: format, ElapsedMS: elapsedMS, MeasuredFromAnswer: fromAnswer}
}
func TestClassifyResponseTimesUsesFloorsPerFormat(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
samples := []AssessmentResponseSample{
answerSample(AnswerFormatInteger, 4999, true),
answerSample(AnswerFormatInteger, 5000, true),
answerSample(AnswerFormatIntegerSequence, 7999, true),
answerSample(AnswerFormatIntegerSequence, 8000, true),
// The first item of a work session is measured from the session start,
// when the item was not necessarily on screen, so it is not counted.
answerSample(AnswerFormatInteger, 10, false),
}
got := policy.ClassifyResponseTimes(samples)
if got.Answered != 5 || got.Fast != 2 || got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(floors) = %+v, want 5 answers, 2 fast, and no deviation below the minimum count", got)
}
}
func TestClassifyResponseTimesDeviatesOnTheFastSideWithinOneFormat(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
steady := func(count int, elapsed int32) []AssessmentResponseSample {
samples := make([]AssessmentResponseSample, 0, count+1)
for range count {
samples = append(samples, answerSample(AnswerFormatInteger, elapsed, true))
}
return samples
}
if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 11999, true))); got.Deviating != 1 || got.Fast != 0 {
t.Fatalf("ClassifyResponseTimes(fast outlier) = %+v, want one deviation below a fifth of the median", got)
}
if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 12001, true))); got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(inside the ratio) = %+v, want no deviation", got)
}
if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 900000, true))); got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(slow outlier) = %+v, want no deviation: a slow answer is not suspicious", got)
}
// Another format has its own median and its own minimum count: five slow
// orders do not make a quick integer answer deviate, and the integer
// answers alone are too few.
mixed := append(steady(3, 60000), answerSample(AnswerFormatIntegerSequence, 70000, true), answerSample(AnswerFormatIntegerSequence, 70000, true))
mixed = append(mixed, answerSample(AnswerFormatInteger, 9000, true))
if got := policy.ClassifyResponseTimes(mixed); got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(mixed formats) = %+v, want no deviation: each format has fewer than %d answers", got, policy.DeviationMinAnswers)
}
// Answers measured from a session start are left out of the median too.
withStart := append(steady(5, 60000), answerSample(AnswerFormatInteger, 60000, false), answerSample(AnswerFormatInteger, 1, false))
if got := policy.ClassifyResponseTimes(withStart); got.Deviating != 0 || got.Fast != 0 {
t.Fatalf("ClassifyResponseTimes(session start items) = %+v, want them excluded", got)
}
}
func TestClassifyResponseTimesCountsAnAnswerOnce(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
samples := make([]AssessmentResponseSample, 0, 7)
for range 6 {
samples = append(samples, answerSample(AnswerFormatInteger, 60000, true))
}
// Under the floor and far below the median: fast, and not a deviation too.
samples = append(samples, answerSample(AnswerFormatInteger, 1000, true))
got := policy.ClassifyResponseTimes(samples)
if got.Fast != 1 || got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes() = %+v, want the answer counted as fast only", got)
}
}
func originMark(second int, session, network byte) AssessmentOriginMark {
mark := AssessmentOriginMark{
ID: uuid.New(), AttemptID: AssessmentAttemptID(uuid.New()), Source: AssessmentOriginAnswer,
ObservedAt: time.Date(2026, time.October, 1, 12, 0, second, 0, time.UTC),
SessionDigest: AssessmentDigest{session}, KeyVersion: 1,
}
if network != 0 {
mark.NetworkDigest = AssessmentDigest{network}
}
return mark
}
func TestCountOriginAnomalies(t *testing.T) {
tests := []struct {
name string
marks []AssessmentOriginMark
want AssessmentOriginAnomalies
}{
{"one session and one network", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 1), originMark(3, 1, 1)}, AssessmentOriginAnomalies{}},
{"moving once to another session is not parallel", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 2, 1), originMark(3, 2, 1)}, AssessmentOriginAnomalies{}},
{"turns between two sessions", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 2, 1), originMark(3, 1, 1), originMark(4, 2, 1)}, AssessmentOriginAnomalies{ParallelAlternations: 2}},
{"unknown addresses are skipped and a return is not a new network", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 0), originMark(3, 1, 2), originMark(4, 1, 2), originMark(5, 1, 1)}, AssessmentOriginAnomalies{ExtraNetworks: 1}},
{"three networks", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 2), originMark(3, 1, 3), originMark(4, 1, 1)}, AssessmentOriginAnomalies{ExtraNetworks: 2}},
{"order follows time and not the slice", []AssessmentOriginMark{originMark(4, 2, 1), originMark(1, 1, 1), originMark(3, 1, 1), originMark(2, 2, 1)}, AssessmentOriginAnomalies{ParallelAlternations: 2}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := CountOriginAnomalies(test.marks); got != test.want {
t.Fatalf("CountOriginAnomalies() = %+v, want %+v", got, test.want)
}
})
}
}
func TestEvaluateBandFollowsThePolicyAndClientSignalsOnlyRaiseToAttention(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
tests := []struct {
name string
measures AssessmentReviewMeasures
wantBand AssessmentReviewBand
wantReasons []AssessmentReviewReason
}{
{"nothing observed", AssessmentReviewMeasures{AnsweredItems: 8}, AssessmentReviewBandNormal, nil},
{"fast answers reach attention", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers}},
{"fast answers reach review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersReview}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers}},
{"a weak signal alone stops at attention", AssessmentReviewMeasures{ExtraNetworks: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraNetworks}},
{"parallel sessions alone stop at attention", AssessmentReviewMeasures{ParallelAlternations: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions}},
{"two weak signals do not lift each other", AssessmentReviewMeasures{ParallelAlternations: 50, ExtraNetworks: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks}},
{"a weak signal reaches review beside a server signal", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ExtraNetworks: 50}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonExtraNetworks}},
{"less duplicate evidence than the attention level is no flag", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateAttentionBits - 1}, AssessmentReviewBandNormal, nil},
{"duplicate evidence at the attention level", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateAttentionBits}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonDuplicateAnswers}},
{"duplicate evidence at the review level", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateReviewBits}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonDuplicateAnswers}},
{"client signals alone raise a normal band to attention", AssessmentReviewMeasures{ClientFocusLossMS: int64(policy.ClientFocusLossAttentionMS)}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"client signals never raise attention to review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ClientClipboardEvents: 1000, ClientFullscreenExits: 1000, ClientFocusLossMS: 1 << 40}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonClientSignals}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := policy.Evaluate(test.measures)
if got.Band != test.wantBand || !slices.Equal(got.Reasons, test.wantReasons) {
t.Fatalf("Evaluate() = %+v, want band %s reasons %v", got, test.wantBand, test.wantReasons)
}
})
}
}
func TestEvaluateUsesTheThresholdsOfTheGivenPolicy(t *testing.T) {
measures := AssessmentReviewMeasures{FastAnswers: 4}
strict := DemoAssessmentSignalPolicy()
strict.FastAnswersAttention, strict.FastAnswersReview = 2, 4
relaxed := DemoAssessmentSignalPolicy()
relaxed.FastAnswersAttention, relaxed.FastAnswersReview = 100, 200
if got := strict.Evaluate(measures).Band; got != AssessmentReviewBandReview {
t.Fatalf("strict policy band = %s, want review", got)
}
if got := relaxed.Evaluate(measures).Band; got != AssessmentReviewBandNormal {
t.Fatalf("relaxed policy band = %s, want normal", got)
}
}
func TestParseAssessmentReviewActorRequiresAnOperatorHandle(t *testing.T) {
if _, err := ParseAssessmentReviewActor("operator:night.shift-1"); err != nil {
t.Fatalf("ParseAssessmentReviewActor(valid) error = %v", err)
}
for _, invalid := range []string{"", "alice", "operator:", "operator:Alice", "operator:a@b.example", "system:cron"} {
if _, err := ParseAssessmentReviewActor(invalid); err == nil {
t.Errorf("ParseAssessmentReviewActor(%q) accepted an invalid actor", invalid)
}
}
}
+13
View File
@@ -130,6 +130,10 @@ func (policy ProductPolicy) clone() ProductPolicy {
trainingCopy := *training
copied.Assessment.Training = &trainingCopy
}
if signals := policy.Assessment.Signals; signals != nil {
signalsCopy := *signals
copied.Assessment.Signals = &signalsCopy
}
if support := policy.Support; support != nil {
supportCopy := *support
copied.Support = &supportCopy
@@ -324,6 +328,10 @@ type AssessmentPolicy struct {
// Training is an explicit non-qualification policy section. It is nil in
// immutable legacy policies and never inherits real assessment settings.
Training *AssessmentTrainingPolicy
// Signals holds the thresholds of the manual-review band. It is nil in
// policy versions that predate it; such a version computes no band and
// never inherits another version's thresholds.
Signals *AssessmentSignalPolicy
}
// AssessmentAttemptPolicy holds the versioned execution limits for a newly
@@ -452,6 +460,11 @@ func (policy AssessmentPolicy) Validate() error {
return err
}
}
if policy.Signals != nil {
if err := policy.Signals.Validate(); err != nil {
return err
}
}
return nil
}
+10
View File
@@ -86,3 +86,13 @@ func DemoProductPolicyV2() ProductPolicy {
policy.Support = &support
return policy
}
// DemoProductPolicyV3 returns the demo policy with the manual-review band
// thresholds on top of DemoProductPolicyV2. It is published explicitly; a
// stored version is never rewritten, and startup seeding publishes V1 only.
func DemoProductPolicyV3() ProductPolicy {
policy := DemoProductPolicyV2()
signals := DemoAssessmentSignalPolicy()
policy.Assessment.Signals = &signals
return policy
}
+79 -2
View File
@@ -88,6 +88,7 @@ type assessmentPolicyDocument struct {
StopRule *assessmentStopDocument `json:"stop_rule"`
Attempt *assessmentAttemptDocument `json:"attempt,omitempty"`
Training *assessmentTrainingDocument `json:"training,omitempty"`
Signals *assessmentSignalsDocument `json:"signals,omitempty"`
}
type assessmentPolicyV1Document struct {
@@ -111,6 +112,28 @@ type assessmentAttemptDocument struct {
BasicPassMarkBP *BasisPoints `json:"basic_pass_mark_bp"`
}
type assessmentSignalsDocument struct {
FastFloorIntegerMS *int32 `json:"fast_floor_integer_ms"`
FastFloorSequenceMS *int32 `json:"fast_floor_sequence_ms"`
FastAnswersAttention *int32 `json:"fast_answers_attention"`
FastAnswersReview *int32 `json:"fast_answers_review"`
DeviationRatioBP *BasisPoints `json:"deviation_ratio_bp"`
DeviationMinAnswers *int32 `json:"deviation_min_answers"`
DeviatingAnswersAttention *int32 `json:"deviating_answers_attention"`
DeviatingAnswersReview *int32 `json:"deviating_answers_review"`
ParallelAlternationsAttention *int32 `json:"parallel_alternations_attention"`
ParallelAlternationsReview *int32 `json:"parallel_alternations_review"`
ExtraNetworksAttention *int32 `json:"extra_networks_attention"`
ExtraNetworksReview *int32 `json:"extra_networks_review"`
DuplicateIntegerCapBits *int32 `json:"duplicate_integer_cap_bits"`
DuplicateSequenceCapBits *int32 `json:"duplicate_sequence_cap_bits"`
DuplicateBitsAttention *int32 `json:"duplicate_bits_attention"`
DuplicateBitsReview *int32 `json:"duplicate_bits_review"`
ClientFocusLossAttentionMS *int32 `json:"client_focus_loss_attention_ms"`
ClientClipboardEventsAttention *int32 `json:"client_clipboard_events_attention"`
ClientFullscreenExitsAttention *int32 `json:"client_fullscreen_exits_attention"`
}
type assessmentTrainingDocument struct {
DemoExpressDurationSeconds *int32 `json:"demo_express_duration_seconds"`
DemoExpressItemCount *int32 `json:"demo_express_item_count"`
@@ -155,7 +178,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
}
}
schemaVersion := int32(productPolicySchemaVersionV1)
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support != nil {
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || policy.Support != nil {
schemaVersion = productPolicySchemaVersionV2
}
document := productPolicyDocument{
@@ -196,6 +219,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
},
Attempt: encodeAssessmentAttemptPolicy(assessment.Attempt),
Training: encodeAssessmentTrainingPolicy(assessment.Training),
Signals: encodeAssessmentSignalPolicy(assessment.Signals),
},
Identity: &identityPolicyDocument{
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
@@ -241,6 +265,33 @@ func encodeAssessmentTrainingPolicy(policy *AssessmentTrainingPolicy) *assessmen
}
}
func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSignalsDocument {
if policy == nil {
return nil
}
return &assessmentSignalsDocument{
FastFloorIntegerMS: pointer(policy.FastFloorIntegerMS),
FastFloorSequenceMS: pointer(policy.FastFloorSequenceMS),
FastAnswersAttention: pointer(policy.FastAnswersAttention),
FastAnswersReview: pointer(policy.FastAnswersReview),
DeviationRatioBP: pointer(policy.DeviationRatio),
DeviationMinAnswers: pointer(policy.DeviationMinAnswers),
DeviatingAnswersAttention: pointer(policy.DeviatingAnswersAttention),
DeviatingAnswersReview: pointer(policy.DeviatingAnswersReview),
ParallelAlternationsAttention: pointer(policy.ParallelAlternationsAttention),
ParallelAlternationsReview: pointer(policy.ParallelAlternationsReview),
ExtraNetworksAttention: pointer(policy.ExtraNetworksAttention),
ExtraNetworksReview: pointer(policy.ExtraNetworksReview),
DuplicateIntegerCapBits: pointer(policy.DuplicateIntegerCapBits),
DuplicateSequenceCapBits: pointer(policy.DuplicateSequenceCapBits),
DuplicateBitsAttention: pointer(policy.DuplicateAttentionBits),
DuplicateBitsReview: pointer(policy.DuplicateReviewBits),
ClientFocusLossAttentionMS: pointer(policy.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: pointer(policy.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: pointer(policy.ClientFullscreenExitsAttention),
}
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
@@ -295,7 +346,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
return ProductPolicy{}, err
}
assessment := parsed.Assessment
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil)
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil)
if !hasAssessmentExtension && parsed.Support == nil {
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
}
@@ -371,6 +422,31 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
IdleTimeoutSeconds: require(&reader, "assessment.training.idle_timeout_seconds", training.IdleTimeoutSeconds),
}
}
var signalPolicy *AssessmentSignalPolicy
if assessment.Signals != nil {
signals := assessment.Signals
signalPolicy = &AssessmentSignalPolicy{
FastFloorIntegerMS: require(&reader, "assessment.signals.fast_floor_integer_ms", signals.FastFloorIntegerMS),
FastFloorSequenceMS: require(&reader, "assessment.signals.fast_floor_sequence_ms", signals.FastFloorSequenceMS),
FastAnswersAttention: require(&reader, "assessment.signals.fast_answers_attention", signals.FastAnswersAttention),
FastAnswersReview: require(&reader, "assessment.signals.fast_answers_review", signals.FastAnswersReview),
DeviationRatio: require(&reader, "assessment.signals.deviation_ratio_bp", signals.DeviationRatioBP),
DeviationMinAnswers: require(&reader, "assessment.signals.deviation_min_answers", signals.DeviationMinAnswers),
DeviatingAnswersAttention: require(&reader, "assessment.signals.deviating_answers_attention", signals.DeviatingAnswersAttention),
DeviatingAnswersReview: require(&reader, "assessment.signals.deviating_answers_review", signals.DeviatingAnswersReview),
ParallelAlternationsAttention: require(&reader, "assessment.signals.parallel_alternations_attention", signals.ParallelAlternationsAttention),
ParallelAlternationsReview: require(&reader, "assessment.signals.parallel_alternations_review", signals.ParallelAlternationsReview),
ExtraNetworksAttention: require(&reader, "assessment.signals.extra_networks_attention", signals.ExtraNetworksAttention),
ExtraNetworksReview: require(&reader, "assessment.signals.extra_networks_review", signals.ExtraNetworksReview),
DuplicateIntegerCapBits: require(&reader, "assessment.signals.duplicate_integer_cap_bits", signals.DuplicateIntegerCapBits),
DuplicateSequenceCapBits: require(&reader, "assessment.signals.duplicate_sequence_cap_bits", signals.DuplicateSequenceCapBits),
DuplicateAttentionBits: require(&reader, "assessment.signals.duplicate_bits_attention", signals.DuplicateBitsAttention),
DuplicateReviewBits: require(&reader, "assessment.signals.duplicate_bits_review", signals.DuplicateBitsReview),
ClientFocusLossAttentionMS: require(&reader, "assessment.signals.client_focus_loss_attention_ms", signals.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: require(&reader, "assessment.signals.client_clipboard_events_attention", signals.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: require(&reader, "assessment.signals.client_fullscreen_exits_attention", signals.ClientFullscreenExitsAttention),
}
}
policy := ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
@@ -406,6 +482,7 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
},
Attempt: attemptPolicy,
Training: trainingPolicy,
Signals: signalPolicy,
},
Identity: IdentityPolicy{
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),