Files
lincodex/backend/internal/domain/assessment_watermark_test.go

382 lines
18 KiB
Go

package domain
import (
"fmt"
"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)
}
}
// dependencyOrderStatement is a family whose first interchangeable phrase comes
// after the size of the task, so the piece before it differs between variants and
// the closing sentence is the only text that every variant shares.
func dependencyOrderStatement(jobs int, dependencies string) string {
return fmt.Sprintf("A worker runs %[1]d jobs numbered from 1 to %[1]d, one at a time. A dependency A->B means job A must finish before job B starts. "+
"The dependencies are: %[2]s. The dependencies contain no cycle, so at least one valid order exists. "+
"Among all execution orders that respect every dependency, choose the one that is smallest when compared number by number from the first position. "+
"Write that order as job numbers separated by single spaces.", jobs, dependencies)
}
func TestAlignmentDoesNotTakeASharedClosingSentenceForACopyOfAnotherVariant(t *testing.T) {
leaked, other := dependencyOrderStatement(9, "7->2 9->4 2->9 6->2"), dependencyOrderStatement(5, "3->4 2->5 2->4 2->1 1->4")
leak := "Posted in the group chat: " + VisibleAssessmentText(testWatermark(t, 1).Mark(leaked)) + " please help"
// The closing sentence is long enough to be a landmark and occurs in both
// variants, but the leak differs from the other variant before it.
if got := AssessmentLeakAlignment(other, leak); got.Follows() || got.Runes != 0 {
t.Fatalf("another variant aligned %+v, want nothing: the text before the shared closing sentence differs", got)
}
if got := AssessmentLeakAlignment(leaked, leak); !got.Complete || !got.Follows() {
t.Fatalf("the leaked variant aligned %+v, want it followed to its end", got)
}
// A leak that starts inside the statement, at the closing sentence, still
// follows it: the part that the leak holds is a copy.
visible := VisibleAssessmentText(testWatermark(t, 1).Mark(leaked))
closing := strings.Index(visible, " execution orders")
if closing < 0 {
t.Fatal("the leaked statement has no closing sentence")
}
tail := visible[strings.LastIndex(visible[:closing], ". ")+len(". "):]
for name, statement := range map[string]string{"leaked": leaked, "other": other} {
if got := AssessmentLeakAlignment(statement, tail); !got.Complete || !got.Follows() {
t.Fatalf("%s variant aligned %+v for a leak of the closing sentence only, want a copy of that part", name, 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")
}
}