feat(assessment): watermark the task text of real attempts

This commit is contained in:
shira committed 2026-10-11 10:44:30 +03:00
1 parent 24b64d698a
commit c975a0d506
57 files changed
+2429 -92

No files matched your search

@@ -318,6 +318,16 @@ type AssessmentAttemptPublicSnapshot struct {
IdleTimeout int32 `json:"idle_timeout_seconds"`
CurrentItem *AssessmentAttemptPublicItem `json:"current_item"`
Practices []AssessmentAttemptPublicPractice `json:"practices"`
// Watermark is set when a response is presented, never when it is stored:
// the retained idempotent response stays free of it, and every presentation
// derives the same value from the attempt.
Watermark *AssessmentAttemptPublicWatermark `json:"watermark,omitempty"`
}
// AssessmentAttemptPublicWatermark is the visible pseudonymous code that the
// task screen shows next to the time. It reveals nothing about the candidate.
type AssessmentAttemptPublicWatermark struct {
Code string `json:"code"`
}
// AssessmentAttemptPublicPractice is the empty, explicit practice projection
@@ -0,0 +1,321 @@
package domain
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// ErrInvalidAssessmentWatermark reports a malformed watermark seed or code.
var ErrInvalidAssessmentWatermark = errors.New("invalid assessment watermark")
// AssessmentWatermarkSeed is the secret stream of one attempt: a keyed digest
// of the attempt identifier under a server key. The visible code, the zero-width
// mark, and the choice of wordings are all read from it, so none of them can be
// forged or predicted without the server secret, and none carries the attempt
// identifier or any account data. The seed itself never leaves the server.
type AssessmentWatermarkSeed [32]byte
// IsZero reports an unset seed.
func (seed AssessmentWatermarkSeed) IsZero() bool { return seed == AssessmentWatermarkSeed{} }
const (
// watermarkAlphabet is Crockford base32: no I, L, O, or U, so a code read
// from a screenshot is not confused between 0 and O or 1 and I.
watermarkAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
watermarkCodeLength = 10
watermarkCodeBits = 5 * watermarkCodeLength
// watermarkDigits is the number of base-4 digits that carry the code bits
// in the zero-width mark. One more digit is a check.
watermarkDigits = watermarkCodeBits / 2
watermarkRunLength = watermarkDigits + 1
// watermarkMaxCopies bounds how many times the mark is repeated in one text.
watermarkMaxCopies = 8
// watermarkWordingOffset is where the wording choices start in the seed,
// after the 7 bytes that the code reads.
watermarkWordingOffset = 8
)
// watermarkZeroWidth are the four characters of the invisible mark, the digits
// 0 to 3. They are the zero width space, non-joiner, joiner, and word joiner.
//
//nolint:gochecknoglobals // A fixed table that is read-only after initialization.
var watermarkZeroWidth = [4]rune{'\u200b', '\u200c', '\u200d', '\u2060'}
// AssessmentWatermarkCode is the pseudonymous code of an attempt: 10 symbols
// of Crockford base32 held in upper case without separators. It shows on the
// task screen next to the time. It contains no name, contact, or identifier.
type AssessmentWatermarkCode string
// String writes the code in two groups of five, the way it is shown.
func (code AssessmentWatermarkCode) String() string {
if len(code) != watermarkCodeLength {
return string(code)
}
return string(code[:5]) + "-" + string(code[5:])
}
// ParseAssessmentWatermarkCode reads a code as an operator or an OCR gives it:
// any case, with or without the separator, with O read as 0 and I or L as 1.
func ParseAssessmentWatermarkCode(value string) (AssessmentWatermarkCode, error) {
var builder strings.Builder
for _, r := range strings.ToUpper(value) {
switch {
case r == '-' || unicode.IsSpace(r):
continue
case r == 'O':
r = '0'
case r == 'I' || r == 'L':
r = '1'
case r == 'U':
r = 'V'
}
if !strings.ContainsRune(watermarkAlphabet, r) {
return "", fmt.Errorf("domain.ParseAssessmentWatermarkCode - the code has a character outside its alphabet: %w", ErrInvalidAssessmentWatermark)
}
builder.WriteRune(r)
}
if builder.Len() != watermarkCodeLength {
return "", fmt.Errorf("domain.ParseAssessmentWatermarkCode - the code must have %d symbols: %w", watermarkCodeLength, ErrInvalidAssessmentWatermark)
}
return AssessmentWatermarkCode(builder.String()), nil
}
// Distance counts the positions at which two codes differ.
func (code AssessmentWatermarkCode) Distance(other AssessmentWatermarkCode) int {
if len(code) != len(other) {
return max(len(code), len(other))
}
differing := 0
for index := range len(code) {
if code[index] != other[index] {
differing++
}
}
return differing
}
// value is the code as one integer of watermarkCodeBits bits.
func (code AssessmentWatermarkCode) value() uint64 {
var number uint64
for index := range len(code) {
number = number<<5 | uint64(strings.IndexByte(watermarkAlphabet, code[index])) //nolint:gosec // The index is 0 to 31 for a parsed code.
}
return number
}
// AssessmentWatermark marks the task text of one attempt.
type AssessmentWatermark struct {
seed AssessmentWatermarkSeed
}
// NewAssessmentWatermark rejects an unset seed, which would give every attempt
// the same mark.
func NewAssessmentWatermark(seed AssessmentWatermarkSeed) (AssessmentWatermark, error) {
if seed.IsZero() {
return AssessmentWatermark{}, fmt.Errorf("domain.NewAssessmentWatermark - the seed must be set: %w", ErrInvalidAssessmentWatermark)
}
return AssessmentWatermark{seed: seed}, nil
}
// Code returns the visible code of the attempt: the leading bits of the seed.
func (watermark AssessmentWatermark) Code() AssessmentWatermarkCode {
number := binary.BigEndian.Uint64(watermark.seed[:8]) >> (64 - watermarkCodeBits)
symbols := make([]byte, watermarkCodeLength)
for index := watermarkCodeLength - 1; index >= 0; index-- {
symbols[index] = watermarkAlphabet[number&31]
number >>= 5
}
return AssessmentWatermarkCode(symbols)
}
// Mark writes the statement for this attempt. It picks one form for each
// interchangeable phrase and then inserts the invisible mark at the start of
// the sentences. Neither step changes the meaning, the answer, or what a screen
// reader says: see VisibleAssessmentText.
func (watermark AssessmentWatermark) Mark(statement string) string {
reworded := rewriteWording(canonicalWording(VisibleAssessmentText(statement)), watermark.wordingForm)
return insertWatermarkRuns(reworded, watermark.zeroWidthRun())
}
// wordingForm is the index of the form that this attempt uses for a group.
func (watermark AssessmentWatermark) wordingForm(group int) int {
forms := len(assessmentWordingGroups[group].forms)
return int(watermark.seed[watermarkWordingOffset+group%(len(watermark.seed)-watermarkWordingOffset)]) % forms
}
// WordingAgreement compares the phrases of a leaked text with the choices of
// this attempt, reading only the phrases that the leak shows within the stored
// statement (see AssessmentLeakAlignment): words around the statement in the
// leak, such as a quotation or a message, are not read. Slots is the number of
// phrase groups that the leak shows and Agreeing how many of them stand in the
// form this attempt picked. A group counts once however often it occurs, and a
// group that stands in two forms in the leak does not agree. Each group is
// worth about one bit: another attempt agrees with a group by chance in one
// case of two.
func (watermark AssessmentWatermark) WordingAgreement(alignment LeakAlignment) (agreeing, slots int) {
forms := map[int]int{}
conflicting := map[int]bool{}
for _, phrase := range alignment.Phrases {
if previous, seen := forms[phrase.Group]; seen && previous != phrase.Form {
conflicting[phrase.Group] = true
}
forms[phrase.Group] = phrase.Form
}
for group, form := range forms {
if !conflicting[group] && form == watermark.wordingForm(group) {
agreeing++
}
}
return agreeing, len(forms)
}
// zeroWidthRun encodes the code bits as watermarkDigits base-4 digits in the
// invisible characters, followed by a check digit, so a run that was cut or
// mixed with other characters is recognized as damaged.
func (watermark AssessmentWatermark) zeroWidthRun() string {
number := watermark.Code().value()
digits := make([]rune, watermarkDigits+1)
sum := 0
for index := watermarkDigits - 1; index >= 0; index-- {
digit := int(number & 3)
digits[index] = watermarkZeroWidth[digit]
sum += digit
number >>= 2
}
digits[watermarkDigits] = watermarkZeroWidth[sum%4]
return string(digits)
}
// insertWatermarkRuns places the mark after the first space and at the start of
// each following sentence, so that any copy of a sentence or two keeps a whole
// run. Positions are byte offsets in the text.
func insertWatermarkRuns(text, run string) string {
positions := watermarkPositions(text)
if len(positions) == 0 {
return text + run
}
var builder strings.Builder
builder.Grow(len(text) + len(positions)*len(run))
copied := 0
for _, position := range positions {
builder.WriteString(text[copied:position])
builder.WriteString(run)
copied = position
}
builder.WriteString(text[copied:])
return builder.String()
}
func watermarkPositions(text string) []int {
var positions []int
if first := strings.IndexFunc(text, unicode.IsSpace); first >= 0 && first+1 < len(text) {
positions = append(positions, first+1)
}
previous := rune(0)
for offset, r := range text {
if len(positions) >= watermarkMaxCopies {
break
}
next := offset + utf8.RuneLen(r)
if unicode.IsSpace(r) && (previous == '.' || previous == '!' || previous == '?') && next < len(text) {
if len(positions) == 0 || positions[len(positions)-1] != next {
positions = append(positions, next)
}
}
previous = r
}
return positions
}
// ExtractAssessmentWatermarkCodes returns the codes read from the invisible
// marks in a text, in order, one per intact run. A run is a maximal stretch of
// the four mark characters of exactly the right length and a correct check
// digit; anything else is ignored.
func ExtractAssessmentWatermarkCodes(text string) []AssessmentWatermarkCode {
var codes []AssessmentWatermarkCode
var run []int
flush := func() {
if code, ok := decodeWatermarkRun(run); ok {
codes = append(codes, code)
}
run = run[:0]
}
for _, r := range text {
if digit := watermarkDigit(r); digit >= 0 {
run = append(run, digit)
continue
}
flush()
}
flush()
return codes
}
func watermarkDigit(r rune) int {
for digit, candidate := range watermarkZeroWidth {
if r == candidate {
return digit
}
}
return -1
}
func decodeWatermarkRun(digits []int) (AssessmentWatermarkCode, bool) {
if len(digits) != watermarkRunLength {
return "", false
}
var number uint64
sum := 0
for _, digit := range digits[:watermarkDigits] {
number = number<<2 | uint64(digit) //nolint:gosec // A digit is 0 to 3.
sum += digit
}
if sum%4 != digits[watermarkDigits] {
return "", false
}
symbols := make([]byte, watermarkCodeLength)
for index := watermarkCodeLength - 1; index >= 0; index-- {
symbols[index] = watermarkAlphabet[number&31]
number >>= 5
}
return AssessmentWatermarkCode(symbols), true
}
// VisibleAssessmentText removes everything a reader cannot see from a marked
// text: the four mark characters (all of them format characters of Unicode) and
// the other invisible format characters. It
// is the text that assistive technology must read, and the client uses the same
// rule to keep the marks out of the accessibility tree.
func VisibleAssessmentText(text string) string {
return strings.Map(func(r rune) rune {
if invisibleTextRune(r) {
return -1
}
return r
}, text)
}
func invisibleTextRune(r rune) bool {
return unicode.Is(unicode.Cf, r)
}
// NormalizedAssessmentText brings a leaked text to a form in which it can be
// read: the invisible characters are removed, the typographic apostrophe
// becomes a plain one, and runs of white space, non-breaking spaces among them,
// collapse into one space. The wording of the text is kept.
func NormalizedAssessmentText(text string) string {
cleaned := strings.NewReplacer("\u2019", "'", "\u02bc", "'").Replace(VisibleAssessmentText(text))
return strings.Join(strings.Fields(cleaned), " ")
}
// CanonicalAssessmentText is the normalized text with every interchangeable
// phrase written in its canonical form. Two copies of one statement that differ
// only by the watermark have the same canonical text, and so does a stored
// statement, which makes it the form in which a leak is compared.
func CanonicalAssessmentText(text string) string {
return canonicalWording(NormalizedAssessmentText(text))
}
@@ -0,0 +1,343 @@
package domain
import (
"strings"
"testing"
"unicode"
)
// rateLimitTemplate is the statement template of the rate limit family of the demo
// bank. It holds several interchangeable phrases, as real statements do.
const rateLimitTemplate = "A gateway protects an endpoint with a sliding-window limiter. A request arriving at second t is accepted only when fewer than {{.limit}} previously accepted requests have an arrival time in the half-open interval (t - {{.window}}, t]. A rejected request is not remembered and does not count against later requests. The gateway receives {{.requests}} requests at these arrival times, in seconds and in non-decreasing order: {{.timestamps}}. How many requests does the gateway reject?"
func watermarkSeed(first byte) AssessmentWatermarkSeed {
var seed AssessmentWatermarkSeed
for index := range seed {
seed[index] = first + byte(index*7)
}
return seed
}
func testWatermark(t *testing.T, first byte) AssessmentWatermark {
t.Helper()
watermark, err := NewAssessmentWatermark(watermarkSeed(first))
if err != nil {
t.Fatalf("NewAssessmentWatermark() error = %v", err)
}
return watermark
}
func rateLimitVariant(t *testing.T) AssessmentVariant {
t.Helper()
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]AssessmentParameterRange{
"requests": {Min: 8, Max: 12}, "window": {Min: 3, Max: 5}, "limit": {Min: 2, Max: 3}, "max_gap": {Min: 0, Max: 3},
},
StatementTemplate: rateLimitTemplate,
}
input.AnswerKey.AnswerFormat = assessmentAlgorithms["rate_limit_window.v1"].answerFormat
variant, err := restoreAssessment(t, input).NewVariant(4242)
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
return variant
}
func hasInvisible(text string) bool {
return strings.IndexFunc(text, func(r rune) bool { return unicode.Is(unicode.Cf, r) }) >= 0
}
func TestTheSameVariantOfTwoAttemptsDiffersOnlyByTheWatermark(t *testing.T) {
variant := rateLimitVariant(t)
first, second := testWatermark(t, 1), testWatermark(t, 9)
markedFirst, markedSecond := first.Mark(variant.Statement), second.Mark(variant.Statement)
if markedFirst == markedSecond {
t.Fatal("two attempts got the same marked statement, want a mark of their own")
}
if !hasInvisible(markedFirst) || !hasInvisible(markedSecond) {
t.Fatal("a marked statement has no invisible mark")
}
// Whatever the attempt, the statement says the same: only the mark and the
// interchangeable phrases differ, and both disappear in the canonical text.
want := CanonicalAssessmentText(variant.Statement)
for name, marked := range map[string]string{"first": markedFirst, "second": markedSecond} {
if got := CanonicalAssessmentText(marked); got != want {
t.Fatalf("canonical text of the %s attempt =\n%q\nwant\n%q", name, got, want)
}
}
// The mark is outside the variant: the reference answer, the rubric, and the
// options that grading reads are the ones of the variant.
if variant.ReferenceAnswer == "" {
t.Fatal("the variant has no reference answer to compare")
}
if again := rateLimitVariant(t); again.ReferenceAnswer != variant.ReferenceAnswer || again.Statement != variant.Statement {
t.Fatal("marking changed the variant, want the unmarked statement and the same reference answer")
}
}
func TestMarkingIsDeterministicAndIdempotent(t *testing.T) {
statement := rateLimitVariant(t).Statement
watermark := testWatermark(t, 3)
marked := watermark.Mark(statement)
if again := watermark.Mark(statement); again != marked {
t.Fatal("marking the same statement twice gave two results")
}
if again := watermark.Mark(marked); again != marked {
t.Fatal("marking a marked statement changed it, want the same text")
}
if other := testWatermark(t, 3).Mark(statement); other != marked {
t.Fatal("equal seeds gave different marks")
}
}
func TestInvisibleMarkRoundTripsAndSurvivesCopiedSentences(t *testing.T) {
statement := rateLimitVariant(t).Statement
watermark := testWatermark(t, 5)
marked := watermark.Mark(statement)
codes := ExtractAssessmentWatermarkCodes(marked)
if len(codes) < 3 {
t.Fatalf("ExtractAssessmentWatermarkCodes() found %d copies, want one in each of several sentences", len(codes))
}
for _, code := range codes {
if code != watermark.Code() {
t.Fatalf("a copy decoded to %s, want %s", code, watermark.Code())
}
}
// A paragraph taken from the middle keeps a whole run.
sentences := strings.SplitAfter(marked, ". ")
if got := ExtractAssessmentWatermarkCodes(sentences[2] + sentences[3]); len(got) == 0 || got[0] != watermark.Code() {
t.Fatalf("two copied sentences decoded to %v, want %s", got, watermark.Code())
}
// Removing the invisible characters removes the mark and nothing else.
if codes := ExtractAssessmentWatermarkCodes(VisibleAssessmentText(marked)); len(codes) != 0 {
t.Fatalf("a text without invisible characters decoded to %v", codes)
}
}
func TestDamagedInvisibleMarkIsNotRead(t *testing.T) {
watermark := testWatermark(t, 5)
run := watermark.zeroWidthRun()
runes := []rune(run)
tests := map[string]string{
"a run cut short": "a " + string(runes[:len(runes)-1]) + " b",
"a run with an extra": "a " + run + string(watermarkZeroWidth[1]) + " b",
"a wrong check digit": "a " + string(runes[:len(runes)-1]) + string(watermarkZeroWidth[(watermarkDigit(runes[len(runes)-1])+1)%4]) + " b",
"two runs run together": "a " + run + run + " b",
}
for name, text := range tests {
t.Run(name, func(t *testing.T) {
if codes := ExtractAssessmentWatermarkCodes(text); len(codes) != 0 {
t.Fatalf("ExtractAssessmentWatermarkCodes() = %v, want nothing from a damaged mark", codes)
}
})
}
if codes := ExtractAssessmentWatermarkCodes("a " + run + " b"); len(codes) != 1 || codes[0] != watermark.Code() {
t.Fatalf("ExtractAssessmentWatermarkCodes(intact run) = %v, want one code", codes)
}
}
func TestAccessibleTextOfAMarkedStatementIsTheStatement(t *testing.T) {
variant := rateLimitVariant(t)
watermark := testWatermark(t, 7)
marked := watermark.Mark(variant.Statement)
visible := VisibleAssessmentText(marked)
if hasInvisible(visible) {
t.Fatal("the accessible text still holds an invisible character")
}
// What assistive technology reads is the statement with the phrases the
// attempt picked: the same words in the same order, nothing added.
if got, want := CanonicalAssessmentText(visible), CanonicalAssessmentText(variant.Statement); got != want {
t.Fatalf("accessible text differs in meaning:\n%q\nwant\n%q", got, want)
}
if len(visible) > len(variant.Statement)+32 {
t.Fatalf("accessible text grew from %d to %d bytes, want only a different choice of phrases", len(variant.Statement), len(visible))
}
// The numbers and data of the task are untouched.
for _, token := range strings.Fields(variant.Statement) {
if strings.ContainsAny(token, "0123456789") && !strings.Contains(visible, strings.Trim(token, ".,:;")) {
t.Fatalf("data token %q is missing from the accessible text", token)
}
}
}
func TestWordingAgreementReadsOnlyTheAlignedPhrasesOfTheStatement(t *testing.T) {
statement := rateLimitVariant(t).Statement
first := testWatermark(t, 1)
own := first.Mark(statement)
// The statement as the attempt showed it, alone and among other words that
// hold phrases of their own, agrees with every phrase of its attempt.
surrounded := "He wrote: it isn't hard, and we don't know. " + VisibleAssessmentText(own) + " Thanks, it isn't clear."
for name, leak := range map[string]string{"alone": VisibleAssessmentText(own), "with the marks": own, "surrounded": surrounded} {
agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, leak))
if slots < 4 || agreeing != slots {
t.Fatalf("%s: WordingAgreement() = %d of %d, want every one of at least four phrase groups to agree", name, agreeing, slots)
}
}
// Some other attempt picked other phrases for at least one group, and it
// disagrees with the leak of the first one.
disagreeing := 0
for seed := byte(2); seed < 40; seed++ {
if agreeing, slots := testWatermark(t, seed).WordingAgreement(AssessmentLeakAlignment(statement, VisibleAssessmentText(own))); agreeing < slots {
disagreeing++
}
}
if disagreeing == 0 {
t.Fatal("no other seed disagrees with the phrases of the first attempt")
}
// A leak of a fragment yields the phrases of the fragment only.
piece := VisibleAssessmentText(own)
start := strings.Index(piece, "A rejected")
if start < 0 {
t.Fatal("the statement has no sentence that starts with A rejected")
}
fragment := piece[start:]
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, fragment)); slots == 0 || slots >= 5 || agreeing != slots {
t.Fatalf("fragment: WordingAgreement() = %d of %d, want fewer groups than the whole statement, all agreeing", agreeing, slots)
}
// A text that is not the statement has nothing to align.
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, "It is not what it is. It does not matter, as it isn't related.")); slots != 0 || agreeing != 0 {
t.Fatalf("unrelated text: WordingAgreement() = %d of %d, want nothing aligned", agreeing, slots)
}
// A group written in two forms is edited text and agrees with no group.
edited := strings.Replace(VisibleAssessmentText(own), "does not", "doesn't", 1) + " " + strings.Replace(VisibleAssessmentText(own), "doesn't", "does not", 1)
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, edited)); agreeing > slots {
t.Fatalf("edited text: %d of %d", agreeing, slots)
}
}
func TestAlignmentIsLongestForTheVariantThatWasLeakedAndShorterForOtherVariants(t *testing.T) {
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]AssessmentParameterRange{
"requests": {Min: 8, Max: 12}, "window": {Min: 3, Max: 5}, "limit": {Min: 2, Max: 3}, "max_gap": {Min: 0, Max: 3},
},
StatementTemplate: rateLimitTemplate,
}
input.AnswerKey.AnswerFormat = assessmentAlgorithms["rate_limit_window.v1"].answerFormat
family := restoreAssessment(t, input)
leaked, err := family.NewVariant(4242)
if err != nil {
t.Fatalf("NewVariant(4242) error = %v", err)
}
other, err := family.NewVariant(99)
if err != nil || other.Statement == leaked.Statement {
t.Fatalf("NewVariant(99) = %v, %v, want another statement", other.Statement, err)
}
leak := "Someone asked: " + VisibleAssessmentText(testWatermark(t, 1).Mark(leaked.Statement)) + " thanks"
own, foreign := AssessmentLeakAlignment(leaked.Statement, leak), AssessmentLeakAlignment(other.Statement, leak)
if own.Runes <= foreign.Runes {
t.Fatalf("aligned %d characters for the leaked variant and %d for another variant of the family, want the leaked one longer", own.Runes, foreign.Runes)
}
// The leak is a copy of the leaked variant, and the other variant shares only
// the text of its family and then diverges, so it is not the source.
if !own.Complete || !own.Follows() || foreign.Follows() {
t.Fatalf("leaked variant: %+v, other variant: %+v, want the leaked one followed to its end and the other one diverged", own, foreign)
}
// A leak cut inside the statement ends there; a leak with other words in the
// middle of it has diverged.
cut := VisibleAssessmentText(testWatermark(t, 1).Mark(leaked.Statement))
cut = cut[:len(cut)*2/3]
if got := AssessmentLeakAlignment(leaked.Statement, cut); got.Complete || !got.Ended || !got.Follows() {
t.Fatalf("a cut leak aligned %+v, want it to end inside the statement", got)
}
if got := AssessmentLeakAlignment(leaked.Statement, cut+" and some other words that the statement does not have"); got.Follows() {
t.Fatalf("a leak with other words inside the statement aligned %+v, want it to have diverged", got)
}
total := 0
for _, piece := range AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(leaked.Statement)) {
total += len([]rune(piece))
}
if own.Runes != total {
t.Fatalf("the leaked variant aligned %d characters, want all %d characters of its pieces", own.Runes, total)
}
if got := AssessmentLeakAlignment(leaked.Statement, "nothing in common with it at all"); got.Runes != 0 || len(got.Phrases) != 0 {
t.Fatalf("unrelated text aligned %+v, want nothing", got)
}
}
func TestSplittingATextAtItsPhrasesLeavesPiecesThatEveryCopyShares(t *testing.T) {
statement := rateLimitVariant(t).Statement
// Whatever phrases an attempt picked, the pieces between them are the same.
want := AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(statement))
for seed := byte(1); seed < 20; seed++ {
got := AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(testWatermark(t, seed).Mark(statement)))
if len(got) != len(want) {
t.Fatalf("seed %d: %d pieces, want %d", seed, len(got), len(want))
}
for index := range want {
if got[index] != want[index] {
t.Fatalf("seed %d: piece %d = %q, want %q", seed, index, got[index], want[index])
}
}
}
}
func TestInterchangeablePhrasesStayWithinTheirGuards(t *testing.T) {
watermark := testWatermark(t, 1)
// At the end of a sentence "at most" is not followed by a number, so the
// alternative form would not read the same and is not used.
tail := "How many requests per minute can it serve at most?"
if got := VisibleAssessmentText(watermark.Mark(tail)); got != tail {
t.Fatalf("Mark(%q) = %q, want the phrase before a question mark kept", tail, got)
}
// Inside a longer word nothing is replaced.
inside := "This is nothing, and scannotes stays."
if got := VisibleAssessmentText(watermark.Mark(inside)); !strings.Contains(got, "scannotes") || !strings.Contains(got, "This is nothing") {
t.Fatalf("Mark(%q) = %q, want words that contain a phrase left alone", inside, got)
}
// Both forms of a group map to the canonical one.
for want, texts := range map[string][]string{
"holds at most 5 entries": {"holds at most 5 entries", "holds no more than 5 entries"},
"хранит не более 5 записей": {"хранит не более 5 записей", "хранит не больше 5 записей"},
"it isn't empty": {"it isn't empty", "it is not empty", "it isn\u2019t empty"},
} {
for _, text := range texts {
if got := CanonicalAssessmentText(text); got != strings.ReplaceAll(want, "isn't", "is not") {
t.Fatalf("CanonicalAssessmentText(%q) = %q", text, got)
}
}
}
}
func TestWatermarkCodeIsStableReadableAndParsesWhatOCRReads(t *testing.T) {
watermark := testWatermark(t, 1)
code := watermark.Code()
if len(code) != watermarkCodeLength || len(code.String()) != watermarkCodeLength+1 || code.String()[5] != '-' {
t.Fatalf("Code() = %q, want ten symbols shown as XXXXX-XXXXX", code)
}
if testWatermark(t, 1).Code() != code || testWatermark(t, 2).Code() == code {
t.Fatal("the code must follow the seed")
}
for _, shown := range []string{code.String(), strings.ToLower(code.String()), strings.ReplaceAll(code.String(), "-", " ")} {
parsed, err := ParseAssessmentWatermarkCode(shown)
if err != nil || parsed != code {
t.Fatalf("ParseAssessmentWatermarkCode(%q) = %q, %v, want %q", shown, parsed, err, code)
}
}
// The letters that OCR confuses read as the digits and letters of the alphabet.
read, err := ParseAssessmentWatermarkCode("OIL0O-1U123")
if err != nil {
t.Fatalf("ParseAssessmentWatermarkCode(OCR errors) error = %v", err)
}
if got, want := read.String(), "01100-1V123"; got != want {
t.Fatalf("ParseAssessmentWatermarkCode(OCR errors) = %q, want %q", got, want)
}
for _, bad := range []string{"", "ABCDE", "ABCDE-FGHJK-M", "ABCD!-FGHJK", "ABCDE-FGHJ#"} {
if _, err := ParseAssessmentWatermarkCode(bad); err == nil {
t.Fatalf("ParseAssessmentWatermarkCode(%q) succeeded, want an error", bad)
}
}
if code.Distance(code) != 0 || code.Distance(testWatermark(t, 2).Code()) == 0 {
t.Fatal("Distance must be zero for equal codes only")
}
if _, err := NewAssessmentWatermark(AssessmentWatermarkSeed{}); err == nil {
t.Fatal("NewAssessmentWatermark(zero seed) succeeded, want an error")
}
}
@@ -0,0 +1,262 @@
package domain
import (
"strings"
"unicode"
"unicode/utf8"
)
// wordingGroup lists interchangeable ways to write one phrase of a statement.
// Every form means exactly the same, so choosing one never changes the task or
// its reference answer. forms[0] is the canonical form: the attempt marker
// replaces every form of a group in a statement by the form it picked for the
// attempt, and the leak trace maps every form back to forms[0] before it
// compares texts.
//
// The list is append-only. Reordering or removing a form, or inserting a group
// before another, changes the choice of every attempt already served, and the
// marks of those attempts could no longer be read back. A new group goes to the
// end.
type wordingGroup struct {
forms []string
// beforeNumber limits the group to places where the phrase is followed by a
// space and a digit ("at most 5"). The forms read the same only there: "at
// most" ends a sentence in "how many can it serve at most?", where "no more
// than" would not.
beforeNumber bool
}
// assessmentWordingGroups are phrases of plain connective prose in the
// statements: comparisons of counts, negations that can be contracted, and
// spelling variants. They avoid the terms a statement defines and then reuses
// ("processed", "dropped", "accepted"), because rewording one of several uses of
// a defined term would confuse the task.
//
//nolint:gochecknoglobals // A fixed, append-only table that is read-only after initialization.
var assessmentWordingGroups = []wordingGroup{
{forms: []string{"at most", "no more than"}, beforeNumber: true},
{forms: []string{"at least", "no fewer than"}, beforeNumber: true},
{forms: []string{"fewer than", "less than"}, beforeNumber: true},
{forms: []string{"is not", "isn't"}},
{forms: []string{"are not", "aren't"}},
{forms: []string{"does not", "doesn't"}},
{forms: []string{"do not", "don't"}},
{forms: []string{"cannot", "can't"}},
{forms: []string{"non-decreasing", "nondecreasing"}},
{forms: []string{"only when", "only if"}},
{forms: []string{"half-open interval", "half open interval"}},
{forms: []string{"one at a time", "one by one"}},
{forms: []string{"Among all", "Of all"}},
{forms: []string{"не более", "не больше"}, beforeNumber: true},
{forms: []string{"не менее", "не меньше"}, beforeNumber: true},
{forms: []string{"только если", "лишь если"}},
{forms: []string{"в порядке неубывания", "в неубывающем порядке"}},
{forms: []string{"Найдите", "Определите"}},
}
// wordingOccurrence is one phrase found in a text.
type wordingOccurrence struct {
group int
form int
start int
end int
}
// findWordingOccurrences scans the text left to right and returns the
// non-overlapping phrases of the table. Where several forms start at the same
// place the longest wins.
func findWordingOccurrences(text string) []wordingOccurrence {
var found []wordingOccurrence
for position := 0; position < len(text); {
best := wordingOccurrence{group: -1}
for groupIndex, group := range assessmentWordingGroups {
for formIndex, form := range group.forms {
if !wordingFormAt(text, position, form, group.beforeNumber) {
continue
}
if best.group < 0 || len(form) > best.end-best.start {
best = wordingOccurrence{group: groupIndex, form: formIndex, start: position, end: position + len(form)}
}
}
}
if best.group < 0 {
_, size := utf8.DecodeRuneInString(text[position:])
position += size
continue
}
found = append(found, best)
position = best.end
}
return found
}
// wordingFormAt reports whether the form stands at the position as whole
// words: not inside a longer word and, for a number group, before a number.
func wordingFormAt(text string, position int, form string, beforeNumber bool) bool {
if !strings.HasPrefix(text[position:], form) {
return false
}
if previous, _ := utf8.DecodeLastRuneInString(text[:position]); position > 0 && wordRune(previous) {
return false
}
end := position + len(form)
if next, _ := utf8.DecodeRuneInString(text[end:]); end < len(text) && wordRune(next) {
return false
}
if !beforeNumber {
return true
}
rest := text[end:]
if len(rest) < 2 || rest[0] != ' ' {
return false
}
return rest[1] >= '0' && rest[1] <= '9'
}
// wordRune reports whether the rune continues a word. The apostrophe and the
// hyphen join words in the forms of the table, so a form never starts or ends
// inside a hyphenated or contracted word.
func wordRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '\'' || r == '-'
}
// rewriteWording replaces every phrase of the table by the form that choose
// returns for its group.
func rewriteWording(text string, choose func(group int) int) string {
occurrences := findWordingOccurrences(text)
if len(occurrences) == 0 {
return text
}
var builder strings.Builder
builder.Grow(len(text) + 16)
copied := 0
for _, occurrence := range occurrences {
builder.WriteString(text[copied:occurrence.start])
builder.WriteString(assessmentWordingGroups[occurrence.group].forms[choose(occurrence.group)])
copied = occurrence.end
}
builder.WriteString(text[copied:])
return builder.String()
}
// canonicalWording writes every phrase of the table in its canonical form.
func canonicalWording(text string) string {
return rewriteWording(text, func(int) int { return 0 })
}
// AssessmentTextPiecesBetweenPhrases cuts a text at every interchangeable
// phrase and returns the pieces in between. The pieces read the same in every
// copy of a statement, whichever form each attempt wrote the phrases in, so a
// stored statement can be searched for a piece literally.
func AssessmentTextPiecesBetweenPhrases(text string) []string {
pieces := make([]string, 0, 8)
copied := 0
for _, occurrence := range findWordingOccurrences(text) {
pieces = append(pieces, text[copied:occurrence.start])
copied = occurrence.end
}
return append(pieces, text[copied:])
}
// minAlignedPieceRunes is the shortest piece of a statement that the alignment
// accepts as a landmark in a leak: a shorter one occurs anywhere.
const minAlignedPieceRunes = 8
// LeakPhrase is a phrase of a statement as a leak writes it: the group and the
// index of the form that the leak uses.
type LeakPhrase struct {
Group int
Form int
}
// LeakAlignment is how far a leaked text follows a stored statement: the
// phrases it shows, in the forms it writes them, and the number of characters
// of the statement that it repeats between its phrases.
type LeakAlignment struct {
Phrases []LeakPhrase
// Runes is the length of the pieces of the statement that the leak repeats
// in order. A leak of the whole statement repeats all of them, and the
// statement of another variant of the same family repeats only the text of
// the family up to the first number that differs.
Runes int
// Complete reports that the leak followed the statement to its end. Ended
// reports that the leak stopped inside the statement, exactly where the
// statement continues. A leak that has other words where the statement
// continues does neither: it diverged from the statement, so the statement is
// not its source, however long the text they share.
Complete bool
Ended bool
}
// Follows reports whether the leak is a copy of the statement, whole or cut:
// it either reached the end of the statement or ended inside it.
func (alignment LeakAlignment) Follows() bool { return alignment.Complete || alignment.Ended }
// AssessmentLeakAlignment aligns a leaked text with a stored statement. It finds
// a landmark of the statement in the leak (the first piece between phrases that
// is long enough) and then follows the statement: after each piece, the leak
// must continue with one form of the next phrase and then the next piece. It
// stops at the first place where the leak does not follow the statement, so a
// leak that holds only part of the statement, an edited one, or the statement of
// another variant yields only the part that was aligned.
func AssessmentLeakAlignment(statement, leak string) LeakAlignment {
normalized := NormalizedAssessmentText(statement)
occurrences := findWordingOccurrences(normalized)
pieces := AssessmentTextPiecesBetweenPhrases(normalized)
leak = NormalizedAssessmentText(leak)
start, position := firstLandmark(pieces, leak)
if start < 0 {
return LeakAlignment{}
}
alignment := LeakAlignment{Runes: utf8.RuneCountInString(pieces[start]), Complete: true}
for index := start; index < len(occurrences); index++ {
group := assessmentWordingGroups[occurrences[index].group]
next := pieces[index+1]
matched := false
for form, text := range group.forms {
if strings.HasPrefix(leak[position:], text+next) {
alignment.Phrases = append(alignment.Phrases, LeakPhrase{Group: occurrences[index].group, Form: form})
alignment.Runes += utf8.RuneCountInString(next)
position += len(text) + len(next)
matched = true
break
}
}
if !matched {
alignment.Complete = false
alignment.Ended = leakEndsInside(leak[position:], group.forms, next)
break
}
}
return alignment
}
// leakEndsInside reports whether the rest of the leak is the beginning of what
// the statement has next (a form of the phrase, then the next piece), which is
// how a leak that was cut ends. An empty rest, and a rest that holds only a cut
// phrase or a cut piece, end the leak; any other word does not.
func leakEndsInside(rest string, forms []string, next string) bool {
if rest == "" {
return true
}
for _, form := range forms {
if strings.HasPrefix(form+next, rest) {
return true
}
}
return false
}
// firstLandmark returns the index of the first piece that is long enough and
// occurs in the leak, and the position in the leak just after it.
func firstLandmark(pieces []string, leak string) (index, position int) {
for index, piece := range pieces {
if utf8.RuneCountInString(piece) < minAlignedPieceRunes {
continue
}
if at := strings.Index(leak, piece); at >= 0 {
return index, at + len(piece)
}
}
return -1, 0
}