package mapatest import ( "context" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "sort" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/db" "amadan.net/oficina/mapa/internal/mapa" ) // Gate 6, speed at size (spec §11, §6.1): a 10,000-page synthetic // fixture. The warm typeahead target is asserted, measured as server // time through the real handler, Sync and JSON included. The cold wake // (a fresh process: schema check, index built from sealed rows, first // answer) is measured and logged; §6.1 marks its 2 s target unmeasured, // so this test records it and fails only far past it. const ( fixturePages = 10000 warmTarget = 5 * time.Millisecond // coldCeiling is not §6.1's target; it is the line past which the // recorded figure is a regression nobody should ship. coldCeiling = 10 * time.Second ) func openApp(t *testing.T, path string) mapa.Built { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) database, err := db.Open(path, logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { database.Close() }) built, err := mapa.AppForTest(database, testConfig(t, Ana+","+Bo), logger, Bo) if err != nil { t.Fatal(err) } return built } func TestGate6SpeedAtSize(t *testing.T) { path := filepath.Join(t.TempDir(), "mapa.db") seeded := time.Now() first := openApp(t, path) err := mapa.SeedSynthetic(context.Background(), first.Store, Ana, fixturePages) if err != nil { t.Fatal(err) } t.Logf("seeded %d pages in %v", fixturePages, time.Since(seeded)) woken := time.Now() built := openApp(t, path) if code := ask(built, "/search/suggest?q=zz"); code != http.StatusOK { t.Fatalf("first search: %d", code) } cold := time.Since(woken) t.Logf("cold wake to first search answered, at %d pages: %v", fixturePages, cold) if cold > coldCeiling { t.Fatalf("cold wake took %v", cold) } views := pageViews(t, built) t.Logf("page views (backlinks and unlinked mentions included): %d, "+ "p50 %v, p95 %v, max %v", len(views), percentile(views, 50), percentile(views, 95), percentile(views, 100)) if p95 := percentile(views, 95); p95 > pageViewTarget { t.Errorf("page view p95 is %v, over %v", p95, pageViewTarget) } for _, kind := range []string{"/search/suggest", "/links/suggest"} { times := typeahead(built, kind) p50, p95 := percentile(times, 50), percentile(times, 95) t.Logf("%s: %d queries, p50 %v, p95 %v, max %v", kind, len(times), p50, p95, percentile(times, 100)) if p95 > warmTarget { t.Errorf("%s p95 is %v, over §6.1's %v", kind, p95, warmTarget) } } } // pageViewTarget is not in §6.1, which times search; it is the bound the // review asked gate 6 to hold a page view to (review L5), with its // backlinks and unlinked mentions, at 10,000 pages. const pageViewTarget = 50 * time.Millisecond // pageViews times opening 200 team pages, spread across the fixture. func pageViews(t *testing.T, built mapa.Built) []time.Duration { t.Helper() pages, err := built.Index.TeamPages(context.Background()) if err != nil || len(pages) < fixturePages { t.Fatalf("%d pages: %v", len(pages), err) } // The worst case for unlinked mentions: a title of the fixture's two // commonest words, which thousands of pages hold. The intersection // was quadratic in them before review L5. words := mapa.SyntheticWords() common, err := built.Store.CreateTeamPage(context.Background(), Bo, words[0]+" "+words[1], "") if err != nil { t.Fatal(err) } var times []time.Duration for number := 0; number < 200; number++ { href := pages[number*47%len(pages)].Href if number%10 == 0 { href = mapa.PagePath(common) } started := time.Now() if code := ask(built, href); code != http.StatusOK { t.Fatalf("GET %s: %d", href, code) } times = append(times, time.Since(started)) } return times } func ask(built mapa.Built, target string) int { recorder := httptest.NewRecorder() built.Mux.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, target, nil)) return recorder.Code } // typeahead types queries a letter at a time, as a person does, and // times each answer: words of every frequency, titles, and two-word // queries whose last word is still being typed. func typeahead(built mapa.Built, kind string) []time.Duration { words := mapa.SyntheticWords() var queries []string for number := 0; number < 40; number++ { queries = append(queries, words[number*73%len(words)], mapa.SyntheticTitle(number*241%fixturePages)) } for number := 0; number < 10; number++ { queries = append(queries, words[number]+" "+words[number*37+5]) } var times []time.Duration for _, query := range queries { for end := 1; end <= len(query); end++ { target := kind + "?q=" + url.QueryEscape(query[:end]) started := time.Now() ask(built, target) times = append(times, time.Since(started)) } } return times } func percentile(times []time.Duration, rank int) time.Duration { sorted := append([]time.Duration(nil), times...) sort.Slice(sorted, func(left, right int) bool { return sorted[left] < sorted[right] }) at := (len(sorted)*rank + 99) / 100 return sorted[max(0, min(at, len(sorted))-1)] } // The fixture is what it claims: 10,000 team pages that link to each // other, so the gate measures a graph and not a pile of text. func TestTheFixtureLinksPages(t *testing.T) { built := openApp(t, filepath.Join(t.TempDir(), "mapa.db")) mapa.SeedSynthetic(context.Background(), built.Store, Ana, 200) pages, _ := built.Index.TeamPages(context.Background()) links := 0 for _, page := range pages { links += strings.Count(page.Body, "[[") } if len(pages) != 200 || links < 100 { t.Fatalf("%d pages, %d links", len(pages), links) } } // Review M3 follow-up: two processes on one database file, as in a // zero-downtime swap. A write in one reaches the other's index through // its watcher, off-request: the other's reads still do no catch-up. func TestAnotherProcesssWriteArrivesWithoutAReaderPaying(t *testing.T) { path := filepath.Join(t.TempDir(), "mapa.db") writer, reader := openApp(t, path), openApp(t, path) ctx := context.Background() if hits, _ := reader.Index.Search(ctx, mapa.Scope{}, "quillon", 8); len(hits.All()) != 0 { t.Fatal("found before it was written") } if _, err := writer.Store.CreateTeamPage(ctx, Ana, "Quillon", ""); err != nil { t.Fatal(err) } deadline := time.Now().Add(5 * time.Second) for reader.Index.CatchUps() == 0 && time.Now().Before(deadline) { time.Sleep(50 * time.Millisecond) } if reader.Index.CatchUps() == 0 { t.Fatal("the other process's write never reached this index") } before := reader.Index.CatchUps() hits, err := reader.Index.Search(ctx, mapa.Scope{}, "quillon", 8) if err != nil || len(hits.All()) != 1 { t.Fatalf("the write is not found: %+v, %v", hits, err) } if reader.Index.CatchUps() != before { t.Fatal("a read caught the index up") } }