oficina / mapa Public

Mapa: Recently edited as one indexed query, with gates for a busy page and deleted pages

0.3ms whatever the history, down from up to 47ms. A new events index (migration 0004, additive). Gates for 900 edits to one page and for deleted pages. Fable APPROVED (08088d4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from fix/recent-query into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2cf0c447c78acfcd01c15e00463bf0656b1aa9e1 parent 4dcfbdf
8 files changed, +314 −91
  • docs/superpowers/specs/2026-11-14-mapa-level-up.md +19 −1
  • internal/mapa/migrations/0004_events_actor_page.sql +2 −0
  • internal/mapa/migrations/schema.sql +2 −0
  • internal/mapa/models.go +12 −6
  • internal/mapa/recent.go +66 −77
  • internal/mapa/recent_bench_test.go +131 −0
  • internal/mapatest/sidebar_ruling_test.go +74 −0
  • scripts/mutate/mutations.go +8 −7

CI passed — run details

CI log
=== editor ===
cd editor && npm ci --no-audit --no-fund --loglevel=error

added 16 packages in 335ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.fd68828f6fa8343e.js (317138 bytes, 99.0KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ L1: mounting then serialising gives cleanBody(body), byte for byte (52.075584ms)
ℹ 760 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (58.35235ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (101.796065ms)
ℹ 748 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (110.689349ms)
ℹ 755 inserts, 715 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (3071.197039ms)
ℹ 18240 edits over 760 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (954.742581ms)
ℹ 4124 links over 760 bodies; refused: {"A page link can’t hold another link or a line break. Select plain words.":610,"A page link can’t show [ or ]]. Select words without them.":370,"Select some words to link them to a page.":163,"Linked here, the Markdown around these words would read differently: a ! before them makes an embed, and a stray ` or * pairs up. Select other words.":17}
✔ linear: trailing spaces (21.980551ms)
✔ linear: trailing whitespace (12.037275ms)
✔ linear: unclosed web links (11.694784ms)
✔ linear: web links with no address (24.931045ms)
✔ linear: unclosed wiki links (18.515143ms)
✔ linear: unclosed embeds (20.049139ms)
✔ linear: closes only (6.851998ms)
✔ the selected words become the chip's shown text (11.679876ms)
✔ words that are the title make a plain [[Title]] (3.369831ms)
✔ spaces at the selection's edges stay outside the chip (1.403635ms)
✔ a date makes a date link, in a heading, an item and a quote (5.767373ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (1.092249ms)
✔ only the linked block's bytes change, and undo gives the body back (2.076749ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (1.051604ms)
✔ a target the words cannot be linked to as typed is refused (0.225857ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (2.313809ms)
✔ web-linked words are refused: the address would be lost (review M4) (0.961077ms)
✔ words whose Markdown would read otherwise are refused (review M3) (1.645142ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (0.371547ms)
✔ linkCheck says why it refuses (review low 2) (0.493973ms)
✔ golden file has bodies (0.73583ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (14.50013ms)
✔ markup.mjs strips and spans every block as Go does (26.006724ms)
✔ the schema's toDOM draws every body as Go renders it (69.85023ms)
✔ emphasis draws the four pinned outputs (16.234917ms)
✔ a body ends in the editor's empty paragraph (0.209237ms)
✔ a POST that never answers is aborted after the timeout (21.429261ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (1.140138ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (8.657537ms)
✔ an offered draft never commits by itself; Save commits it (1.098321ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.61669ms)
✔ closing carries text not yet sent, and the cap leaves it out (25.656398ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (4.696002ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (3.167978ms)
✔ typing mid-flight: the merge is not applied and the base does not move (1.215837ms)
✔ a merge the editor cannot represent stops after three tries (3.827466ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (1.336591ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (1.620326ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (1.026819ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (0.971757ms)
✔ noBase and gone lead to the existing choices (0.985142ms)
✔ a commit that merged is applied when nothing was typed since (1.231647ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (9.699102ms)
✔ an own draft committed meanwhile goes on as a new draft (1.747972ms)
✔ a reload keeps a stored draft; unsent text still commits (0.683574ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (1.652606ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (5.569969ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (2.112285ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (4.908376ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (1.326512ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.381676ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (1.116313ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.599889ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (0.85959ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (0.679606ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (0.68699ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (5.210613ms)
✔ marks close before code, links and atoms, and reopen after (0.552642ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (4.885634ms)
✔ empty blocks are written as nothing (1.633079ms)
✔ an unclosed fence that is no longer last gets its closing fence (1.031097ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (1.400739ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (2.497147ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (1.954053ms)
✔ a trailing hard break stays on screen and is written as nothing (0.460071ms)
✔ the reparse waits while an IME is composing (0.616309ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (2.777425ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.623312ms)
✔ rebuild changes origins only, outside undo history (1.196642ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (4.392462ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (1.706625ms)
✔ a duplicate ^id typed above its holder never takes the id from it (0.595882ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (0.816921ms)
✔ a history command that throws is refused, never thrown (2.549284ms)
✔ one rename at a time, from either field (1.605239ms)
✔ an empty or unchanged title sends nothing (0.165937ms)
✔ a refusal keeps what was typed, and the title (0.20011ms)
✔ the pending state holds for the busy rule (8.254853ms)
✔ a failed POST says so and keeps the title (0.371507ms)
✔ Update links posts the confirm page's POST (0.271432ms)
✔ clean is CleanTitle's whitespace rule (0.128457ms)
✔ the saver's base follows a rename made over it, and only that (0.331823ms)
✔ closing sends the rename as one keepalive POST (1.52507ms)
ℹ tests 89
ℹ suites 0
ℹ pass 89
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4496.647656
=== vet ===
go vet ./...
go vet -tags browser ./internal/mapatest/
=== fmt ===
=== code ===
go tool rastrillo budget code
The base has no .rastrillo/code.txt: skipping the check that records only go down.
budget code: within the limits.
=== test ===
CGO_ENABLED=0 go test ./...
?   	amadan.net/oficina/mapa/cmd/mapa	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa	0.531s
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/markup	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/seal	(cached)
ok  	amadan.net/oficina/mapa/internal/mapatest	9.169s
?   	amadan.net/oficina/mapa/scripts/mutate	[no test files]
?   	amadan.net/oficina/mapa/scripts/preview	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
=== credits-check ===
python3 scripts/credits.py --check
credits: checked
diff --git a/docs/superpowers/specs/2026-11-14-mapa-level-up.md b/docs/superpowers/specs/2026-11-14-mapa-level-up.md
index 02eca5d..97fa63a 100644
--- a/docs/superpowers/specs/2026-11-14-mapa-level-up.md
+++ b/docs/superpowers/specs/2026-11-14-mapa-level-up.md
@@ -1204,12 +1204,22 @@ Phase 1's choices where this spec was silent, or where the build chose different
80. **Recently edited is team pages only, and the sidebar has one full highlight** (amends §3.2 and §11 Q2).
- **The ruling.** Paul took Fable's recommendation: Recently edited lists team pages only. No scratch page and no daily note is in it, and no scratch page's first line is anywhere in the sidebar, the rail's tooltips and estilo's Menu sheet included. The reasons are §3.2's: Today covers days, so Scratch covers scratch; ⌘K already separates "Your notes"; the list has six slots; and on a shared screen private first lines would show on every page.
- - **The list.** `recent.go` reads only events on live team pages: the query joins `pages` and keeps `rung = 'team'` and not `gone`, both plaintext (§4). Private writes are never in the window of events it reads, so no number of them pushes the team pages out (Fable M1: filtered after `LIMIT 200`, 210 scratch writes emptied the list). The window starts at 200 events and grows fourfold until it holds six pages or the whole history, so one page edited many times cannot hide the rest. The scoped view still filters what it returns. A private page's label is never drawn there. Bulk detection now sees only team events; Update links still marks its transaction bulk by the team pages' `relinked`, and Make team page's new page logs `created`, so both count as before.
+ - **The list.** `recent.go` reads only events on live team pages: the query joins `pages` and keeps `rung = 'team'` and not `gone`, both plaintext (§4). Private writes are never in the window of events it reads, so no number of them pushes the team pages out (Fable M1: filtered after `LIMIT 200`, 210 scratch writes emptied the list). It was first a window of the newest 200 events that grew fourfold to a cap; Fable's re-review of `168d97b` (round 6 addendum, L1) found that costs 46ms a page view for a person who edits few team pages, and at the cap it shows one page. It is now one query (`recentQuery`): a loose scan of a new index, `idx_events_actor_page` (actor, kind, object; migration 0004), visits each page the person wrote in once; for each live team page, its newest write that counts is read back from that page's end of the index, stopping at the first; the six newest are kept. A plain `GROUP BY object_id` with `MAX(id)` was measured first and rejected: it reads every one of the person's events (13ms at 20,000 and 150ms at 200,000; 36ms and 400ms with the bulk test). The bulk test reads one transaction through `idx_events_at`, named with `INDEXED BY` because the planner otherwise takes the person's whole index for it. The cost now follows how many pages the person wrote in, not how many times:
+
+ | Apple M1 Max, 20 runs (`BenchmarkRecentEdits*`) | before | after |
+ |---|---|---|
+ | 20,000 events, all on one of six pages | 45.8ms, 1 page shown | 0.27ms, 6 |
+ | 200,000 events, all on one of six pages | 47.3ms, 1 page shown | 0.28ms, 6 |
+ | 20,000 events over six pages | 0.60ms | 0.29ms |
+ | 200,000 events over 1,000 pages | not measured | 9.5ms |
+
+ The last row is the trade: about 9µs a page written in. A person with thousands of pages behind them would pay milliseconds; a first pass over the newest events, falling back to this query only when it cannot prove its six, would take that back, and is not built. `TestRecentlyEditedReadsByIndex` holds the plan to the two indexes and no scan of `events`. The scoped view still filters what it returns. A private page's label is never drawn there. Bulk detection now sees only team events; Update links still marks its transaction bulk by the team pages' `relinked`, and Make team page's new page logs `created`, so both count as before.
- **Scratch.** The row stays. Its screen says "Only you see these: untitled notes, the last edited first", and lists them in that order (`Index.ordered`, as before).
- **Pins.** A note of your own can be pinned (it always could). It stays in Pinned, as the person chose it, with a lock glyph at the row's end and ", only you see this" in its name. The rail hides Pinned, so its tooltips never show it.
- **One full highlight.** `side.go`'s `light` gives `aria-current` to the first row that is the page on screen (Pinned before Recently edited), and then takes it off the page's place. A past day lights Today, as today's note does: Today is where days are kept, and the day pill says which day; the old `dayNav` lit nothing for one. A team page in neither list lights All pages; a scratch page, Scratch; a pinned scratch page, its row.
- **The rail, with and without script.** The rail hides the page rows, so there the place must be lit, and with no cookie only CSS knows the sidebar is a rail (by width). So a place holding a page that has its own row is drawn twice: unlit (`mapa-side-holds="open"`) and lit (`mapa-side-holds="rail"`). CSS shows the unlit copy in the open sidebar and the lit one in the rail, by the same selectors that fold it. The lit copy also carries `hidden`, which the rail's `display: grid` outranks, so with no CSS at all only the page's own row is lit (Fable low 4). The cookie, the width and ⌘\'s fold in place all agree, with no script and no `aria-current` moved by script. A hidden copy is out of the accessibility tree, so exactly one lit row is ever exposed. The Menu sheet's rows are the places, and the page's place is lit there.
- **Gates.** `sidebar_ruling_test.go` (server, so the scriptless screen): no scratch or daily row in Recently edited and no private first line in the sidebar or the bar's nav, on five screens with each cookie; the Scratch screen's order and label; a pinned note's lock; one highlight for eight kinds of page, open and in the rail. `sidebar_browser_test.go` in `make browser`, scripts off and on, at 1400 and 900 with no cookie, `open` and `rail`: exactly one visible `aria-current` for nine screens, the sidebar's text (the tooltips are its labels) holding no private line; at 390 the Menu sheet; ⌘\ moving the highlight from the row to All pages and back. Red on `510eaa5`: two rows lit on a team page in Recently edited ("All pages | Quarterly plan"), on a pinned one three ("All pages | Pinned plan | Pinned plan"), on a scratch page "Scratch | Zanzibar secret first line", on a day "Today | Monday 16 November 2026", none on a past day; the private line in the sidebar's markup, also at 390 where only the Menu sheet shows; and no lock.
+ - **Gates added after Fable's re-review of `168d97b`.** `TestRecentlyEditedOutlastsManyEditsToOnePage`: six team pages, then 900 edits to one, and all six are listed (with the old window capped at 200, only "Team page 6"; uncapped, the old code passed). `TestRecentlyEditedLeavesOutDeletedPages`: nine team pages, every third deleted, six live rows and no deleted title; `make mutate` drops only `NOT pages.gone` and must see it fail (the scoped view would still hide the deleted titles, but the list falls short of six). The M1 mutant now drops the query's rung filter.
- **Gates added after Fable's review of `8066d40`.** `TestRecentlyEditedOutlastsManyPrivateWrites`: seven team pages, then 210 scratch pages, and Recently edited holds team pages 2 to 7 (0 rows at `8066d40`); `make mutate` moves the rung filter out of the query and must see it fail. `TestOneFullHighlightForEachPage` also counts the rows lit with no CSS (2 without `hidden`).
81. **Link selected words to a page: Page link in the bubble, and ⌘L** (amends §6.6).
@@ -1348,3 +1358,11 @@ No review round after; each finding is answered with a gate shown red without th
| **L2** The bubble ignored a refused link | `linkCheck`'s refusal shown | the same test: never said "The selection changed" | `a7513f1` |
| **L3** Ctrl+L on a Mac fired in the textarea | Mod only (⌘ on Apple, Ctrl elsewhere) | `TestTheMarkdownScreenNeverReplacesASelection`: wrote "line [[one]]" | `07236bb` |
| **L4** With no CSS both the lit rail copy and the page row carried `aria-current` | The lit copy is `hidden` too (note 80) | `TestOneFullHighlightForEachPage`: "with no CSS 2 rows are lit" | `60421da` |
+
+**Addendum: Fable's re-review of `168d97b` — APPROVE**, landed as `4dcfbdf`. Three lows, on `fix/recent-query`:
+
+| Finding | Change | Gate, red without the fix | Commit |
+|---|---|---|---|
+| **L1** The widening window cost ~46ms a page view for a heavy editor of few team pages | One query: a loose scan of `idx_events_actor_page` (migration 0004), each page's newest write that counts, six (note 80, with before and after) | `BenchmarkRecentEdits20k` 45.8ms → 0.27ms, `200k` 47.3ms → 0.28ms; `TestRecentlyEditedReadsByIndex` holds the plan | `4ee3a36` |
+| **L2** "One page edited many times cannot hide the rest" was not gated | Gated | `TestRecentlyEditedOutlastsManyEditsToOnePage`: "Team page 6" alone with the window capped | `67cd217` |
+| **L3** `NOT pages.gone` was not gated on its own | Gated, and a mutant | `TestRecentlyEditedLeavesOutDeletedPages`; the mutant dropping only that clause | `67cd217` |
diff --git a/internal/mapa/migrations/0004_events_actor_page.sql b/internal/mapa/migrations/0004_events_actor_page.sql
new file mode 100644
index 0000000..5c0a116
--- /dev/null
+++ b/internal/mapa/migrations/0004_events_actor_page.sql
@@ -0,0 +1,2 @@
+CREATE INDEX `idx_events_actor_page` ON `events`(`actor_id`,`object_kind`,`object_id`);
+
diff --git a/internal/mapa/migrations/schema.sql b/internal/mapa/migrations/schema.sql
index 9f54774..43c1c36 100644
--- a/internal/mapa/migrations/schema.sql
+++ b/internal/mapa/migrations/schema.sql
@@ -29,6 +29,8 @@ CREATE INDEX `idx_drafts_updated_at` ON `drafts`(`updated_at`);
CREATE INDEX `idx_events_actor_id` ON `events`(`actor_id`);
+CREATE INDEX `idx_events_actor_page` ON `events`(`actor_id`,`object_kind`,`object_id`);
+
CREATE INDEX `idx_events_at` ON `events`(`at`);
CREATE INDEX `idx_events_object_id` ON `events`(`object_id`);
diff --git a/internal/mapa/models.go b/internal/mapa/models.go
index 72ac858..2ce9b37 100644
--- a/internal/mapa/models.go
+++ b/internal/mapa/models.go
@@ -136,13 +136,19 @@ type Draft struct {
// invisible to both, so store.go refuses to commit one (gate 8).
type Event struct {
ID int64
- Nonce int64 `gorm:"not null"`
- At time.Time `gorm:"not null;index"`
+ Nonce int64 `gorm:"not null"`
+ // At's index, idx_events_at, is named by Recently edited's bulk
+ // check (recent.go, INDEXED BY): drop or rename it and that query
+ // fails outright, taking Pinned and Recently edited off every page.
+ // TestRecentlyEditedReadsByIndex holds it (build note 80).
+ At time.Time `gorm:"not null;index"`
// ActorID is the person who made the change (suite ruling 9). Mapa
- // is never an actor.
- ActorID int64 `gorm:"not null;index"`
- ObjectKind string `gorm:"size:8;not null"`
- ObjectID int64 `gorm:"not null;index"`
+ // is never an actor. idx_events_actor_page is Recently edited's:
+ // a person's pages, each one step, and each page's writes newest
+ // first by the rowid it ends in (recent.go, build note 80).
+ ActorID int64 `gorm:"not null;index;index:idx_events_actor_page"`
+ ObjectKind string `gorm:"size:8;not null;index:idx_events_actor_page"`
+ ObjectID int64 `gorm:"not null;index;index:idx_events_actor_page"`
Verb string `gorm:"size:16;not null"`
// Revision is the object's revision after this event, or 0 for a
// verb that mints none.
diff --git a/internal/mapa/recent.go b/internal/mapa/recent.go
index b591376..3df9efe 100644
--- a/internal/mapa/recent.go
+++ b/internal/mapa/recent.go
@@ -2,6 +2,7 @@ package mapa
import (
"context"
+ "database/sql"
"net/http"
)
@@ -14,90 +15,78 @@ import (
const recentCount = 6
// recentVerbs are the writes that count as editing a page. Bulk link
-// edits on team pages log their own verbs and do not count (§8); they
-// are read only to recognise their transaction.
-var recentVerbs = []string{VerbCreated, VerbEdited, VerbReverted,
- VerbRelinked, VerbMarked}
+// edits on team pages log their own verbs (linkVerbs) and do not count
+// (§8); they are read only to recognise their transaction.
+var (
+ recentVerbs = []string{VerbCreated, VerbEdited, VerbReverted}
+ linkVerbs = []string{VerbRelinked, VerbMarked}
+)
+
+// recentQuery is Recently edited in one query (build note 80, review
+// round 6 L1): each live team page the person wrote in (the rung and
+// gone are plaintext, §4), at its newest write, newest first, six.
+//
+// A GROUP BY over the person's events reads every one of them: 13ms at
+// 20,000 and 150ms at 200,000, 36ms and 400ms with the bulk test. So
+// the pages are walked instead, one index step each (touched, a loose
+// scan of idx_events_actor_page), and each page's newest write is read
+// back from its end of that index, which stops at the first that
+// counts. The cost follows how many pages the person wrote in, not how
+// many times: 0.3ms at 20,000 or 200,000 events.
+//
+// An "edited" does not count when its transaction (one actor, one at)
+// also logged another "edited" or a link verb on a live team page:
+// bulk, as §3.2 and N1 define it. That test reads one transaction by
+// idx_events_at, named because the planner otherwise takes the person's
+// whole index for it. Link verbs never count themselves.
+const recentQuery = `
+WITH RECURSIVE touched(id) AS (
+ SELECT (SELECT MIN(object_id) FROM events
+ WHERE actor_id = @actor AND object_kind = @page)
+ UNION ALL
+ SELECT (SELECT MIN(object_id) FROM events
+ WHERE actor_id = @actor AND object_kind = @page
+ AND object_id > touched.id)
+ FROM touched WHERE touched.id IS NOT NULL
+),
+newest(page, last) AS (
+ SELECT touched.id, (SELECT e.id FROM events e
+ WHERE e.actor_id = @actor AND e.object_kind = @page
+ AND e.object_id = touched.id AND e.verb IN @verbs
+ AND NOT (e.verb = @edited AND EXISTS (
+ SELECT 1 FROM events other INDEXED BY idx_events_at
+ JOIN pages them ON them.id = other.object_id
+ WHERE other.at = e.at AND other.actor_id = e.actor_id
+ AND other.object_kind = @page AND other.id <> e.id
+ AND them.rung = @team AND NOT them.gone
+ AND (other.verb = @edited OR other.verb IN @links)))
+ ORDER BY e.id DESC LIMIT 1)
+ FROM touched JOIN pages ON pages.id = touched.id
+ WHERE pages.rung = @team AND NOT pages.gone
+)
+SELECT page FROM newest WHERE last IS NOT NULL
+ORDER BY last DESC LIMIT @limit`
// recentEdits is the team page ids the person last wrote in, newest
-// first, leaving out bulk edits: a transaction that logged more than
-// one "edited" (Update links on private pages, which keep "edited" so
-// the plaintext log says nothing of a private link graph; §3.2, N1).
-// Only events on team pages that still exist are read (the rung and
-// gone are plaintext, §4), so no number of private writes can push the
-// team pages out of the window read (review M1, build note 80); the
-// window grows until it holds recentCount pages or the whole history.
+// first, at most recentCount, leaving out bulk edits: a transaction
+// that logged more than one "edited" (Update links on private pages,
+// which keep "edited" so the plaintext log says nothing of a private
+// link graph; §3.2, N1), or a link verb. No number of private writes,
+// and no number of writes to one page, can push a team page out.
func (store *Store) recentEdits(ctx context.Context,
memberID int64) ([]int64, error) {
- for limit := recentWindow; ; limit *= 4 {
- rows, err := store.recentEvents(ctx, memberID, limit)
- if err != nil {
- return nil, err
- }
- ids := recentIDs(rows)
- if len(ids) >= recentCount || len(rows) < limit ||
- limit >= recentWindowMax {
- return ids, nil
- }
- }
-}
-
-// recentWindow is how many events Recently edited reads first, and
-// recentWindowMax the most it reads.
-const (
- recentWindow = 200
- recentWindowMax = recentWindow * 64
-)
-
-// recentEvents is the person's last limit events on live team pages.
-func (store *Store) recentEvents(ctx context.Context, memberID int64,
- limit int) ([]Event, error) {
- var rows []Event
- err := store.database.WithContext(ctx).Model(&Event{}).
- Joins("JOIN pages ON pages.id = events.object_id").
- Where("events.actor_id = ? AND events.object_kind = ? AND "+
- "events.verb IN ? AND pages.rung = ? AND NOT pages.gone",
- memberID, ObjectPage, recentVerbs, RungTeam).
- Order("events.id DESC").Limit(limit).Find(&rows).Error
- return rows, err
-}
-
-// recentIDs is the pages events name, newest first, once each, without
-// bulk edits and link verbs.
-func recentIDs(rows []Event) []int64 {
- bulk := bulkWrites(rows)
var ids []int64
- seen := map[int64]bool{}
- for _, row := range rows {
- if row.Verb == VerbRelinked || row.Verb == VerbMarked ||
- (row.Verb == VerbEdited && bulk[row.At.UnixNano()]) ||
- seen[row.ObjectID] {
- continue
- }
- seen[row.ObjectID] = true
- ids = append(ids, row.ObjectID)
- }
- return ids
+ err := store.database.WithContext(ctx).Raw(recentQuery,
+ recentArgs(memberID)...).Scan(&ids).Error
+ return ids, err
}
-// bulkWrites is each transaction (one actor, one at) that edited more
-// than one page, or that a link verb also names: "Update links" on
-// private pages logs "edited", and in a transaction with a team page it
-// sits beside "relinked" (review L3).
-func bulkWrites(rows []Event) map[int64]bool {
- edited := map[int64]int{}
- bulk := map[int64]bool{}
- for _, row := range rows {
- at := row.At.UnixNano()
- switch row.Verb {
- case VerbEdited:
- edited[at]++
- bulk[at] = bulk[at] || edited[at] > 1
- case VerbRelinked, VerbMarked:
- bulk[at] = true
- }
- }
- return bulk
+// recentArgs are recentQuery's named arguments for one person.
+func recentArgs(memberID int64) []any {
+ return []any{sql.Named("actor", memberID),
+ sql.Named("page", ObjectPage), sql.Named("verbs", recentVerbs),
+ sql.Named("links", linkVerbs), sql.Named("edited", VerbEdited),
+ sql.Named("team", RungTeam), sql.Named("limit", recentCount)}
}
// sideLists are Pinned and Recently edited for the viewer. A failure to
diff --git a/internal/mapa/recent_bench_test.go b/internal/mapa/recent_bench_test.go
new file mode 100644
index 0000000..dbbecee
--- /dev/null
+++ b/internal/mapa/recent_bench_test.go
@@ -0,0 +1,131 @@
+package mapa
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/db"
+
+ "amadan.net/oficina/mapa/internal/mapa/seal"
+)
+
+// Recently edited's cost for a heavy editor of few team pages (build
+// note 80, review round 6 L1): six team pages and n of the person's
+// edits on them, written straight to the event log.
+//
+// go test -run '^$' -bench RecentEdits ./internal/mapa/
+
+func benchStore(tb testing.TB) *Store {
+ tb.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ database, err := db.Open(filepath.Join(tb.TempDir(), "mapa.db"),
+ logger)
+ if err != nil {
+ tb.Fatal(err)
+ }
+ tb.Cleanup(func() { database.Close() })
+ sealer, err := seal.New(bytes.Repeat([]byte{3}, 32))
+ if err != nil {
+ tb.Fatal(err)
+ }
+ if _, err := App(database, Config{Sealer: sealer}, logger); err != nil {
+ tb.Fatal(err)
+ }
+ return NewStore(database.G, sealer)
+}
+
+// heavyEditor is a store holding count team pages one person created,
+// then events edits by them, spread over the first spread pages, and
+// that person's member id.
+func heavyEditor(tb testing.TB, events, count, spread int) (*Store,
+ int64) {
+ tb.Helper()
+ store := benchStore(tb)
+ var pages []int64
+ for number := range count {
+ page, err := store.CreateTeamPage(ctx(), "ana@example.com",
+ fmt.Sprintf("Page %d", number), "Text.")
+ if err != nil {
+ tb.Fatal(err)
+ }
+ pages = append(pages, page.ID)
+ }
+ var member Member
+ if err := store.database.First(&member).Error; err != nil {
+ tb.Fatal(err)
+ }
+ start := time.Now().UTC()
+ rows := make([]Event, 0, events)
+ for number := range events {
+ rows = append(rows, Event{Nonce: int64(number + 1),
+ At: start.Add(time.Duration(number) * time.Millisecond),
+ ActorID: member.ID, ObjectKind: ObjectPage,
+ ObjectID: pages[number%spread], Verb: VerbEdited})
+ }
+ if err := store.database.CreateInBatches(rows, 1000).Error; err != nil {
+ tb.Fatal(err)
+ }
+ return store, member.ID
+}
+
+func benchmarkRecentEdits(b *testing.B, events, count, spread int) {
+ store, member := heavyEditor(b, events, count, spread)
+ b.ResetTimer()
+ for b.Loop() {
+ ids, err := store.recentEdits(ctx(), member)
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.ReportMetric(float64(len(ids)), "pages")
+ }
+}
+
+// The edits on one page: the five others are found only by reading
+// past all of them.
+func BenchmarkRecentEdits20k(b *testing.B) {
+ benchmarkRecentEdits(b, 20000, 6, 1)
+}
+
+func BenchmarkRecentEdits200k(b *testing.B) {
+ benchmarkRecentEdits(b, 200000, 6, 1)
+}
+
+// The edits spread over all six: the newest few events find them.
+func BenchmarkRecentEditsSpread20k(b *testing.B) {
+ benchmarkRecentEdits(b, 20000, 6, 6)
+}
+
+// A person who wrote in 1,000 team pages: one step per page.
+func BenchmarkRecentEditsWide200k(b *testing.B) {
+ benchmarkRecentEdits(b, 200000, 1000, 1000)
+}
+
+// The plan reads events only through indexes (review round 6 L1): the
+// person's pages by idx_events_actor_page, a transaction by
+// idx_events_at, and never a scan of the table.
+func TestRecentlyEditedReadsByIndex(t *testing.T) {
+ store, member := heavyEditor(t, 50, 6, 6)
+ var plan []struct{ Detail string }
+ err := store.database.Raw("EXPLAIN QUERY PLAN "+recentQuery,
+ recentArgs(member)...).Scan(&plan).Error
+ if err != nil {
+ t.Fatal(err)
+ }
+ var lines []string
+ for _, step := range plan {
+ lines = append(lines, step.Detail)
+ }
+ all := strings.Join(lines, "\n")
+ if strings.Contains(all, "SCAN events") || strings.Contains(all,
+ "SCAN e ") || strings.Contains(all, "SCAN other") ||
+ !strings.Contains(all, "idx_events_actor_page") ||
+ !strings.Contains(all, "INDEX idx_events_at") {
+ t.Fatalf("the plan:\n%s", all)
+ }
+}
diff --git a/internal/mapatest/sidebar_ruling_test.go b/internal/mapatest/sidebar_ruling_test.go
index d4db0dc..aa8074b 100644
--- a/internal/mapatest/sidebar_ruling_test.go
+++ b/internal/mapatest/sidebar_ruling_test.go
@@ -1,6 +1,7 @@
package mapatest
import (
+ "context"
"fmt"
"net/http"
"net/http/httptest"
@@ -8,6 +9,8 @@ import (
"strings"
"testing"
"time"
+
+ "amadan.net/oficina/mapa/internal/mapa"
)
// Paul's ruling of 2026-11-16 on the sidebar (build note 80), as the
@@ -216,3 +219,74 @@ func TestRecentlyEditedOutlastsManyPrivateWrites(t *testing.T) {
}
}
}
+
+// recentRows is the titles in Ana's Recently edited, in order.
+func recentRows(t *testing.T, rig *rig) []string {
+ t.Helper()
+ recent := between(sideNav(rig.page(t, Ana, "/pages")),
+ "Recently edited", "mapa-side-foot")
+ var titles []string
+ for _, row := range strings.Split(recent, "<span mapa-side-label>")[1:] {
+ title, _, _ := strings.Cut(row, "<")
+ titles = append(titles, title)
+ }
+ return titles
+}
+
+// Six team pages, then 900 edits to one: the other five are still
+// there (review round 6 L2). A window of the newest events, capped,
+// held only the one page.
+func TestRecentlyEditedOutlastsManyEditsToOnePage(t *testing.T) {
+ rig := newRig(t)
+ ctx := context.Background()
+ var heavy mapa.Page
+ for number := 1; number <= 6; number++ {
+ page, err := rig.built.Store.CreateTeamPage(ctx, Ana,
+ fmt.Sprintf("Team page %d", number), "Text.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ heavy = page
+ }
+ revision := heavy.Revision
+ for number := range 900 {
+ if _, err := rig.built.Store.Commit(ctx, Ana, heavy.ID, revision,
+ fmt.Sprintf("Edit %d.", number)); err != nil {
+ t.Fatal(err)
+ }
+ err := rig.db.G.Raw("SELECT revision FROM pages WHERE id = ?",
+ heavy.ID).Scan(&revision).Error
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ got := strings.Join(recentRows(t, rig), ", ")
+ if got != "Team page 6, Team page 5, Team page 4, Team page 3, "+
+ "Team page 2, Team page 1" {
+ t.Fatalf("Recently edited: %s", got)
+ }
+}
+
+// Deleted team pages among the recent writes leave six live rows, and
+// no deleted title (review round 6 L3).
+func TestRecentlyEditedLeavesOutDeletedPages(t *testing.T) {
+ rig := newRig(t)
+ ctx := context.Background()
+ for number := 1; number <= 9; number++ {
+ page, err := rig.built.Store.CreateTeamPage(ctx, Ana,
+ fmt.Sprintf("Team page %d", number), "Text.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if number%3 == 0 {
+ if err := rig.built.Store.Delete(ctx, Ana, page.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ got := strings.Join(recentRows(t, rig), ", ")
+ if got != "Team page 8, Team page 7, Team page 5, Team page 4, "+
+ "Team page 2, Team page 1" {
+ t.Fatalf("Recently edited: %s", got)
+ }
+}
diff --git a/scripts/mutate/mutations.go b/scripts/mutate/mutations.go
index aba8b39..1dc7f6f 100644
--- a/scripts/mutate/mutations.go
+++ b/scripts/mutate/mutations.go
@@ -109,12 +109,13 @@ var mutations = []mutation{
"pageID, from).",
to: "\t\tWhere(\"page_id = ?\", pageID)."}}},
{gate: "80", test: "TestRecentlyEditedOutlastsManyPrivateWrites",
- name: "Recently edited filters team pages after its window " +
- "of events",
+ name: "Recently edited's query reads private pages too",
edits: []edit{{file: recent,
- from: "\"events.verb IN ? AND pages.rung = ? AND " +
- "NOT pages.gone\",\n" +
- "\t\t\tmemberID, ObjectPage, recentVerbs, RungTeam).",
- to: "\"events.verb IN ?\",\n" +
- "\t\t\tmemberID, ObjectPage, recentVerbs)."}}},
+ from: " WHERE pages.rung = @team AND NOT pages.gone\n)",
+ to: " WHERE NOT pages.gone\n)"}}},
+ {gate: "80", test: "TestRecentlyEditedLeavesOutDeletedPages",
+ name: "Recently edited's query reads deleted pages too",
+ edits: []edit{{file: recent,
+ from: " WHERE pages.rung = @team AND NOT pages.gone\n)",
+ to: " WHERE pages.rung = @team\n)"}}},
}