| 1 | package docs_test |
| 2 | |
| 3 | // Live-push latency probe (spec/live-push, 2026-11-26). Not a gate: both |
| 4 | // tests skip unless DOCS_LIVE_PROBE_DIR and DOCS_LIVE_PROBE_ROLE are set by |
| 5 | // native/benchmarks/live-push/run-probe.py. |
| 6 | // |
| 7 | // Role "server" serves the real authenticated application on loopback, |
| 8 | // seeds DOCS_LIVE_PROBE_DOCS documents with DOCS_LIVE_PROBE_SEED, and logs |
| 9 | // every request and every stream write to $DIR/events.jsonl with Unix |
| 10 | // milliseconds, so other processes on this machine (the browser, the native |
| 11 | // XCTest) can line their own timestamps up with it. With |
| 12 | // DOCS_LIVE_PROBE_RTT_MS > 0 the clients are given a loopback TCP proxy |
| 13 | // that holds each chunk for half that in each direction, which is how a |
| 14 | // round trip to the CARLOS edge is stood in for. GET /__probe/stats answers |
| 15 | // the server process's CPU time and allocation counters. |
| 16 | // |
| 17 | // Role "clients" plays N typists, each in its own document, each with one |
| 18 | // watcher, with the upload pacing named by DOCS_LIVE_PROBE_POLICY: |
| 19 | // |
| 20 | // web250 fixtures/save-queue.mjs: a key starts a 250 ms timer (not reset); |
| 21 | // what queues behind a save on the wire goes when it is answered. |
| 22 | // native250 DocsOfflineAccount.pace: the first send after a pause goes at |
| 23 | // once; POST starts are at least 250 ms apart. |
| 24 | // idle<N> send when nothing is on the wire and N ms have passed since the |
| 25 | // last send started; coalesce otherwise (idle0 = send at once). |
| 26 | // |
| 27 | // Watchers follow fixtures/live-updates.mjs: an announced seq above the |
| 28 | // cursor fetches ?since=cursor, one fetch at a time. A sender behaves as its |
| 29 | // platform does with its own announcement: web fetches it if it arrives |
| 30 | // before the POST's answer (noteOwnSeq only adopts afterwards), native holds |
| 31 | // it until the answer. Per key it records when the key was pressed, when its |
| 32 | // batch was sent and answered, when the watcher's stream announced a seq |
| 33 | // that covers it (= when pushed bytes would arrive) and when the watcher's |
| 34 | // fetch for it completed (= today). Results go to $DIR/keys-<label>.csv and |
| 35 | // one summary line in $DIR/summary.jsonl. |
| 36 | |
| 37 | import ( |
| 38 | "bufio" |
| 39 | "bytes" |
| 40 | "context" |
| 41 | "crypto/sha256" |
| 42 | "database/sql" |
| 43 | "encoding/base64" |
| 44 | "encoding/binary" |
| 45 | "encoding/hex" |
| 46 | "encoding/json" |
| 47 | "fmt" |
| 48 | "io" |
| 49 | "math" |
| 50 | "math/rand" |
| 51 | "net" |
| 52 | "net/http" |
| 53 | "net/http/httptest" |
| 54 | "os" |
| 55 | "os/exec" |
| 56 | "path/filepath" |
| 57 | "runtime" |
| 58 | "sort" |
| 59 | "strconv" |
| 60 | "strings" |
| 61 | "sync" |
| 62 | "sync/atomic" |
| 63 | "syscall" |
| 64 | "testing" |
| 65 | "time" |
| 66 | |
| 67 | "github.com/carlosframework/docs/internal/core" |
| 68 | "github.com/carlosframework/docs/internal/docs" |
| 69 | _ "modernc.org/sqlite" |
| 70 | ) |
| 71 | |
| 72 | // probeKeyFingerprint is the content key's fingerprint, as |
| 73 | // content_cipher.go derives it (hex SHA-256 of the key's bytes), which |
| 74 | // MaintainContent wants to activate sealing. |
| 75 | func probeKeyFingerprint(key string) (string, error) { |
| 76 | raw, err := base64.StdEncoding.DecodeString(key) |
| 77 | if err != nil { |
| 78 | return "", err |
| 79 | } |
| 80 | sum := sha256.Sum256(raw) |
| 81 | return hex.EncodeToString(sum[:]), nil |
| 82 | } |
| 83 | |
| 84 | func probeNow() float64 { return float64(time.Now().UnixNano()) / 1e6 } |
| 85 | |
| 86 | func probeEnvInt(name string, def int) int { |
| 87 | if v, err := strconv.Atoi(os.Getenv(name)); err == nil { |
| 88 | return v |
| 89 | } |
| 90 | return def |
| 91 | } |
| 92 | |
| 93 | type probeWriter struct { |
| 94 | http.ResponseWriter |
| 95 | status int |
| 96 | bytes int64 |
| 97 | onData func([]byte) |
| 98 | } |
| 99 | |
| 100 | func (w *probeWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) } |
| 101 | func (w *probeWriter) Write(p []byte) (int, error) { |
| 102 | if w.status == 0 { |
| 103 | w.status = 200 |
| 104 | } |
| 105 | if w.onData != nil { |
| 106 | w.onData(p) |
| 107 | } |
| 108 | n, err := w.ResponseWriter.Write(p) |
| 109 | w.bytes += int64(n) |
| 110 | return n, err |
| 111 | } |
| 112 | func (w *probeWriter) Flush() { |
| 113 | if f, ok := w.ResponseWriter.(http.Flusher); ok { |
| 114 | f.Flush() |
| 115 | } |
| 116 | } |
| 117 | func (w *probeWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 118 | |
| 119 | // delayProxy forwards every accepted connection to upstream, holding each |
| 120 | // chunk for oneWay in each direction, in order. |
| 121 | func delayProxy(l net.Listener, upstream string, oneWay time.Duration) { |
| 122 | for { |
| 123 | c, err := l.Accept() |
| 124 | if err != nil { |
| 125 | return |
| 126 | } |
| 127 | go func() { |
| 128 | u, err := net.Dial("tcp", upstream) |
| 129 | if err != nil { |
| 130 | c.Close() |
| 131 | return |
| 132 | } |
| 133 | go delayPump(c, u, oneWay) |
| 134 | go delayPump(u, c, oneWay) |
| 135 | }() |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | func delayPump(src, dst net.Conn, d time.Duration) { |
| 140 | type chunk struct { |
| 141 | b []byte |
| 142 | at time.Time |
| 143 | } |
| 144 | ch := make(chan chunk, 1<<14) |
| 145 | go func() { |
| 146 | for c := range ch { |
| 147 | time.Sleep(time.Until(c.at)) |
| 148 | if _, err := dst.Write(c.b); err != nil { |
| 149 | break |
| 150 | } |
| 151 | } |
| 152 | if tc, ok := dst.(*net.TCPConn); ok { |
| 153 | tc.CloseWrite() |
| 154 | } else { |
| 155 | dst.Close() |
| 156 | } |
| 157 | for range ch { |
| 158 | } |
| 159 | }() |
| 160 | buf := make([]byte, 64<<10) |
| 161 | for { |
| 162 | n, err := src.Read(buf) |
| 163 | if n > 0 { |
| 164 | ch <- chunk{append([]byte(nil), buf[:n]...), time.Now().Add(d)} |
| 165 | } |
| 166 | if err != nil { |
| 167 | close(ch) |
| 168 | return |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | func TestLivePushProbeServer(t *testing.T) { |
| 174 | dir := os.Getenv("DOCS_LIVE_PROBE_DIR") |
| 175 | if dir == "" || os.Getenv("DOCS_LIVE_PROBE_ROLE") != "server" { |
| 176 | t.Skip("Run native/benchmarks/live-push/run-probe.py") |
| 177 | } |
| 178 | ndocs := probeEnvInt("DOCS_LIVE_PROBE_DOCS", 1) |
| 179 | rtt := probeEnvInt("DOCS_LIVE_PROBE_RTT_MS", 0) |
| 180 | |
| 181 | appListener, err := net.Listen("tcp", "127.0.0.1:0") |
| 182 | if err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | defer appListener.Close() |
| 186 | origin := "http://" + appListener.Addr().String() |
| 187 | var proxyListener net.Listener |
| 188 | if rtt > 0 { |
| 189 | proxyListener, err = net.Listen("tcp", "127.0.0.1:0") |
| 190 | if err != nil { |
| 191 | t.Fatal(err) |
| 192 | } |
| 193 | defer proxyListener.Close() |
| 194 | origin = "http://" + proxyListener.Addr().String() |
| 195 | } |
| 196 | cfg := docs.Config{AllowedAddresses: "probe@example.com", Origin: origin, WarmHandle: os.Getenv("DOCS_LIVE_PROBE_WARM") == "1", LivePush: os.Getenv("DOCS_LIVE_PROBE_PUSH") == "1"} |
| 197 | if p := os.Getenv("DOCS_LIVE_PROBE_DB"); p != "" { |
| 198 | // A known path, for a replicator to watch (Litestream, slice 1b). |
| 199 | cfg.DBPath = p |
| 200 | } |
| 201 | if os.Getenv("DOCS_LIVE_PROBE_SEAL") == "1" { |
| 202 | // Sealed rows, as production stores them. |
| 203 | if cfg.DBPath == "" { |
| 204 | cfg.DBPath = filepath.Join(t.TempDir(), "docs.db") |
| 205 | } |
| 206 | cfg.Env = "development" |
| 207 | cfg.ContentKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{71}, 32)) |
| 208 | first, err := docs.New(cfg) |
| 209 | if err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | first.Close() |
| 213 | fp, err := probeKeyFingerprint(cfg.ContentKey) |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | if err := docs.MaintainContent(context.Background(), docs.ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: cfg.ContentKey, ExpectedFingerprint: fp}); err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | } |
| 221 | app, err := docs.NewForTestWith(t, cfg) |
| 222 | if err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | if n := probeEnvInt("DOCS_LIVE_PROBE_LATE_LIMIT", 0); n > 0 { |
| 226 | // The probe's clients share one session; real typists each have one. |
| 227 | app.TestSetLateLimit(n) |
| 228 | } |
| 229 | cookies := signInCookies(t, app, "probe@example.com") |
| 230 | var seed []byte |
| 231 | if path := os.Getenv("DOCS_LIVE_PROBE_SEED"); path != "" { |
| 232 | if seed, err = os.ReadFile(path); err != nil { |
| 233 | t.Fatal(err) |
| 234 | } |
| 235 | } |
| 236 | var sqids []string |
| 237 | for i := 0; i < ndocs; i++ { |
| 238 | create := httptest.NewRequest("POST", "/documents", strings.NewReader(fmt.Sprintf("title=Live+push+%d", i))) |
| 239 | create.Header.Set("Origin", origin) |
| 240 | create.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 241 | for _, c := range cookies { |
| 242 | create.AddCookie(c) |
| 243 | } |
| 244 | rec := httptest.NewRecorder() |
| 245 | app.Handler().ServeHTTP(rec, create) |
| 246 | if rec.Code != http.StatusSeeOther { |
| 247 | t.Fatalf("create: status %d", rec.Code) |
| 248 | } |
| 249 | sqid := strings.TrimPrefix(rec.Header().Get("Location"), "/d/") |
| 250 | if seed != nil { |
| 251 | post := httptest.NewRequest("POST", "/d/"+sqid+"/updates", bytes.NewReader(seed)) |
| 252 | post.Header.Set("Origin", origin) |
| 253 | post.Header.Set("Content-Type", "application/octet-stream") |
| 254 | for _, c := range cookies { |
| 255 | post.AddCookie(c) |
| 256 | } |
| 257 | rec := httptest.NewRecorder() |
| 258 | app.Handler().ServeHTTP(rec, post) |
| 259 | if rec.Code/100 != 2 { |
| 260 | t.Fatalf("seed: status %d %s", rec.Code, rec.Body.String()) |
| 261 | } |
| 262 | } |
| 263 | sqids = append(sqids, sqid) |
| 264 | } |
| 265 | |
| 266 | logFile, err := os.OpenFile(filepath.Join(dir, "events.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) |
| 267 | if err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | defer logFile.Close() |
| 271 | logs := bufio.NewWriterSize(logFile, 1<<20) |
| 272 | var mu sync.Mutex |
| 273 | logLine := func(v map[string]any) { |
| 274 | mu.Lock() |
| 275 | json.NewEncoder(logs).Encode(v) |
| 276 | mu.Unlock() |
| 277 | } |
| 278 | inner := app.Handler() |
| 279 | handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 280 | if r.URL.Path == "/__probe/stats" { |
| 281 | var ru syscall.Rusage |
| 282 | syscall.Getrusage(syscall.RUSAGE_SELF, &ru) |
| 283 | var ms runtime.MemStats |
| 284 | runtime.ReadMemStats(&ms) |
| 285 | mu.Lock() |
| 286 | logs.Flush() |
| 287 | mu.Unlock() |
| 288 | json.NewEncoder(w).Encode(map[string]any{ |
| 289 | "cpu_ms": float64(ru.Utime.Nano()+ru.Stime.Nano()) / 1e6, |
| 290 | "total_alloc": ms.TotalAlloc, "mallocs": ms.Mallocs, "num_gc": ms.NumGC, |
| 291 | "heap_inuse": ms.HeapInuse, "goroutines": runtime.NumGoroutine(), "max_rss": ru.Maxrss, |
| 292 | }) |
| 293 | return |
| 294 | } |
| 295 | start := probeNow() |
| 296 | pw := &probeWriter{ResponseWriter: w} |
| 297 | if strings.HasSuffix(r.URL.Path, "/stream") { |
| 298 | uri := r.URL.RequestURI() |
| 299 | logLine(map[string]any{"ev": "open", "t": start, "path": uri}) |
| 300 | pw.onData = func(p []byte) { |
| 301 | s := string(p) |
| 302 | if i := strings.Index(s, "data: "); i >= 0 { |
| 303 | rest := s[i+6:] |
| 304 | if j := strings.IndexByte(rest, '\n'); j >= 0 { |
| 305 | rest = rest[:j] |
| 306 | } |
| 307 | logLine(map[string]any{"ev": "sse", "t": probeNow(), "path": uri, "seq": rest, "bytes": len(p)}) |
| 308 | } else { |
| 309 | logLine(map[string]any{"ev": "ping", "t": probeNow(), "path": uri, "bytes": len(p)}) |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | var reqBytes int64 |
| 314 | if r.ContentLength > 0 { |
| 315 | reqBytes = r.ContentLength |
| 316 | } |
| 317 | inner.ServeHTTP(pw, r) |
| 318 | logLine(map[string]any{"ev": "req", "t": start, "end": probeNow(), "method": r.Method, "path": r.URL.RequestURI(), |
| 319 | "req_bytes": reqBytes, "resp_bytes": pw.bytes, "status": pw.status, "seq": pw.Header().Get("Docs-Seq")}) |
| 320 | }) |
| 321 | server := httptest.NewUnstartedServer(handler) |
| 322 | server.Listener.Close() |
| 323 | server.Listener = appListener |
| 324 | server.Start() |
| 325 | defer server.Close() |
| 326 | if proxyListener != nil { |
| 327 | go delayProxy(proxyListener, appListener.Addr().String(), time.Duration(rtt)*time.Millisecond/2) |
| 328 | } |
| 329 | cookie := make([]string, 0, len(cookies)) |
| 330 | for _, c := range cookies { |
| 331 | cookie = append(cookie, c.Name+"="+c.Value) |
| 332 | } |
| 333 | connCfg := map[string]any{"origin": origin, "direct": "http://" + appListener.Addr().String(), "sqids": sqids, |
| 334 | "cookie": strings.Join(cookie, "; "), "cookies": cookies, "rtt_ms": rtt, "pid": os.Getpid()} |
| 335 | data, _ := json.Marshal(connCfg) |
| 336 | if err := os.WriteFile(filepath.Join(dir, "connection.json"), data, 0600); err != nil { |
| 337 | t.Fatal(err) |
| 338 | } |
| 339 | deadline := time.Now().Add(60 * time.Minute) |
| 340 | for time.Now().Before(deadline) { |
| 341 | if _, err := os.Stat(filepath.Join(dir, "done")); err == nil { |
| 342 | mu.Lock() |
| 343 | logs.Flush() |
| 344 | mu.Unlock() |
| 345 | return |
| 346 | } |
| 347 | time.Sleep(20 * time.Millisecond) |
| 348 | mu.Lock() |
| 349 | logs.Flush() |
| 350 | mu.Unlock() |
| 351 | } |
| 352 | t.Fatal("probe never completed") |
| 353 | } |
| 354 | |
| 355 | type probeConn struct { |
| 356 | Origin string `json:"origin"` |
| 357 | Direct string `json:"direct"` |
| 358 | Sqids []string `json:"sqids"` |
| 359 | Cookie string `json:"cookie"` |
| 360 | RTT int `json:"rtt_ms"` |
| 361 | } |
| 362 | |
| 363 | type probeBatch struct { |
| 364 | lo, hi int |
| 365 | send, ack float64 |
| 366 | seq int64 |
| 367 | status int |
| 368 | reqBytes int |
| 369 | echoFetched bool |
| 370 | answeredLate bool |
| 371 | } |
| 372 | |
| 373 | type probeKey struct { |
| 374 | at float64 |
| 375 | batch *probeBatch |
| 376 | } |
| 377 | |
| 378 | // probeClient is one tab or app: its own connection pool, cursor and |
| 379 | // fetch serialization (live-updates.mjs drain()). |
| 380 | type probeClient struct { |
| 381 | conn *probeConn |
| 382 | sqid string |
| 383 | http *http.Client |
| 384 | native bool |
| 385 | mu sync.Mutex |
| 386 | cursor int64 |
| 387 | fetching bool |
| 388 | pending bool |
| 389 | posting bool |
| 390 | held int64 |
| 391 | events [][2]float64 // (t, seq) per announcement |
| 392 | fetches [][2]float64 // (t done, Docs-Seq) per fetch |
| 393 | fetchN int64 |
| 394 | fetchByte int64 |
| 395 | push bool |
| 396 | streamID string |
| 397 | counter int |
| 398 | sentOwn map[string]bool |
| 399 | pushN int64 |
| 400 | ownN int64 |
| 401 | } |
| 402 | |
| 403 | func newProbeClient(conn *probeConn, sqid string, native bool) *probeClient { |
| 404 | tr := &http.Transport{MaxIdleConnsPerHost: 8, IdleConnTimeout: 90 * time.Second} |
| 405 | return &probeClient{conn: conn, sqid: sqid, http: &http.Client{Transport: tr}, native: native} |
| 406 | } |
| 407 | |
| 408 | func (c *probeClient) request(method, path string, body []byte) (*http.Response, []byte, error) { |
| 409 | var rd io.Reader |
| 410 | if body != nil { |
| 411 | rd = bytes.NewReader(body) |
| 412 | } |
| 413 | req, err := http.NewRequest(method, c.conn.Origin+path, rd) |
| 414 | if err != nil { |
| 415 | return nil, nil, err |
| 416 | } |
| 417 | req.Header.Set("Cookie", c.conn.Cookie) |
| 418 | if method == "POST" { |
| 419 | req.Header.Set("Origin", c.conn.Origin) |
| 420 | req.Header.Set("Content-Type", "application/octet-stream") |
| 421 | c.mu.Lock() |
| 422 | if c.push && c.streamID != "" { |
| 423 | c.counter++ |
| 424 | n := strconv.Itoa(c.counter) |
| 425 | if c.sentOwn == nil { |
| 426 | c.sentOwn = map[string]bool{} |
| 427 | } |
| 428 | c.sentOwn[n] = true |
| 429 | req.Header.Set("Docs-Stream", c.streamID+"."+n) |
| 430 | } |
| 431 | c.mu.Unlock() |
| 432 | } |
| 433 | res, err := c.http.Do(req) |
| 434 | if err != nil { |
| 435 | return nil, nil, err |
| 436 | } |
| 437 | data, err := io.ReadAll(res.Body) |
| 438 | res.Body.Close() |
| 439 | return res, data, err |
| 440 | } |
| 441 | |
| 442 | func (c *probeClient) noteOwnSeq(seq int64) { |
| 443 | c.mu.Lock() |
| 444 | if seq == c.cursor+1 { |
| 445 | c.cursor = seq |
| 446 | } |
| 447 | c.mu.Unlock() |
| 448 | } |
| 449 | |
| 450 | func (c *probeClient) announce(seq int64) { |
| 451 | c.mu.Lock() |
| 452 | c.events = append(c.events, [2]float64{probeNow(), float64(seq)}) |
| 453 | if seq <= c.cursor { |
| 454 | c.mu.Unlock() |
| 455 | return |
| 456 | } |
| 457 | if c.native && c.posting && seq == c.cursor+1 { |
| 458 | if seq > c.held { |
| 459 | c.held = seq |
| 460 | } |
| 461 | c.mu.Unlock() |
| 462 | return |
| 463 | } |
| 464 | c.mu.Unlock() |
| 465 | c.drain() |
| 466 | } |
| 467 | |
| 468 | func (c *probeClient) drain() { |
| 469 | c.mu.Lock() |
| 470 | if c.fetching { |
| 471 | c.pending = true |
| 472 | c.mu.Unlock() |
| 473 | return |
| 474 | } |
| 475 | c.fetching = true |
| 476 | from := c.cursor |
| 477 | c.mu.Unlock() |
| 478 | go func() { |
| 479 | res, data, err := c.request("GET", fmt.Sprintf("/d/%s/updates?since=%d", c.sqid, from), nil) |
| 480 | c.mu.Lock() |
| 481 | if err == nil && res.StatusCode == 200 { |
| 482 | seq, _ := strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64) |
| 483 | c.fetches = append(c.fetches, [2]float64{probeNow(), float64(seq)}) |
| 484 | c.fetchN++ |
| 485 | c.fetchByte += int64(len(data)) |
| 486 | if seq > c.cursor { |
| 487 | c.cursor = seq |
| 488 | } |
| 489 | } |
| 490 | c.fetching = false |
| 491 | again := c.pending |
| 492 | c.pending = false |
| 493 | c.mu.Unlock() |
| 494 | if again { |
| 495 | c.drain() |
| 496 | } |
| 497 | }() |
| 498 | } |
| 499 | |
| 500 | // frame handles a push-stream event (spec §3.1): push and own advance the |
| 501 | // cursor when exactly next; anything else fetches. |
| 502 | func (c *probeClient) frame(event, data string) { |
| 503 | now := probeNow() |
| 504 | parts := strings.SplitN(data, " ", 2) |
| 505 | seq, _ := strconv.ParseInt(parts[0], 10, 64) |
| 506 | c.mu.Lock() |
| 507 | switch event { |
| 508 | case "hello": |
| 509 | c.streamID = parts[0] |
| 510 | c.mu.Unlock() |
| 511 | return |
| 512 | case "push", "own": |
| 513 | c.events = append(c.events, [2]float64{now, float64(seq)}) |
| 514 | ok := seq == c.cursor+1 && !c.fetching |
| 515 | if event == "own" { |
| 516 | ok = ok && len(parts) == 2 && c.sentOwn[parts[1]] |
| 517 | c.ownN++ |
| 518 | } else { |
| 519 | c.pushN++ |
| 520 | } |
| 521 | if ok { |
| 522 | c.cursor = seq |
| 523 | c.fetches = append(c.fetches, [2]float64{now, float64(seq)}) |
| 524 | c.mu.Unlock() |
| 525 | return |
| 526 | } |
| 527 | if seq <= c.cursor { |
| 528 | c.mu.Unlock() |
| 529 | return |
| 530 | } |
| 531 | c.mu.Unlock() |
| 532 | c.drain() |
| 533 | return |
| 534 | } |
| 535 | c.mu.Unlock() |
| 536 | c.announce(seq) |
| 537 | } |
| 538 | |
| 539 | func (c *probeClient) listen(stop <-chan struct{}, tag string) { |
| 540 | go func() { |
| 541 | url := c.conn.Origin + "/d/" + c.sqid + "/stream?probe=" + tag |
| 542 | if c.push { |
| 543 | c.mu.Lock() |
| 544 | url += fmt.Sprintf("&push=1&since=%d", c.cursor) |
| 545 | c.mu.Unlock() |
| 546 | } |
| 547 | req, _ := http.NewRequest("GET", url, nil) |
| 548 | req.Header.Set("Cookie", c.conn.Cookie) |
| 549 | tr := &http.Transport{} |
| 550 | res, err := (&http.Client{Transport: tr}).Do(req) |
| 551 | if err != nil { |
| 552 | return |
| 553 | } |
| 554 | go func() { <-stop; res.Body.Close() }() |
| 555 | sc := bufio.NewScanner(res.Body) |
| 556 | sc.Buffer(make([]byte, 64<<10), 1<<20) |
| 557 | event, data := "", "" |
| 558 | for sc.Scan() { |
| 559 | line := sc.Text() |
| 560 | switch { |
| 561 | case strings.HasPrefix(line, "event:"): |
| 562 | event = strings.TrimSpace(line[6:]) |
| 563 | case strings.HasPrefix(line, "data:"): |
| 564 | data = strings.TrimSpace(line[5:]) |
| 565 | case line == "": |
| 566 | if c.push && event != "" { |
| 567 | c.frame(event, data) |
| 568 | } else if seq, err := strconv.ParseInt(data, 10, 64); err == nil && data != "" { |
| 569 | c.announce(seq) |
| 570 | } |
| 571 | event, data = "", "" |
| 572 | } |
| 573 | } |
| 574 | }() |
| 575 | } |
| 576 | |
| 577 | func loadProbeUpdates(path string) (map[[2]int][]byte, error) { |
| 578 | data, err := os.ReadFile(path) |
| 579 | if err != nil { |
| 580 | return nil, err |
| 581 | } |
| 582 | out := map[[2]int][]byte{} |
| 583 | for len(data) >= 12 { |
| 584 | lo, hi, n := binary.LittleEndian.Uint32(data), binary.LittleEndian.Uint32(data[4:]), binary.LittleEndian.Uint32(data[8:]) |
| 585 | out[[2]int{int(lo), int(hi)}] = data[12 : 12+n] |
| 586 | data = data[12+n:] |
| 587 | } |
| 588 | return out, nil |
| 589 | } |
| 590 | |
| 591 | // probeSchedule is one typist's key times (ms from start): 60 ms plus an |
| 592 | // exponential with mean meanMs-60, and a 0.7–1.5 s pause every 30–60 keys. |
| 593 | func probeSchedule(rng *rand.Rand, keys int, meanMs float64) []float64 { |
| 594 | out := make([]float64, keys) |
| 595 | at, nextPause := 0.0, 30+rng.Intn(30) |
| 596 | for k := range out { |
| 597 | out[k] = at |
| 598 | at += 60 + rng.ExpFloat64()*(meanMs-60) |
| 599 | if k == nextPause { |
| 600 | at += 700 + rng.Float64()*800 |
| 601 | nextPause += 30 + rng.Intn(30) |
| 602 | } |
| 603 | } |
| 604 | return out |
| 605 | } |
| 606 | |
| 607 | func probePercentile(xs []float64, p float64) float64 { |
| 608 | if len(xs) == 0 { |
| 609 | return math.NaN() |
| 610 | } |
| 611 | s := append([]float64(nil), xs...) |
| 612 | sort.Float64s(s) |
| 613 | i := int(math.Ceil(p*float64(len(s)))) - 1 |
| 614 | if i < 0 { |
| 615 | i = 0 |
| 616 | } |
| 617 | return s[i] |
| 618 | } |
| 619 | |
| 620 | func TestLivePushProbeClients(t *testing.T) { |
| 621 | dir := os.Getenv("DOCS_LIVE_PROBE_DIR") |
| 622 | if dir == "" || os.Getenv("DOCS_LIVE_PROBE_ROLE") != "clients" { |
| 623 | t.Skip("Run native/benchmarks/live-push/run-probe.py") |
| 624 | } |
| 625 | data, err := os.ReadFile(filepath.Join(dir, "connection.json")) |
| 626 | if err != nil { |
| 627 | t.Fatal(err) |
| 628 | } |
| 629 | var conn probeConn |
| 630 | if err := json.Unmarshal(data, &conn); err != nil { |
| 631 | t.Fatal(err) |
| 632 | } |
| 633 | policy := os.Getenv("DOCS_LIVE_PROBE_POLICY") |
| 634 | typists := probeEnvInt("DOCS_LIVE_PROBE_TYPISTS", 1) |
| 635 | keys := probeEnvInt("DOCS_LIVE_PROBE_KEYS", 200) |
| 636 | mean := float64(probeEnvInt("DOCS_LIVE_PROBE_MEAN_MS", 150)) |
| 637 | window := probeEnvInt("DOCS_LIVE_PROBE_WINDOW", 24) |
| 638 | label := os.Getenv("DOCS_LIVE_PROBE_LABEL") |
| 639 | updatesDir := os.Getenv("DOCS_LIVE_PROBE_UPDATES") |
| 640 | native := policy == "native250" |
| 641 | var floor float64 |
| 642 | trailing := false |
| 643 | switch { |
| 644 | case policy == "web250": |
| 645 | trailing, floor = true, 250 |
| 646 | case policy == "native250": |
| 647 | floor = 250 |
| 648 | case strings.HasPrefix(policy, "idle"): |
| 649 | floor, _ = strconv.ParseFloat(strings.TrimPrefix(policy, "idle"), 64) |
| 650 | default: |
| 651 | t.Fatalf("unknown policy %q", policy) |
| 652 | } |
| 653 | if shared := probeEnvInt("DOCS_LIVE_PROBE_SHARED", 0); shared == 0 && typists > len(conn.Sqids) { |
| 654 | t.Fatalf("%d typists, %d documents", typists, len(conn.Sqids)) |
| 655 | } |
| 656 | stats := func() map[string]float64 { |
| 657 | res, err := http.Get(conn.Direct + "/__probe/stats") |
| 658 | if err != nil { |
| 659 | t.Fatal(err) |
| 660 | } |
| 661 | defer res.Body.Close() |
| 662 | var m map[string]float64 |
| 663 | json.NewDecoder(res.Body).Decode(&m) |
| 664 | return m |
| 665 | } |
| 666 | |
| 667 | stop := make(chan struct{}) |
| 668 | type typist struct { |
| 669 | sender *probeClient |
| 670 | watchers []*probeClient |
| 671 | keys []probeKey |
| 672 | batches []*probeBatch |
| 673 | } |
| 674 | push := os.Getenv("DOCS_LIVE_PROBE_PUSH") == "1" |
| 675 | shared := probeEnvInt("DOCS_LIVE_PROBE_SHARED", 0) // >0: every typist in one document, with this many watchers |
| 676 | open := func(sqid string, native bool, tag string) *probeClient { |
| 677 | c := newProbeClient(&conn, sqid, native) |
| 678 | c.push = push |
| 679 | res, _, err := c.request("GET", "/d/"+sqid+"/updates", nil) |
| 680 | if err != nil { |
| 681 | t.Fatal(err) |
| 682 | } |
| 683 | c.cursor, _ = strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64) |
| 684 | c.listen(stop, tag) |
| 685 | return c |
| 686 | } |
| 687 | all := make([]*typist, typists) |
| 688 | var sharedWatchers []*probeClient |
| 689 | for w := 0; w < shared; w++ { |
| 690 | sharedWatchers = append(sharedWatchers, open(conn.Sqids[0], false, "watcher")) |
| 691 | } |
| 692 | for i := range all { |
| 693 | sqid := conn.Sqids[0] |
| 694 | if shared == 0 { |
| 695 | sqid = conn.Sqids[i] |
| 696 | } |
| 697 | ty := &typist{sender: open(sqid, native, "sender")} |
| 698 | if shared > 0 { |
| 699 | ty.watchers = sharedWatchers |
| 700 | } else { |
| 701 | ty.watchers = []*probeClient{open(sqid, false, "watcher")} |
| 702 | } |
| 703 | all[i] = ty |
| 704 | } |
| 705 | time.Sleep(1500 * time.Millisecond) // connect-time events settle |
| 706 | before := stats() |
| 707 | t0 := probeNow() |
| 708 | |
| 709 | var wg sync.WaitGroup |
| 710 | var failed atomic.Int64 |
| 711 | for i, ty := range all { |
| 712 | updates, err := loadProbeUpdates(filepath.Join(updatesDir, fmt.Sprintf("t%d.bin", i))) |
| 713 | if err != nil { |
| 714 | t.Fatal(err) |
| 715 | } |
| 716 | sched := probeSchedule(rand.New(rand.NewSource(int64(1000+i))), keys, mean) |
| 717 | ty.keys = make([]probeKey, keys) |
| 718 | wg.Add(1) |
| 719 | go func(ty *typist) { |
| 720 | defer wg.Done() |
| 721 | keyCh := make(chan int) |
| 722 | answerCh := make(chan *probeBatch) |
| 723 | go func() { |
| 724 | start := time.Now() |
| 725 | for k, ms := range sched { |
| 726 | time.Sleep(time.Until(start.Add(time.Duration(ms * float64(time.Millisecond))))) |
| 727 | keyCh <- k |
| 728 | } |
| 729 | close(keyCh) |
| 730 | }() |
| 731 | queueLo, queueHi := 0, -1 // keys typed and not yet sent |
| 732 | var inFlight *probeBatch |
| 733 | var timer *time.Timer |
| 734 | var timerC <-chan time.Time |
| 735 | lastSend := -1e18 |
| 736 | send := func() { |
| 737 | if inFlight != nil || queueHi < queueLo { |
| 738 | return |
| 739 | } |
| 740 | if timer != nil { |
| 741 | timer.Stop() |
| 742 | timer, timerC = nil, nil |
| 743 | } |
| 744 | hi := queueHi |
| 745 | if hi-queueLo+1 > window { |
| 746 | hi = queueLo + window - 1 |
| 747 | } |
| 748 | b := &probeBatch{lo: queueLo, hi: hi, send: probeNow()} |
| 749 | for k := queueLo; k <= hi; k++ { |
| 750 | ty.keys[k].batch = b |
| 751 | } |
| 752 | queueLo = hi + 1 |
| 753 | body := updates[[2]int{b.lo, b.hi}] |
| 754 | b.reqBytes = len(body) |
| 755 | lastSend = b.send |
| 756 | inFlight = b |
| 757 | ty.batches = append(ty.batches, b) |
| 758 | ty.sender.mu.Lock() |
| 759 | ty.sender.posting = true |
| 760 | ty.sender.mu.Unlock() |
| 761 | go func() { |
| 762 | res, _, err := ty.sender.request("POST", "/d/"+ty.sender.sqid+"/updates", body) |
| 763 | b.ack = probeNow() |
| 764 | if err != nil { |
| 765 | failed.Add(1) |
| 766 | } else { |
| 767 | b.status = res.StatusCode |
| 768 | b.seq, _ = strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64) |
| 769 | } |
| 770 | answerCh <- b |
| 771 | }() |
| 772 | } |
| 773 | arm := func(at float64) { |
| 774 | if timer != nil { |
| 775 | return |
| 776 | } |
| 777 | d := time.Duration((at - probeNow()) * float64(time.Millisecond)) |
| 778 | if d < 0 { |
| 779 | d = 0 |
| 780 | } |
| 781 | timer = time.NewTimer(d) |
| 782 | timerC = timer.C |
| 783 | } |
| 784 | // maybeSend applies the policy when something is queued and nothing is on the wire. |
| 785 | maybeSend := func(answered bool) { |
| 786 | if inFlight != nil || queueHi < queueLo { |
| 787 | return |
| 788 | } |
| 789 | if trailing { |
| 790 | if answered { |
| 791 | send() |
| 792 | } else { |
| 793 | arm(probeNow() + floor) |
| 794 | } |
| 795 | return |
| 796 | } |
| 797 | if probeNow()-lastSend >= floor { |
| 798 | send() |
| 799 | } else { |
| 800 | arm(lastSend + floor) |
| 801 | } |
| 802 | } |
| 803 | keysOpen := true |
| 804 | for keysOpen || inFlight != nil || queueHi >= queueLo { |
| 805 | select { |
| 806 | case k, ok := <-keyCh: |
| 807 | if !ok { |
| 808 | keysOpen = false |
| 809 | keyCh = nil |
| 810 | if inFlight == nil && queueHi >= queueLo && timer == nil { |
| 811 | maybeSend(false) |
| 812 | } |
| 813 | continue |
| 814 | } |
| 815 | ty.keys[k].at = probeNow() |
| 816 | queueHi = k |
| 817 | maybeSend(false) |
| 818 | case <-timerC: |
| 819 | timer, timerC = nil, nil |
| 820 | send() |
| 821 | case b := <-answerCh: |
| 822 | inFlight = nil |
| 823 | s := ty.sender |
| 824 | s.mu.Lock() |
| 825 | s.posting = false |
| 826 | held := s.held |
| 827 | s.held = 0 |
| 828 | s.mu.Unlock() |
| 829 | if b.status/100 == 2 { |
| 830 | s.noteOwnSeq(b.seq) |
| 831 | } |
| 832 | if held > 0 { |
| 833 | s.mu.Lock() |
| 834 | cur := s.cursor |
| 835 | s.mu.Unlock() |
| 836 | if held > cur { |
| 837 | s.drain() |
| 838 | } |
| 839 | } |
| 840 | maybeSend(true) |
| 841 | } |
| 842 | } |
| 843 | }(ty) |
| 844 | } |
| 845 | wg.Wait() |
| 846 | typed := probeNow() |
| 847 | time.Sleep(2 * time.Second) |
| 848 | after := stats() |
| 849 | close(stop) |
| 850 | |
| 851 | // Per key: the watcher's first announcement / fetch covering its batch's seq. |
| 852 | var pace, post, announce, fetchAfter, viaFetch, viaPush []float64 |
| 853 | var posts, sends int |
| 854 | var watcherFetches, senderFetches, events int64 |
| 855 | var reqBytes int |
| 856 | csvPath := filepath.Join(dir, "keys-"+label+".csv") |
| 857 | csv, err := os.Create(csvPath) |
| 858 | if err != nil { |
| 859 | t.Fatal(err) |
| 860 | } |
| 861 | fmt.Fprintln(csv, "typist,key,at,send,ack,seq,announced,fetched") |
| 862 | var pushes, owns int64 |
| 863 | counted := map[*probeClient]bool{} |
| 864 | for i, ty := range all { |
| 865 | ty.sender.mu.Lock() |
| 866 | senderFetches += ty.sender.fetchN |
| 867 | owns += ty.sender.ownN |
| 868 | ty.sender.mu.Unlock() |
| 869 | for _, b := range ty.batches { |
| 870 | posts++ |
| 871 | reqBytes += b.reqBytes |
| 872 | } |
| 873 | sends += len(ty.batches) |
| 874 | for _, w := range ty.watchers { |
| 875 | w.mu.Lock() |
| 876 | evs, fs := append([][2]float64(nil), w.events...), append([][2]float64(nil), w.fetches...) |
| 877 | if !counted[w] { |
| 878 | counted[w] = true |
| 879 | watcherFetches += w.fetchN |
| 880 | events += int64(len(evs)) |
| 881 | pushes += w.pushN |
| 882 | } |
| 883 | w.mu.Unlock() |
| 884 | first := func(list [][2]float64, seq int64, after float64) float64 { |
| 885 | for _, e := range list { |
| 886 | if e[1] >= float64(seq) && e[0] >= after { |
| 887 | return e[0] |
| 888 | } |
| 889 | } |
| 890 | return math.NaN() |
| 891 | } |
| 892 | for k, key := range ty.keys { |
| 893 | b := key.batch |
| 894 | if b == nil || b.seq == 0 { |
| 895 | continue |
| 896 | } |
| 897 | ann := first(evs, b.seq, b.send) |
| 898 | got := first(fs, b.seq, b.send) |
| 899 | fmt.Fprintf(csv, "%d,%d,%.3f,%.3f,%.3f,%d,%.3f,%.3f\n", i, k, key.at, b.send, b.ack, b.seq, ann, got) |
| 900 | pace = append(pace, b.send-key.at) |
| 901 | post = append(post, b.ack-b.send) |
| 902 | announce = append(announce, ann-b.send) |
| 903 | fetchAfter = append(fetchAfter, got-ann) |
| 904 | viaFetch = append(viaFetch, got-key.at) |
| 905 | viaPush = append(viaPush, ann-key.at) |
| 906 | } |
| 907 | } |
| 908 | } |
| 909 | csv.Close() |
| 910 | seconds := (typed - t0) / 1000 |
| 911 | pp := func(xs []float64) [2]float64 { return [2]float64{probePercentile(xs, 0.5), probePercentile(xs, 0.95)} } |
| 912 | summary := map[string]any{ |
| 913 | "label": label, "policy": policy, "typists": typists, "keys": keys, "rtt_ms": conn.RTT, "mean_ms": mean, |
| 914 | "seconds": seconds, "failed_posts": failed.Load(), |
| 915 | "pace": pp(pace), "post_rtt": pp(post), "send_to_announce": pp(announce), "announce_to_fetched": pp(fetchAfter), |
| 916 | "key_to_fetched": pp(viaFetch), "key_to_announced": pp(viaPush), |
| 917 | "posts_per_s_per_typist": float64(posts) / seconds / float64(typists), |
| 918 | "keys_per_s_per_typist": float64(keys) / seconds, |
| 919 | "watcher_fetches_per_s_per_doc": float64(watcherFetches) / seconds / float64(typists), |
| 920 | "push": push, "shared_watchers": shared, "watcher_gets_total": watcherFetches, "push_frames": pushes, "own_frames": owns, |
| 921 | "sender_echo_fetches_per_typist": float64(senderFetches) / float64(typists), |
| 922 | "watcher_events": events, |
| 923 | "post_bytes_mean": float64(reqBytes) / float64(posts), |
| 924 | "server_cpu_ms": after["cpu_ms"] - before["cpu_ms"], |
| 925 | "server_cpu_ms_per_s": (after["cpu_ms"] - before["cpu_ms"]) / (seconds + 2), |
| 926 | "server_alloc_mb": (after["total_alloc"] - before["total_alloc"]) / 1e6, |
| 927 | "server_mallocs": after["mallocs"] - before["mallocs"], |
| 928 | "server_gc": after["num_gc"] - before["num_gc"], |
| 929 | "server_heap_inuse_mb": after["heap_inuse"] / 1e6, |
| 930 | "t0": t0, "typed": typed, |
| 931 | } |
| 932 | line, _ := json.Marshal(summary) |
| 933 | f, err := os.OpenFile(filepath.Join(dir, "summary.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) |
| 934 | if err != nil { |
| 935 | t.Fatal(err) |
| 936 | } |
| 937 | f.Write(append(line, '\n')) |
| 938 | f.Close() |
| 939 | fmt.Println("LIVEPROBE " + string(line)) |
| 940 | } |
| 941 | |
| 942 | // TestLivePushProbeApplyCost prices what one POST costs the core today |
| 943 | // (a fresh handle: replay the document, then apply the update) against |
| 944 | // applying the same update to a handle kept warm between POSTs. Skipped |
| 945 | // unless DOCS_LIVE_PROBE_APPLY names a seed and DOCS_LIVE_PROBE_UPDATES a |
| 946 | // gen-typing.mjs directory. |
| 947 | func TestLivePushProbeApplyCost(t *testing.T) { |
| 948 | seedPath, updatesDir := os.Getenv("DOCS_LIVE_PROBE_APPLY"), os.Getenv("DOCS_LIVE_PROBE_UPDATES") |
| 949 | if seedPath == "" || updatesDir == "" { |
| 950 | t.Skip("set DOCS_LIVE_PROBE_APPLY and DOCS_LIVE_PROBE_UPDATES") |
| 951 | } |
| 952 | ctx := context.Background() |
| 953 | seed, err := os.ReadFile(seedPath) |
| 954 | if err != nil { |
| 955 | t.Fatal(err) |
| 956 | } |
| 957 | updates, err := loadProbeUpdates(filepath.Join(updatesDir, "t0.bin")) |
| 958 | if err != nil { |
| 959 | t.Fatal(err) |
| 960 | } |
| 961 | rt, err := core.New(ctx) |
| 962 | if err != nil { |
| 963 | t.Fatal(err) |
| 964 | } |
| 965 | defer rt.Close(ctx) |
| 966 | const n = 100 |
| 967 | var cold, warm []float64 |
| 968 | for k := 0; k < n; k++ { |
| 969 | start := time.Now() |
| 970 | h, err := rt.NewDoc(ctx, "probe-guid", 1) |
| 971 | if err != nil { |
| 972 | t.Fatal(err) |
| 973 | } |
| 974 | if err := h.Apply(ctx, seed); err != nil { |
| 975 | t.Fatal(err) |
| 976 | } |
| 977 | for j := 0; j < k; j++ { |
| 978 | if err := h.Apply(ctx, updates[[2]int{j, j}]); err != nil { |
| 979 | t.Fatal(err) |
| 980 | } |
| 981 | } |
| 982 | replayed := time.Now() |
| 983 | if err := h.Apply(ctx, updates[[2]int{k, k}]); err != nil { |
| 984 | t.Fatal(err) |
| 985 | } |
| 986 | cold = append(cold, float64(time.Since(start).Microseconds())/1000) |
| 987 | _ = replayed |
| 988 | h.Close(ctx) |
| 989 | } |
| 990 | h, err := rt.NewDoc(ctx, "probe-guid", 1) |
| 991 | if err != nil { |
| 992 | t.Fatal(err) |
| 993 | } |
| 994 | if err := h.Apply(ctx, seed); err != nil { |
| 995 | t.Fatal(err) |
| 996 | } |
| 997 | for k := 0; k < n; k++ { |
| 998 | start := time.Now() |
| 999 | if err := h.Apply(ctx, updates[[2]int{k, k}]); err != nil { |
| 1000 | t.Fatal(err) |
| 1001 | } |
| 1002 | warm = append(warm, float64(time.Since(start).Microseconds())/1000) |
| 1003 | } |
| 1004 | h.Close(ctx) |
| 1005 | fmt.Printf("LIVEAPPLY %s cold (new handle + seed + tail + update) p50 %.2f p95 %.2f ms; warm apply p50 %.3f p95 %.3f ms\n", |
| 1006 | filepath.Base(seedPath), probePercentile(cold, .5), probePercentile(cold, .95), probePercentile(warm, .5), probePercentile(warm, .95)) |
| 1007 | } |
| 1008 | |
| 1009 | // TestLivePushProbeWarmMemory prices a warm handle's memory: N handles of |
| 1010 | // one seed held at once (each a WASM instance with the document applied), |
| 1011 | // as Go heap and as process RSS. Skipped unless DOCS_LIVE_PROBE_MEM names |
| 1012 | // a seed. |
| 1013 | func TestLivePushProbeWarmMemory(t *testing.T) { |
| 1014 | seedPath := os.Getenv("DOCS_LIVE_PROBE_MEM") |
| 1015 | if seedPath == "" { |
| 1016 | t.Skip("set DOCS_LIVE_PROBE_MEM") |
| 1017 | } |
| 1018 | ctx := context.Background() |
| 1019 | seed, err := os.ReadFile(seedPath) |
| 1020 | if err != nil { |
| 1021 | t.Fatal(err) |
| 1022 | } |
| 1023 | rt, err := core.New(ctx) |
| 1024 | if err != nil { |
| 1025 | t.Fatal(err) |
| 1026 | } |
| 1027 | defer rt.Close(ctx) |
| 1028 | rss := func() float64 { |
| 1029 | out, _ := exec.Command("ps", "-o", "rss=", "-p", strconv.Itoa(os.Getpid())).Output() |
| 1030 | kb, _ := strconv.ParseFloat(strings.TrimSpace(string(out)), 64) |
| 1031 | return kb / 1024 |
| 1032 | } |
| 1033 | heap := func() float64 { |
| 1034 | runtime.GC() |
| 1035 | var ms runtime.MemStats |
| 1036 | runtime.ReadMemStats(&ms) |
| 1037 | return float64(ms.HeapInuse) / 1e6 |
| 1038 | } |
| 1039 | const n = 32 |
| 1040 | h0, r0 := heap(), rss() |
| 1041 | var handles []*core.Handle |
| 1042 | for i := 0; i < n; i++ { |
| 1043 | h, err := rt.NewDoc(ctx, fmt.Sprintf("g%d", i), uint64(i+1)) |
| 1044 | if err != nil { |
| 1045 | t.Fatal(err) |
| 1046 | } |
| 1047 | if err := h.Apply(ctx, seed); err != nil { |
| 1048 | t.Fatal(err) |
| 1049 | } |
| 1050 | handles = append(handles, h) |
| 1051 | } |
| 1052 | h1, r1 := heap(), rss() |
| 1053 | fmt.Printf("LIVEMEM %s: %d warm handles: heap +%.1f MB (%.2f MB each), RSS +%.1f MB (%.2f MB each)\n", |
| 1054 | filepath.Base(seedPath), n, h1-h0, (h1-h0)/n, r1-r0, (r1-r0)/n) |
| 1055 | for _, h := range handles { |
| 1056 | h.Close(ctx) |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | // TestLivePushProbeRowSize measures what one keystroke's row costs on disk |
| 1061 | // with content sealing on: 2,000 single-key updates POSTed through the app, |
| 1062 | // database and WAL checkpointed, size per row. Skipped unless |
| 1063 | // DOCS_LIVE_PROBE_ROWS names a gen-typing.mjs directory and |
| 1064 | // DOCS_LIVE_PROBE_SEED a seed. |
| 1065 | func TestLivePushProbeRowSize(t *testing.T) { |
| 1066 | dir, seedPath := os.Getenv("DOCS_LIVE_PROBE_ROWS"), os.Getenv("DOCS_LIVE_PROBE_SEED") |
| 1067 | if dir == "" || seedPath == "" { |
| 1068 | t.Skip("set DOCS_LIVE_PROBE_ROWS and DOCS_LIVE_PROBE_SEED") |
| 1069 | } |
| 1070 | seed, _ := os.ReadFile(seedPath) |
| 1071 | cfg := docs.Config{AllowedAddresses: "probe@example.com", Origin: "http://127.0.0.1", DBPath: filepath.Join(t.TempDir(), "docs.db"), Env: "development", |
| 1072 | ContentKey: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{71}, 32))} |
| 1073 | first, err := docs.New(cfg) |
| 1074 | if err != nil { |
| 1075 | t.Fatal(err) |
| 1076 | } |
| 1077 | first.Close() |
| 1078 | fp, _ := probeKeyFingerprint(cfg.ContentKey) |
| 1079 | if err := docs.MaintainContent(context.Background(), docs.ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: cfg.ContentKey, ExpectedFingerprint: fp}); err != nil { |
| 1080 | t.Fatal(err) |
| 1081 | } |
| 1082 | app, err := docs.NewForTestWith(t, cfg) |
| 1083 | if err != nil { |
| 1084 | t.Fatal(err) |
| 1085 | } |
| 1086 | cookies := signInCookies(t, app, "probe@example.com") |
| 1087 | do := func(method, path string, body []byte) *httptest.ResponseRecorder { |
| 1088 | req := httptest.NewRequest(method, path, bytes.NewReader(body)) |
| 1089 | req.Header.Set("Origin", cfg.Origin) |
| 1090 | if method == "POST" && path == "/documents" { |
| 1091 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 1092 | } else { |
| 1093 | req.Header.Set("Content-Type", "application/octet-stream") |
| 1094 | } |
| 1095 | for _, c := range cookies { |
| 1096 | req.AddCookie(c) |
| 1097 | } |
| 1098 | rec := httptest.NewRecorder() |
| 1099 | app.Handler().ServeHTTP(rec, req) |
| 1100 | return rec |
| 1101 | } |
| 1102 | rec := do("POST", "/documents", []byte("title=Rows")) |
| 1103 | sqid := strings.TrimPrefix(rec.Header().Get("Location"), "/d/") |
| 1104 | if rec := do("POST", "/d/"+sqid+"/updates", seed); rec.Code/100 != 2 { |
| 1105 | t.Fatal(rec.Code) |
| 1106 | } |
| 1107 | raw, err := sql.Open("sqlite", cfg.DBPath) |
| 1108 | if err != nil { |
| 1109 | t.Fatal(err) |
| 1110 | } |
| 1111 | defer raw.Close() |
| 1112 | checkpoint := func() { |
| 1113 | if _, err := raw.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { |
| 1114 | t.Fatal(err) |
| 1115 | } |
| 1116 | } |
| 1117 | fileSize := func(suffix string) int64 { |
| 1118 | st, err := os.Stat(cfg.DBPath + suffix) |
| 1119 | if err != nil { |
| 1120 | return 0 |
| 1121 | } |
| 1122 | return st.Size() |
| 1123 | } |
| 1124 | updates, err := loadProbeUpdates(filepath.Join(dir, "t0.bin")) |
| 1125 | if err != nil { |
| 1126 | t.Fatal(err) |
| 1127 | } |
| 1128 | post := func(k int) int { |
| 1129 | u := updates[[2]int{k % 300, k % 300}] |
| 1130 | if rec := do("POST", "/d/"+sqid+"/updates", u); rec.Code/100 != 2 { |
| 1131 | t.Fatalf("POST %d: %d", k, rec.Code) |
| 1132 | } |
| 1133 | return len(u) |
| 1134 | } |
| 1135 | // WAL bytes per commit: a short run that stays under the autocheckpoint. |
| 1136 | checkpoint() |
| 1137 | const short = 100 |
| 1138 | for k := 0; k < short; k++ { |
| 1139 | post(k) |
| 1140 | } |
| 1141 | walPerCommit := float64(fileSize("-wal")) / short |
| 1142 | // Storage per row: database file growth over 2,000 rows, checkpointed. |
| 1143 | checkpoint() |
| 1144 | before := fileSize("") |
| 1145 | const n = 2000 |
| 1146 | var payload int |
| 1147 | for k := 0; k < n; k++ { |
| 1148 | payload += post(k) |
| 1149 | } |
| 1150 | checkpoint() |
| 1151 | after := fileSize("") |
| 1152 | fmt.Printf("LIVEROWS sealed: payload %.1f B/row; database file growth %.0f B/row over %d rows (includes %d snapshots); WAL written per commit %.0f B\n", |
| 1153 | float64(payload)/n, float64(after-before)/n, n, n/256, walPerCommit) |
| 1154 | } |
| 1155 | |