carlos / platform Public

analytics-live: Astra round 1 P2s

- Concurrent misses on one memo key make one read (analyticsMemo.load, with
  waiters bounded by their own context): the one-read-a-minute budget holds
  when tabs refresh in the same second.
- The page script never refreshes closer than 55 s apart, so coming back to
  a hidden tab cannot fire two requests a second apart.
- The period row (span, day navigation) is part of what refreshes, so a page
  left open across midnight names the day its numbers are for.
- A past day's restart note names the day instead of saying today.

Findings: docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
(READY AFTER FIXES, 4 P2s fixed here, no round 2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 47d74f1551a9176b7fefc6a424a8fc7f59a5ae8b parent f924d7f
6 files changed, +188 −32
  • docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md +29 −0
  • internal/console/analyticsdisplay.go +2 −2
  • internal/console/analyticsdisplay_test.go +11 −3
  • internal/console/analyticslive_test.go +66 −2
  • internal/console/analyticsview.go +60 −9
  • internal/console/templates/app_analytics.html +20 −16

CI failed — run details

Intent

Human

<task-notification> <task-id>b78js0jnb</task-id> <tool-use-id>toolu_01FrKfZ33fGji2CMCMV1RyNb</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/b78js0jnb.output</output-file> <status>completed</status> <summary>Background command "/home/paulca/.cache/tmp/analytics-live/run-review.sh" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 44.1 g CO₂e (5,582,763 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on analytics-live, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
new file mode 100644
index 000000000..2352fe8bc
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
@@ -0,0 +1,29 @@
+Reviewed `origin/main...fa2f549501` using the brief at `f924d7f9`. No tracked files changed. No P1 findings.
+
+1. **P2 — Shared-read budget is not enforced.**
+ Evidence: `internal/console/analyticsview.go:419–425` checks the memo, reads storage, then populates it without coordinating concurrent misses. Two tabs refreshing an expired key together both perform the LIST and day-file reads, contradicting “one read a minute per app and view.”
+ **Fix:** coalesce concurrent loads by memo key and add a concurrent-miss witness.
+ **Fault family:** storage request budget.
+
+2. **P2 — Returning to a visible tab can trigger requests one second apart.**
+ Evidence: `internal/console/templates/app_analytics.html:187–204`. The visibility handler calls `refresh()`, but the fixed interval does not check `lastRun`. A Node harness executing this script produced requests at 119,000 ms and 120,000 ms.
+ **Fix:** enforce the minimum interval inside `refresh()`, or reschedule one timeout after each attempt.
+ **Fault family:** browser request budget.
+
+3. **P2 — Dates and day navigation become stale across midnight.**
+ Evidence: `internal/console/templates/app_analytics.html:29–40` puts the span and day navigation outside the refreshed element; line 196 replaces only its contents. An active Today page crosses midnight and displays the new day’s counts beneath yesterday’s date. A past-day page can retain “Next day → today” after that link should name yesterday.
+ **Fix:** refresh the period label and day navigation alongside the numbers.
+ **Fault family:** displayed timeframe must match the data.
+
+4. **P2 — Past-day restart warnings incorrectly say “today.”**
+ Evidence: the new day view calls `restartNote(sum.Days)` at `internal/console/analyticsview.go:442`; `internal/console/analyticsdisplay.go:459–460` describes every single-day restart as happening today. Opening a historical day with `Restarted=true` therefore gives the wrong date.
+ **Fix:** name the actual day, or pass the current date and reserve “today” for a matching date.
+ **Fault family:** historical-day accuracy.
+
+The account gate restricts reads to a member’s account and claimed app. Rendered visitor strings use escaped templates; I found no injection or open redirect.
+
+Request cost is two settings GETs per live request. A memo miss adds a box listing, requested unsettled day files, and settled files absent from the cache. Hidden and idle pages skip new fetches, although an existing fetch can finish. The concurrency and timing findings above prevent the stronger stated budget.
+
+Targeted query, neighbour, chart, insight, timing, and memo tests passed. HTTP tests were blocked by the sandbox refusing loopback sockets; their behavior remains unverified.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go
index 3c8129a57..77af1e4ef 100644
--- a/internal/console/analyticsdisplay.go
+++ b/internal/console/analyticsdisplay.go
@@ -446,7 +446,7 @@ func analyticsSpanText(rng string, now time.Time) string {
// had not yet saved were lost, so those days may read low. No bound is
// given: a flush runs every five minutes, but a failed flush is held for
// the next one, so a restart can lose more than one window. Up to three days are named; more are counted.
-func restartNote(days []analytics.DaySummary) string {
+func restartNote(days []analytics.DaySummary, now time.Time) string {
var hit []string
for _, d := range days {
if d.Restarted {
@@ -456,7 +456,7 @@ func restartNote(days []analytics.DaySummary) string {
switch n := len(hit); {
case n == 0:
return ""
- case n == 1 && len(days) == 1:
+ case n == 1 && len(days) == 1 && days[0].Date == now.UTC().Format("2006-01-02"):
return "The edge restarted today. Counts it had not saved yet may be missing."
case n == 1:
return "The edge restarted on " + hit[0] + ". Counts it had not saved yet may be missing for that day."
diff --git a/internal/console/analyticsdisplay_test.go b/internal/console/analyticsdisplay_test.go
index 957e40d95..d4393a34d 100644
--- a/internal/console/analyticsdisplay_test.go
+++ b/internal/console/analyticsdisplay_test.go
@@ -149,19 +149,27 @@ func TestAnalyticsInsights(t *testing.T) {
func TestRestartNote(t *testing.T) {
day := func(date string, r bool) analytics.DaySummary { return analytics.DaySummary{Date: date, Restarted: r} }
- if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}); got != "" {
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}, now); got != "" {
t.Errorf("no restarts = %q", got)
}
- if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
+ if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}, now); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
t.Errorf("two restarts = %q", got)
}
var many []analytics.DaySummary
for i := 1; i <= 5; i++ {
many = append(many, day("2026-10-0"+string(rune('0'+i)), true))
}
- if got := restartNote(many); !strings.Contains(got, "on 5 of these days") {
+ if got := restartNote(many, now); !strings.Contains(got, "on 5 of these days") {
t.Errorf("five restarts = %q", got)
}
+ // One day: "today" only when it is today; a past day is named.
+ if got := restartNote([]analytics.DaySummary{day("2026-10-29", true)}, now); !strings.Contains(got, "restarted today") {
+ t.Errorf("today's restart = %q", got)
+ }
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", true)}, now); strings.Contains(got, "today") || !strings.Contains(got, "Tue 27 Oct") {
+ t.Errorf("a past day's restart = %q, want it named", got)
+ }
}
func TestShareRows(t *testing.T) {
diff --git a/internal/console/analyticslive_test.go b/internal/console/analyticslive_test.go
index 47ce0aec8..fd6b3752e 100644
--- a/internal/console/analyticslive_test.go
+++ b/internal/console/analyticslive_test.go
@@ -5,6 +5,8 @@ import (
"net/http"
"net/url"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -101,8 +103,8 @@ func TestAnalyticsLiveDoor(t *testing.T) {
if !strings.Contains(body, "/analytics?range=today") {
t.Error("today's column does not open the today range")
}
- if strings.Contains(body, "<html") || strings.Contains(body, "<nav") {
- t.Error("live answer carries page chrome")
+ if strings.Contains(body, "<html") || strings.Contains(body, "an-off") || !strings.Contains(body, `<nav class="an-range" aria-label="Period">`) {
+ t.Error("live answer carries page chrome, or lacks its period row")
}
before := cs.dayReads()
res, err = c.Get(fx.u("/apps/titogo/analytics/live?view=tab&range=7d"))
@@ -192,3 +194,65 @@ func readBody(t *testing.T, res *http.Response) string {
}
return b.String()
}
+
+// Concurrent misses on one key make one read: the live door's budget is one
+// read a minute per app and view, however many tabs refresh at once.
+func TestAnalyticsMemoCoalescesConcurrentMisses(t *testing.T) {
+ var m analyticsMemo
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ var reads atomic.Int32
+ release := make(chan struct{})
+ read := func() (analytics.Summary, error) {
+ reads.Add(1)
+ <-release
+ return analytics.Summary{PV: 9}, nil
+ }
+ var wg sync.WaitGroup
+ got := make([]int64, 8)
+ for i := range got {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ sum, err := m.load(context.Background(), "k", now, read)
+ if err != nil {
+ t.Error(err)
+ }
+ got[i] = sum.PV
+ }(i)
+ }
+ time.Sleep(50 * time.Millisecond) // let every caller arrive while the read runs
+ close(release)
+ wg.Wait()
+ if n := reads.Load(); n != 1 {
+ t.Fatalf("8 concurrent misses made %d reads, want 1", n)
+ }
+ for i, pv := range got {
+ if pv != 9 {
+ t.Fatalf("caller %d got %d, want the shared read's 9", i, pv)
+ }
+ }
+ // A waiter gives up with its own context.
+ block := make(chan struct{})
+ defer close(block)
+ go m.load(context.Background(), "slow", now, func() (analytics.Summary, error) { <-block; return analytics.Summary{}, nil })
+ time.Sleep(20 * time.Millisecond)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if _, err := m.load(ctx, "slow", now, read); err == nil {
+ t.Fatal("a waiter outlived its context")
+ }
+}
+
+// The page script never refreshes closer than a minute apart, whatever asks
+// (the interval, or coming back to the tab).
+func TestAnalyticsScriptRefreshesAtMostOnceAMinute(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-script")
+ seedAnalytics(t, fx, seedTime())
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-script-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ if !strings.Contains(body, "if (Date.now() - lastRun < 55000) return;") {
+ t.Fatal("the refresh's minimum interval is missing")
+ }
+}
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go
index ede62e1c7..8a8072f95 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -278,8 +278,56 @@ const (
// it; someone looking at analytics gets the bucket as it is. A held
// Summary is shared between views and must not be changed.
type analyticsMemo struct {
- mu sync.Mutex
- m map[string]analyticsMemoEntry
+ mu sync.Mutex
+ m map[string]analyticsMemoEntry
+ inflight map[string]*analyticsMemoCall
+}
+
+// analyticsMemoCall is one read in progress, which every caller asking for
+// the same key while it runs waits on rather than starting its own.
+type analyticsMemoCall struct {
+ done chan struct{}
+ sum analytics.Summary
+ err error
+}
+
+// load is key's counts: from the memo when held, else from the one read
+// in progress for key, else from read, which this caller runs and keeps.
+// Concurrent misses on one key (two tabs refreshing in the same second)
+// make one read, so the budget is one read a minute per app and view
+// however many pages ask. A waiter gives up with its own context; a failed
+// read is not kept, and the next caller reads again.
+func (c *analyticsMemo) load(ctx context.Context, key string, now time.Time, read func() (analytics.Summary, error)) (analytics.Summary, error) {
+ if sum, ok := c.get(key, now); ok {
+ return sum, nil
+ }
+ c.mu.Lock()
+ if call, ok := c.inflight[key]; ok {
+ c.mu.Unlock()
+ select {
+ case <-call.done:
+ return call.sum, call.err
+ case <-ctx.Done():
+ return analytics.Summary{}, ctx.Err()
+ }
+ }
+ if c.inflight == nil {
+ c.inflight = map[string]*analyticsMemoCall{}
+ }
+ call := &analyticsMemoCall{done: make(chan struct{})}
+ c.inflight[key] = call
+ c.mu.Unlock()
+ defer func() {
+ c.mu.Lock()
+ delete(c.inflight, key)
+ c.mu.Unlock()
+ close(call.done)
+ }()
+ call.sum, call.err = read()
+ if call.err == nil {
+ c.put(key, call.sum, now)
+ }
+ return call.sum, call.err
}
type analyticsMemoEntry struct {
@@ -416,13 +464,16 @@ func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analy
}
from, to := analyticsQuerySpan(q, now)
key := sqid + "/" + app + "/" + rng + "/" + q.Date + "/" + now.UTC().Format("2006-01-02")
- sum, hit := memo.get(key, now)
- if !hit {
+ var sum analytics.Summary
+ if memo == nil {
sum, err = s.readAnalyticsRange(ctx, sqid, app, from, to, now)
- if err != nil {
- return out, err
- }
- memo.put(key, sum, now)
+ } else {
+ sum, err = memo.load(ctx, key, now, func() (analytics.Summary, error) {
+ return s.readAnalyticsRange(ctx, sqid, app, from, to, now)
+ })
+ }
+ if err != nil {
+ return out, err
}
out.Sum = sum
// A day is drawn as today is: its hours.
@@ -439,7 +490,7 @@ func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analy
out.Referers = shareRows(sum.Referers, refererLabel)
out.Events = shareRows(sum.Events, pageLabel)
out.Countries = shareRows(geoCountries(sum.Countries), countryLabel)
- out.Restarts = restartNote(sum.Days)
+ out.Restarts = restartNote(sum.Days, now)
return out, nil
}
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html
index 5d3c19218..161c93e53 100644
--- a/internal/console/templates/app_analytics.html
+++ b/internal/console/templates/app_analytics.html
@@ -26,25 +26,28 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
{{/* The range picker always shows: numbers counted while analytics was on
stay reachable after it is switched off. Three links rather than a
select and a button: one click, and every view is a URL. */}}
-<nav class="an-range" aria-label="Period">
- <a href="?range=today"{{if eq .AnalyticsRange "today"}} aria-current="page"{{end}}>Today</a>
- <a href="?range=7d"{{if eq .AnalyticsRange "7d"}} aria-current="page"{{end}}>7 days</a>
- <a href="?range=30d"{{if eq .AnalyticsRange "30d"}} aria-current="page"{{end}}>30 days</a>
- {{if .AnalyticsWin.Span}}<span class="an-span">{{.AnalyticsWin.Span}}</span>{{end}}
- {{with .AnalyticsWin}}{{if eq .Range "day"}}<span class="an-daynav">
- {{if .Prev}}<a href="?date={{.Prev}}">Previous day</a>{{end}}
- {{if eq .Next "today"}}<a href="?range=today">Next day</a>{{else if .Next}}<a href="?date={{.Next}}">Next day</a>{{end}}
- </span>{{end}}{{end}}
-</nav>
-{{if or .AnalyticsWin.On .AnalyticsWin.HasData}}
-{{with .AnalyticsLive}}<div class="an-live" data-live="{{.Src}}">{{template "analyticsdata" .}}</div>
-{{template "analyticsscript"}}{{end}}
-{{end}}
+{{/* The period row is part of what refreshes: a page left open across
+ midnight must name the day its numbers are for. */}}
+{{with .AnalyticsLive}}{{if and .Win (or .Win.On .Win.HasData)}}
+<div class="an-live" data-live="{{.Src}}">{{template "analyticsdata" .}}</div>
+{{template "analyticsscript"}}
+{{else}}{{template "analyticsnav" .}}{{end}}{{end}}
{{template "bottom" .}}{{end}}
{{/* The numbers part of the tab: what a reload would show, and what the
live door (analyticslive.go) answers to the page's minute refresh. */}}
-{{define "analyticsdata"}}{{with .Win}}
+{{define "analyticsnav"}}<nav class="an-range" aria-label="Period">
+ <a href="?range=today"{{if eq .Query.Range "today"}} aria-current="page"{{end}}>Today</a>
+ <a href="?range=7d"{{if eq .Query.Range "7d"}} aria-current="page"{{end}}>7 days</a>
+ <a href="?range=30d"{{if eq .Query.Range "30d"}} aria-current="page"{{end}}>30 days</a>
+ {{with .Win}}{{if .Span}}<span class="an-span">{{.Span}}</span>{{end}}
+ {{if eq .Range "day"}}<span class="an-daynav">
+ {{if .Prev}}<a href="?date={{.Prev}}">Previous day</a>{{end}}
+ {{if eq .Next "today"}}<a href="?range=today">Next day</a>{{else if .Next}}<a href="?date={{.Next}}">Next day</a>{{end}}
+ </span>{{end}}{{end}}
+</nav>{{end}}
+
+{{define "analyticsdata"}}{{if not .Card}}{{template "analyticsnav" .}}{{end}}{{with .Win}}
{{template "trafficfigures" .}}
{{if .Chart}}
{{template "trafficchart" .Chart}}
@@ -186,6 +189,7 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
function busy(el) { return el.matches(":hover") || el.contains(document.activeElement); }
function refresh() {
if (document.visibilityState !== "visible" || Date.now() - lastInput > 30 * 60 * 1000) return;
+ if (Date.now() - lastRun < 55000) return; // never closer than a minute, whatever asked
lastRun = Date.now();
document.querySelectorAll("[data-live]").forEach(function (el) {
if (busy(el)) return;
@@ -201,7 +205,7 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
}
setInterval(refresh, 60000);
document.addEventListener("visibilitychange", function () {
- if (document.visibilityState === "visible" && Date.now() - lastRun > 60000) refresh();
+ if (document.visibilityState === "visible") refresh();
});
})();
</script>{{end}}