oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapatest
2
3import (
4 "context"
5 "io"
6 "log/slog"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "path/filepath"
11 "sort"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/rastrillo/rastrillo/db"
17
18 "amadan.net/oficina/mapa/internal/mapa"
19)
20
21// Gate 6, speed at size (spec §11, §6.1): a 10,000-page synthetic
22// fixture. The warm typeahead target is asserted, measured as server
23// time through the real handler, Sync and JSON included. The cold wake
24// (a fresh process: schema check, index built from sealed rows, first
25// answer) is measured and logged; §6.1 marks its 2 s target unmeasured,
26// so this test records it and fails only far past it.
27
28const (
29 fixturePages = 10000
30 warmTarget = 5 * time.Millisecond
31 // coldCeiling is not §6.1's target; it is the line past which the
32 // recorded figure is a regression nobody should ship.
33 coldCeiling = 10 * time.Second
34)
35
36func openApp(t *testing.T, path string) mapa.Built {
37 t.Helper()
38 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
39 database, err := db.Open(path, logger)
40 if err != nil {
41 t.Fatal(err)
42 }
43 t.Cleanup(func() { database.Close() })
44 built, err := mapa.AppForTest(database, testConfig(t, Ana+","+Bo),
45 logger, Bo)
46 if err != nil {
47 t.Fatal(err)
48 }
49 return built
50}
51
52func TestGate6SpeedAtSize(t *testing.T) {
53 path := filepath.Join(t.TempDir(), "mapa.db")
54 seeded := time.Now()
55 first := openApp(t, path)
56 err := mapa.SeedSynthetic(context.Background(), first.Store, Ana,
57 fixturePages)
58 if err != nil {
59 t.Fatal(err)
60 }
61 t.Logf("seeded %d pages in %v", fixturePages, time.Since(seeded))
62
63 woken := time.Now()
64 built := openApp(t, path)
65 if code := ask(built, "/search/suggest?q=zz"); code != http.StatusOK {
66 t.Fatalf("first search: %d", code)
67 }
68 cold := time.Since(woken)
69 t.Logf("cold wake to first search answered, at %d pages: %v",
70 fixturePages, cold)
71 if cold > coldCeiling {
72 t.Fatalf("cold wake took %v", cold)
73 }
74 views := pageViews(t, built)
75 t.Logf("page views (backlinks and unlinked mentions included): %d, "+
76 "p50 %v, p95 %v, max %v", len(views), percentile(views, 50),
77 percentile(views, 95), percentile(views, 100))
78 if p95 := percentile(views, 95); p95 > pageViewTarget {
79 t.Errorf("page view p95 is %v, over %v", p95, pageViewTarget)
80 }
81 for _, kind := range []string{"/search/suggest", "/links/suggest"} {
82 times := typeahead(built, kind)
83 p50, p95 := percentile(times, 50), percentile(times, 95)
84 t.Logf("%s: %d queries, p50 %v, p95 %v, max %v", kind, len(times),
85 p50, p95, percentile(times, 100))
86 if p95 > warmTarget {
87 t.Errorf("%s p95 is %v, over §6.1's %v", kind, p95, warmTarget)
88 }
89 }
90}
91
92// pageViewTarget is not in §6.1, which times search; it is the bound the
93// review asked gate 6 to hold a page view to (review L5), with its
94// backlinks and unlinked mentions, at 10,000 pages.
95const pageViewTarget = 50 * time.Millisecond
96
97// pageViews times opening 200 team pages, spread across the fixture.
98func pageViews(t *testing.T, built mapa.Built) []time.Duration {
99 t.Helper()
100 pages, err := built.Index.TeamPages(context.Background())
101 if err != nil || len(pages) < fixturePages {
102 t.Fatalf("%d pages: %v", len(pages), err)
103 }
104 // The worst case for unlinked mentions: a title of the fixture's two
105 // commonest words, which thousands of pages hold. The intersection
106 // was quadratic in them before review L5.
107 words := mapa.SyntheticWords()
108 common, err := built.Store.CreateTeamPage(context.Background(), Bo,
109 words[0]+" "+words[1], "")
110 if err != nil {
111 t.Fatal(err)
112 }
113 var times []time.Duration
114 for number := 0; number < 200; number++ {
115 href := pages[number*47%len(pages)].Href
116 if number%10 == 0 {
117 href = mapa.PagePath(common)
118 }
119 started := time.Now()
120 if code := ask(built, href); code != http.StatusOK {
121 t.Fatalf("GET %s: %d", href, code)
122 }
123 times = append(times, time.Since(started))
124 }
125 return times
126}
127
128func ask(built mapa.Built, target string) int {
129 recorder := httptest.NewRecorder()
130 built.Mux.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet,
131 target, nil))
132 return recorder.Code
133}
134
135// typeahead types queries a letter at a time, as a person does, and
136// times each answer: words of every frequency, titles, and two-word
137// queries whose last word is still being typed.
138func typeahead(built mapa.Built, kind string) []time.Duration {
139 words := mapa.SyntheticWords()
140 var queries []string
141 for number := 0; number < 40; number++ {
142 queries = append(queries, words[number*73%len(words)],
143 mapa.SyntheticTitle(number*241%fixturePages))
144 }
145 for number := 0; number < 10; number++ {
146 queries = append(queries, words[number]+" "+words[number*37+5])
147 }
148 var times []time.Duration
149 for _, query := range queries {
150 for end := 1; end <= len(query); end++ {
151 target := kind + "?q=" + url.QueryEscape(query[:end])
152 started := time.Now()
153 ask(built, target)
154 times = append(times, time.Since(started))
155 }
156 }
157 return times
158}
159
160func percentile(times []time.Duration, rank int) time.Duration {
161 sorted := append([]time.Duration(nil), times...)
162 sort.Slice(sorted, func(left, right int) bool {
163 return sorted[left] < sorted[right]
164 })
165 at := (len(sorted)*rank + 99) / 100
166 return sorted[max(0, min(at, len(sorted))-1)]
167}
168
169// The fixture is what it claims: 10,000 team pages that link to each
170// other, so the gate measures a graph and not a pile of text.
171func TestTheFixtureLinksPages(t *testing.T) {
172 built := openApp(t, filepath.Join(t.TempDir(), "mapa.db"))
173 mapa.SeedSynthetic(context.Background(), built.Store, Ana, 200)
174 pages, _ := built.Index.TeamPages(context.Background())
175 links := 0
176 for _, page := range pages {
177 links += strings.Count(page.Body, "[[")
178 }
179 if len(pages) != 200 || links < 100 {
180 t.Fatalf("%d pages, %d links", len(pages), links)
181 }
182}
183
184// Review M3 follow-up: two processes on one database file, as in a
185// zero-downtime swap. A write in one reaches the other's index through
186// its watcher, off-request: the other's reads still do no catch-up.
187func TestAnotherProcesssWriteArrivesWithoutAReaderPaying(t *testing.T) {
188 path := filepath.Join(t.TempDir(), "mapa.db")
189 writer, reader := openApp(t, path), openApp(t, path)
190 ctx := context.Background()
191 if hits, _ := reader.Index.Search(ctx, mapa.Scope{}, "quillon",
192 8); len(hits.All()) != 0 {
193 t.Fatal("found before it was written")
194 }
195 if _, err := writer.Store.CreateTeamPage(ctx, Ana, "Quillon",
196 ""); err != nil {
197 t.Fatal(err)
198 }
199 deadline := time.Now().Add(5 * time.Second)
200 for reader.Index.CatchUps() == 0 && time.Now().Before(deadline) {
201 time.Sleep(50 * time.Millisecond)
202 }
203 if reader.Index.CatchUps() == 0 {
204 t.Fatal("the other process's write never reached this index")
205 }
206 before := reader.Index.CatchUps()
207 hits, err := reader.Index.Search(ctx, mapa.Scope{}, "quillon", 8)
208 if err != nil || len(hits.All()) != 1 {
209 t.Fatalf("the write is not found: %+v, %v", hits, err)
210 }
211 if reader.Index.CatchUps() != before {
212 t.Fatal("a read caught the index up")
213 }
214}
215