perf(traffic): index exchanges on (host, ts)

traffic_search and the host-filtered traffic list run
WHERE host=? ORDER BY ts DESC LIMIT n. With only idx_ex_host(host) SQLite
reads every exchange of the host and sorts them in a temp b-tree to return
the newest few. Hosts(), which the traffic page polls every 5 s, scans the
table for GROUP BY host / MAX(ts).

Replace idx_ex_host with idx_ex_host_ts(host, ts). The host search walks
the index backwards and stops after n rows, and Hosts() reads only the
index. Existing stores get the new index and drop the old one on open.

BenchmarkHostSearch, 50k exchanges (45k on one host):
  search  42.05 ms -> 0.038 ms
  hosts   19.89 ms -> 7.77 ms
This commit is contained in:
Phantom-IN
2026-11-25 20:53:55 +05:30
parent 3cb06383fd
commit efc7c09fdd
3 changed files with 82 additions and 1 deletions
+1
View File
@@ -14,6 +14,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
- **Traffic host lists no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and the traffic page's host filter sorted every exchange of the host to return the newest few, and the host picker (polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms.
- **Missing Docker buildx is reported before the build**: without the buildx plugin, Compose only warns and falls back to the legacy builder, which fails on the Dockerfile's first `FROM --platform=$BUILDPLATFORM` with `failed to parse platform`. `install.sh` (all-Docker) and `update.sh` (Docker update) now check `docker buildx version` first and stop with an install hint, and the automatic Docker install on apt-based distros not covered by get.docker.com installs the buildx package as well. The README Docker section names buildx as a requirement.
- **A goal URL followed by punctuation is still seeded**: a goal such as `Assess http://juiceshop:3000.` no longer logs `could not parse a target host/IP` and skips the site. Trailing punctuation, including full-width `。` and a closing bracket that has no matching opener, is trimmed from the URL before it is parsed, so `http://[::1]` is left alone. The scheme the goal names is kept and a final period does not end up in the host.
- **Task timeout triggers fire for every task**: `on_task_timeout` used the task id as a watermark, but tasks time out in deadline order. Once a newer task timed out first, an older task that timed out later was never fired for. Fired timeouts are now kept in a persisted set, like met goals; on first start the set is seeded with the tasks already timed out, so nothing replays.
+78
View File
@@ -0,0 +1,78 @@
package traffic
import (
"fmt"
"strings"
"testing"
)
func queryPlan(t testing.TB, tr *Traffic, q string, args ...any) string {
t.Helper()
rows, err := tr.db.Query("EXPLAIN QUERY PLAN "+q, args...)
if err != nil {
t.Fatalf("explain: %v", err)
}
defer rows.Close()
var plan []string
for rows.Next() {
var id, parent, unused int
var detail string
if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
t.Fatalf("scan plan: %v", err)
}
plan = append(plan, detail)
}
return strings.Join(plan, "\n")
}
func TestHostSearchUsesHostTSIndex(t *testing.T) {
tr, _ := openTraffic(t)
plan := queryPlan(t, tr, `SELECT id FROM exchanges WHERE host=? ORDER BY ts DESC LIMIT 3`, "a.example")
if !strings.Contains(plan, "idx_ex_host_ts") || strings.Contains(plan, "TEMP B-TREE") {
t.Fatalf("host search should walk idx_ex_host_ts without a sort:\n%s", plan)
}
plan = queryPlan(t, tr, `SELECT host, COUNT(*) AS n, MAX(ts) AS last FROM exchanges GROUP BY host ORDER BY last DESC`)
if !strings.Contains(plan, "COVERING INDEX idx_ex_host_ts") {
t.Fatalf("Hosts() should read only idx_ex_host_ts:\n%s", plan)
}
}
func BenchmarkHostSearch(b *testing.B) {
tr, err := Open(b.TempDir(), "127.0.0.1:0")
if err != nil {
b.Fatal(err)
}
defer tr.Close()
tx, err := tr.db.Begin()
if err != nil {
b.Fatal(err)
}
for i := 0; i < 50000; i++ {
host := "big.example"
if i%10 == 0 {
host = fmt.Sprintf("h%d.example", i%200)
}
if _, err := tx.Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES (?,?,?,'GET','/','http://x/',200,'text/html',0,0,'/')`, fmt.Sprintf("bench-%d", i), int64(i), host); err != nil {
b.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
b.Fatal(err)
}
b.Run("search", func(b *testing.B) {
for b.Loop() {
if _, err := tr.query("big.example", "", "", 0, 3); err != nil {
b.Fatal(err)
}
}
})
b.Run("hosts", func(b *testing.B) {
for b.Loop() {
if _, err := tr.Hosts(); err != nil {
b.Fatal(err)
}
}
})
}
+3 -1
View File
@@ -53,7 +53,9 @@ CREATE TABLE IF NOT EXISTS exchanges (
resp_len INTEGER,
path TEXT
);
CREATE INDEX IF NOT EXISTS idx_ex_host ON exchanges(host);
-- Replaces idx_ex_host(host): host lists skip the ts sort and Hosts() reads only the index.
CREATE INDEX IF NOT EXISTS idx_ex_host_ts ON exchanges(host, ts);
DROP INDEX IF EXISTS idx_ex_host;
CREATE INDEX IF NOT EXISTS idx_ex_tmpl ON exchanges(host, url_template);
CREATE INDEX IF NOT EXISTS idx_ex_ts ON exchanges(ts);
CREATE INDEX IF NOT EXISTS idx_ex_status ON exchanges(status);