package domain import ( "slices" "strconv" "strings" ) // Registered seed algorithms. Each one draws an input from the seed and // computes the reference answer with its solver. The names carry a version; // see assessmentAlgorithm. var assessmentAlgorithms = map[string]assessmentAlgorithm{ "rate_limit_window.v1": { answerFormat: AnswerFormatInteger, parameters: []assessmentParameterSpec{ {name: "requests", lowest: 1, highest: 500}, {name: "window", lowest: 1, highest: 1000}, {name: "limit", lowest: 1, highest: 100}, {name: "max_gap", lowest: 0, highest: 100}, }, dataNames: []string{"timestamps"}, requiredNames: []string{"timestamps", "window", "limit"}, generate: generateRateLimitWindow, }, "dedup_window.v1": { answerFormat: AnswerFormatInteger, parameters: []assessmentParameterSpec{ {name: "events", lowest: 1, highest: 500}, {name: "keys", lowest: 1, highest: 26}, {name: "ttl", lowest: 1, highest: 1000}, {name: "max_gap", lowest: 0, highest: 100}, }, dataNames: []string{"stream"}, requiredNames: []string{"stream", "ttl"}, generate: generateDedupWindow, }, "lru_hits.v1": { answerFormat: AnswerFormatInteger, parameters: []assessmentParameterSpec{ {name: "accesses", lowest: 1, highest: 500}, {name: "keys", lowest: 1, highest: 100}, {name: "capacity", lowest: 1, highest: 50}, }, dataNames: []string{"sequence"}, requiredNames: []string{"sequence", "capacity"}, generate: generateLRUHits, }, "lru_hits_choice.v1": { answerFormat: AnswerFormatChoice, parameters: []assessmentParameterSpec{ {name: "accesses", lowest: 8, highest: 500}, {name: "keys", lowest: 3, highest: 100}, {name: "capacity", lowest: 2, highest: 50}, }, dataNames: []string{"sequence"}, requiredNames: []string{"sequence", "capacity"}, generateChoice: generateLRUHitsChoice, }, "dependency_order.v1": { answerFormat: AnswerFormatIntegerSequence, parameters: []assessmentParameterSpec{ {name: "tasks", lowest: 2, highest: 20}, {name: "links", lowest: 0, highest: 60}, }, dataNames: []string{"dependencies"}, requiredNames: []string{"dependencies", "tasks"}, generate: generateDependencyOrder, }, } // keyLetters names the keys of the duplicate-window stream; the algorithm // allows at most this many keys. const keyLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // ascendingTimes returns count non-decreasing times. The first is a draw from // 0 to maxGap and every next one adds another such draw to its predecessor. func ascendingTimes(random *seededRandom, count, maxGap int32) []int { times := make([]int, count) current := 0 for index := range times { current += int(random.between(0, maxGap)) times[index] = current } return times } // joinInts writes values as decimal numbers separated by single spaces. func joinInts(values []int) string { parts := make([]string, len(values)) for index, value := range values { parts[index] = strconv.Itoa(value) } return strings.Join(parts, " ") } // Data names: timestamps. func generateRateLimitWindow(random *seededRandom, parameters map[string]int32) (map[string]string, string) { times := ascendingTimes(random, parameters["requests"], parameters["max_gap"]) rejected := rateLimitRejected(times, int(parameters["window"]), int(parameters["limit"])) return map[string]string{"timestamps": joinInts(times)}, strconv.Itoa(rejected) } // rateLimitRejected counts requests that a sliding-window limiter rejects. A // request at time t is accepted when fewer than limit accepted requests lie // in the half-open interval (t-window, t]; rejected requests are not // remembered. Times are non-decreasing. func rateLimitRejected(times []int, window, limit int) int { accepted := make([]int, 0, len(times)) oldest, rejected := 0, 0 for _, moment := range times { for oldest < len(accepted) && accepted[oldest] <= moment-window { oldest++ } if len(accepted)-oldest < limit { accepted = append(accepted, moment) } else { rejected++ } } return rejected } // Data names: stream. func generateDedupWindow(random *seededRandom, parameters map[string]int32) (map[string]string, string) { times := ascendingTimes(random, parameters["events"], parameters["max_gap"]) keys := make([]int, len(times)) events := make([]string, len(times)) for index, moment := range times { keys[index] = random.below(int(parameters["keys"])) events[index] = keyLetters[keys[index]:keys[index]+1] + "@" + strconv.Itoa(moment) } processed := dedupProcessed(keys, times, int(parameters["ttl"])) return map[string]string{"stream": strings.Join(events, " ")}, strconv.Itoa(processed) } // dedupProcessed counts events that an idempotent consumer processes. An // event is dropped as a duplicate when its key was processed less than ttl // time units earlier; a dropped event does not extend that period. Times are // non-decreasing. func dedupProcessed(keys, times []int, ttl int) int { lastProcessed := make(map[int]int, len(keys)) processed := 0 for index, key := range keys { last, seen := lastProcessed[key] if seen && times[index]-last < ttl { continue } lastProcessed[key] = times[index] processed++ } return processed } // Data names: sequence. func generateLRUHits(random *seededRandom, parameters map[string]int32) (map[string]string, string) { accesses := drawLRUAccesses(random, parameters) hits := lruHits(accesses, int(parameters["capacity"])) return map[string]string{"sequence": joinInts(accesses)}, strconv.Itoa(hits) } // drawLRUAccesses draws the access sequence of the cache algorithms. The // draws are part of what the golden tests of lru_hits.v1 pin. func drawLRUAccesses(random *seededRandom, parameters map[string]int32) []int { accesses := make([]int, parameters["accesses"]) for index := range accesses { accesses[index] = 1 + random.below(int(parameters["keys"])) } return accesses } // nearbyCountSteps is how far from the correct count the last-resort // distractors of a count answer reach. const nearbyCountSteps = 8 // Data names: sequence. The answer is the number of hits like lru_hits.v1, // offered among options. The wrong options come from mistakes that a solver // typically makes: an off-by-one count in either direction, counting misses // instead of hits, a cache where a hit does not renew the key (FIFO // eviction), a cache that evicts the most recently used key, and a capacity // that is off by one in either direction. func generateLRUHitsChoice(random *seededRandom, parameters map[string]int32) choiceTask { accesses := drawLRUAccesses(random, parameters) capacity := int(parameters["capacity"]) total := len(accesses) hits := cacheHits(accesses, capacity, cachePolicy{refreshOnHit: true}) mistakes := []int{ hits + 1, hits - 1, total - hits, cacheHits(accesses, capacity, cachePolicy{}), cacheHits(accesses, capacity, cachePolicy{refreshOnHit: true, evictNewest: true}), cacheHits(accesses, capacity-1, cachePolicy{refreshOnHit: true}), cacheHits(accesses, capacity+1, cachePolicy{refreshOnHit: true}), } var nearby []int for step := 2; step <= nearbyCountSteps; step++ { nearby = append(nearby, hits+step, hits-step) } return choiceTask{ data: map[string]string{"sequence": joinInts(accesses)}, correct: strconv.Itoa(hits), mistakes: possibleCounts(mistakes, total), nearby: possibleCounts(nearby, total), } } // possibleCounts writes the values that a count of up to total can take, in // their order. func possibleCounts(values []int, total int) []string { texts := make([]string, 0, len(values)) for _, value := range values { if value >= 0 && value <= total { texts = append(texts, strconv.Itoa(value)) } } return texts } // cachePolicy selects a replacement rule of cacheHits. The zero value is a // first-in-first-out cache that evicts its oldest key. type cachePolicy struct { // refreshOnHit makes a hit renew the key, which is the rule of a // least-recently-used cache. refreshOnHit bool // evictNewest evicts the newest key of a full cache instead of the oldest. evictNewest bool } // cacheHits counts the accesses that find their key in a cache of the given // capacity under the replacement rule. With refreshOnHit and no evictNewest // it counts like lruHits, which the tests keep equal; the other rules model // wrong solutions and exist only to make distractors. func cacheHits(accesses []int, capacity int, policy cachePolicy) int { // held keeps the cached keys from the oldest entry to the newest. held := make([]int, 0, capacity) hits := 0 for _, key := range accesses { position := slices.Index(held, key) if position >= 0 { hits++ if policy.refreshOnHit { held = append(held[:position], held[position+1:]...) held = append(held, key) } continue } if len(held) == capacity { if policy.evictNewest { held = held[:len(held)-1] } else { held = held[1:] } } held = append(held, key) } return hits } // lruHits counts the accesses that find their key in a least-recently-used // cache of the given capacity. A hit and a miss both make the key the most // recently used one; a miss on a full cache evicts the least recently used // key first. func lruHits(accesses []int, capacity int) int { // recent holds the cached keys from least to most recently used. recent := make([]int, 0, capacity) hits := 0 for _, key := range accesses { position := -1 for index, cached := range recent { if cached == key { position = index break } } switch { case position >= 0: hits++ recent = append(recent[:position], recent[position+1:]...) case len(recent) == capacity: recent = recent[1:] } recent = append(recent, key) } return hits } // Data names: dependencies. func generateDependencyOrder(random *seededRandom, parameters map[string]int32) (map[string]string, string) { tasks := int(parameters["tasks"]) // A hidden shuffle fixes a valid order; links only point forward in it, // so the graph never has a cycle. hidden := make([]int, tasks) for index := range hidden { hidden[index] = index + 1 } for index := tasks - 1; index > 0; index-- { swap := random.below(index + 1) hidden[index], hidden[swap] = hidden[swap], hidden[index] } seen := make(map[[2]int]bool) var links [][2]int var described []string for range parameters["links"] { first, second := random.below(tasks), random.below(tasks) if first == second { continue } if first > second { first, second = second, first } link := [2]int{hidden[first], hidden[second]} if seen[link] { continue } seen[link] = true links = append(links, link) described = append(described, strconv.Itoa(link[0])+"->"+strconv.Itoa(link[1])) } dependencies := "none" if len(described) > 0 { dependencies = strings.Join(described, " ") } return map[string]string{"dependencies": dependencies}, joinInts(smallestDependencyOrder(tasks, links)) } // smallestDependencyOrder returns the lexicographically smallest order of // tasks 1..tasks in which every link {before, after} has before first. The // links must not contain a cycle. func smallestDependencyOrder(tasks int, links [][2]int) []int { pending := make([]int, tasks+1) for _, link := range links { pending[link[1]]++ } done := make([]bool, tasks+1) order := make([]int, 0, tasks) for len(order) < tasks { next := 0 for task := 1; task <= tasks; task++ { if !done[task] && pending[task] == 0 { next = task break } } done[next] = true order = append(order, next) for _, link := range links { if link[0] == next { pending[link[1]]-- } } } return order }