ArcMD is a Markdown editor in Go drawn with MyGo. Its bookmark cache uses two uint64 counters to avoid repeating work while the UI rebuilds.
· 6 min read

Two counters, one map: how ArcMD avoids per-frame work


A linear scan may be cheap once and still be the wrong thing to repeat on every render. ArcMD, a Markdown editor written in Go, avoids that trap with a few small caches.

The interface is drawn with MyGo v0.7.4’s ui package. Its package comment describes an Arc- and Zen-inspired layout: pinned documents and folders in a sidebar, a toolbar containing the document address, and the document itself in a rounded card. The more useful lesson is how the code avoids recomputing the same data as that interface is rebuilt.

Open internal/app/bookmarks.go and the first type you meet is this:

type docMarks struct {
	rev, gen   uint64
	known      bool
	bound      bool
	m          map[string]string
	excerptRev uint64
	excerptGen uint64
}

The first counter pair guards the resolved map. The second records when bookmark excerpts were last written back. Keeping those two jobs separate is important later.

Why per-frame work is the problem

The code in internal/app/carddrag.go and internal/app/app.go talks in frames. App documents overClose as “the row whose minus is under the pointer this frame, overClosed the one the frame before.” cardOrder returns a copy because “a grip moving a space as the row builds changes the next frame’s.” Widgets get built inside functions that take a *ui.Context and query state inline: grip.Hovered(), grip.Dragged(), grip.Shortcut(0, ui.KeyLeft).

The widget tree is rebuilt as the app draws, so uncached work in that path runs again on the next pass.

Now look at what marksOf does on a miss. Bookmarks live in spaces.json rather than inside the document, which keeps marking a place from editing the file. The price is that a bookmark has to find its block by ID at runtime. marksOf walks every bookmark in a.state.Bookmarks, filters to the current document, and calls topBlock for each:

func topBlock(d *document, id string) *model.Block {
	for _, b := range d.ed.Doc.Blocks {
		if b.ID == id {
			return b
		}
	}
	return nil
}

That is a linear scan of the document’s top-level blocks for each bookmark. The first resolution can do more: a document read fresh from Markdown has new block IDs, so a bookmark whose ID is missing triggers another scan for a matching editor.BlockExcerpt. It also checks a.state.BookmarkIndex so two bookmarks do not claim the same block. This is useful recovery work, but not work to repeat while drawing the sidebar.

Two counters, because there are two sources of change

The guard at the top of marksOf is the bit worth stealing:

mk := &d.marks
rev := d.ed.Revision()
if mk.known && mk.rev == rev && mk.gen == a.bookmarkGen {
	return mk.m
}

Both counters have to match. d.ed.Revision() changes when the editor model changes. a.bookmarkGen is a field on App, documented as counting “changes to the bookmarks, which documents resolve again.” It changes when a bookmark is added, removed or relabelled anywhere in the app.

Why both? The resolved map depends on two independently changing inputs. A document edit may delete or restore a bookmarked block; a bookmark change alters the set and labels being resolved. Keeping the document revision local also avoids invalidating every document when only one is edited.

Invalidation is one line:

func (a *App) bookmarksChanged() {
	a.bookmarkGen++
	a.saveState()
}

There is no cache walk, subscriber list or back-pointer from the bookmark store to every open document. Every docMarks becomes stale logically and is recomputed the next time it is requested. The implementation needs only one uint64 on the owner and the last-seen value on each cache entry.

Here’s the shape as a standalone helper. This is illustrative, not lifted from ArcMD:

package cache

// Memo caches a value derived from two independently changing inputs.
type Memo[T any] struct {
	rev, gen uint64
	known    bool
	val      T
}

// Get returns the cached value, recomputing it only when either counter moved.
func (m *Memo[T]) Get(rev, gen uint64, compute func() T) T {
	if m.known && m.rev == rev && m.gen == gen {
		return m.val
	}
	m.val = compute()
	m.rev, m.gen, m.known = rev, gen, true
	return m.val
}

One sharp edge: marksOf returns mk.m itself, not a copy. Callers have to treat it as read-only, but the type system does not enforce that. If you copy the pattern, document the ownership rule.

A separate pair of counters for the write side

syncExcerpts pushes the current text of bookmarked blocks back into the bookmarks, so lists show what the block says now rather than what it said when you marked it. Different operation, different cadence, its own counters:

if mk.excerptRev == rev && mk.excerptGen == a.bookmarkGen || d.dirty() {
	return
}

The extra condition matters: excerpt write-back waits while the document is dirty. This operation needs its own last-seen pair because resolving bookmarks and syncing excerpts can happen at different times. If they shared counters, either operation could make the other appear current even though it had not run. Two additional uint64 fields keep the states independent.

Single-slot caches keyed by what they were computed for

App holds the sidebar tree like this:

tree    []*vault.Node
docs    []*vault.Node
treeFor string
treeErr error

The comment: tree and docs are “the folders and documents of treeFor, the space they were read for; docs lists the documents in tree order.” A one-entry cache keyed by space ID. Switch spaces and the key stops matching, so the filesystem read happens again; stay put and it doesn’t.

treeErr is cached with the same key, so a failed read is remembered just like a successful one until the space changes or refreshTree clears the key. That prevents a persistent folder error from becoming a retry loop in the render path.

Per-space UI state goes in sessions map[string]*spaceSession: the document the space was showing when you left it, a ui.ScrollState for the tree, the split group and whether it was shown. The comment draws the line in one sentence: “The Markdown file remains authoritative.” Caches hold view state. The file on disk holds truth.

Animations that report when they’re done

movedCardX in carddrag.go returns where a dragged space card should sit and whether it’s still moving:

if a.reduceMotion || p >= 1 {
	return to, false
}
return m.x + (to-m.x)*listAnim.Ease(max(p, 0)), true

The false tells the caller that the movement has settled. The caller then clears the move instead of requesting another animation frame. a.reduceMotion jumps straight to the target; otherwise ArcMD interpolates across cardSettle, fixed at 220 * time.Millisecond.

Keep slow work off the frame entirely

internal/app/attachments.go handles the other half. Native file dialogs block, so pickImages runs the dialog in a goroutine and marshals the result back:

go func() {
	paths, err := mygo.Dialog.Open(opts)
	if err == nil && len(paths) > 0 {
		win.Update(func() { done(paths) })
	}
}()

win is captured into a local before the goroutine starts, not read off a from inside it. The state mutation happens in the function handed to win.Update, not in the goroutine body.

Then the callback re-checks the world it left behind:

done := func(paths []string) {
	if a.residentDocument(d.space.ID, d.rel) == d {
		a.withDocument(d, func() { a.insertImages(paths, -1) })
	}
}

The user could have closed the document, or closed and reopened it, while the dialog was up. The pointer comparison against residentDocument catches both. pickCover goes further: its callback re-checks d.ed.ReadOnly even though pickCover checked it before opening the dialog, and verifies that the selected path has a supported image extension. The callback validates the state it is about to change instead of relying on the state from before the dialog opened.

None of this is MyGo-specific. Revision-keyed caches, one-entry caches and re-checking state after asynchronous work apply to any repeated view-building path. If MyGo’s own API is what you’re curious about, there is a separate write-up on its design.