Debugging
Lessons learned from bugs, investigations, and things that went wrong.
General Principles
- Read the error message. The whole error message.
- Reproduce before fixing. If you can't trigger it, you don't understand it.
- Don't brute force. If something is blocked, step back and think about why.
- When a test fails, read the test first — the test might be wrong.
Known Gotchas
YAML Auto-Typing
YAML will silently convert strings like yes, no, on, off to booleans. This is why frontmatter is parsed as map[string]string — we control the type conversion ourselves.
Symlink Resolution in Tests
When testing the versioned store, be careful with os.ReadFile vs following symlinks. The store creates doc.md -> versions/doc.md.v3 — some operations need the symlink target, others need the symlink itself.
Path Traversal
filepath.Clean handles most cases but you still need an explicit .. check after cleaning. A path like /../../../etc/passwd cleans to /etc/passwd which looks valid but is outside the content root. The check is: clean the path, then verify it doesn't escape the root.
QUIC Stream Lifecycle
Streams must be closed properly. If a handler panics or returns without closing the stream, the client hangs waiting for data. Always defer stream close.
Debugging Approach for This Project
- Write a failing test that reproduces the issue
- Fix the code
- Verify the test passes
- Check if the fix breaks anything else (
make test) - Run
bash pre-commit.sh
The test-first approach isn't dogma here — it's practical. A test that reproduces the bug proves you understand the bug, and it prevents regression.
QUIC UDP Buffer Size Warning
When running demarkus in CI or containerized environments, quic-go logs this warning:
failed to sufficiently increase receive buffer size (was: 1024 kiB, wanted: 7168 kiB, got: 2048 kiB)
Not a failure. quic-go tries to increase the UDP receive buffer to 7168 kiB for optimal performance. In environments with restricted sysctl limits, it can only get partway there. The connection still works — everything publishes fine.
Fix (if needed): Increase the system limit with sysctl -w net.core.rmem_max=7168000. Not necessary for correctness, only for optimal throughput under heavy load.
First seen: CI publishing content to demarkus-hub (hub.demarkus.io).
OnNode Callback Concurrency
graph.Crawl invokes OnNode from multiple worker goroutines. Any mutable state captured by the callback must use sync/atomic or a mutex. The CrawlAndPersist MaxNodes counter uses atomic.Int32 for this reason. Always run go test -race on packages that use OnNode.
Glamour WithAutoStyle() Blocks TUI Rendering
Symptom: TUI shows "Loading..." for up to 60 seconds after fetch completes. Server logs confirm the FETCH is handled immediately. CLI works fine. A mouse scroll "unsticks" the display.
Root cause: glamour.WithAutoStyle() calls termenv.HasDarkBackground(), which sends an OSC 11 escape sequence to the terminal and reads the response from stdin. But Bubbletea is also reading stdin for input events. This causes two problems:
- Stdin contention — Bubbletea's input goroutine may consume the OSC 11 response, so termenv never sees it and blocks for the full 5-second timeout.
- Render corruption — The stdin race breaks Bubbletea's render cycle, leaving the view stuck on "Loading..." even though the model state has been updated. A mouse event forces a fresh render, which is why scrolling "fixes" it.
The TUI recreated the glamour renderer on every window resize (to update word wrap width), re-triggering the query each time. Multiple resize events at startup compounded into 30-60 seconds of blocking.
Fix: Detect dark/light background once in main() before tea.NewProgram().Run() takes over stdin. Pass the resolved style name ("dark" or "light") into the model. Use glamour.WithStandardStyle(styleName) instead of glamour.WithAutoStyle() — this hits the DefaultStyles map lookup directly, bypassing the terminal query entirely. Also added a -style flag so users can skip detection.
Guard: Both stdin and stdout must be terminals before attempting detection. If either is piped, fall back to dark.
Key insight: Never do terminal escape sequence queries inside a Bubbletea event loop. Bubbletea owns stdin once it starts. Any library that reads stdin for terminal responses will race with Bubbletea's input goroutine.
TUI Link Highlighting: Marker Injection and the Glamour Black Box
Context: The TUI needs to highlight the selected link in the rendered markdown and support clickable links. But glamour's API is Render(string) → string — a black box. It doesn't expose the goldmark AST it builds internally, and the rendered ANSI output doesn't preserve link structure. Link URLs are stripped from the output; only styled text remains.
Problem: We parse the markdown twice with goldmark. Once in links.ExtractWithPositions to get link destinations and their byte offsets in the source, and again inside glamour to render. If glamour exposed its pre-parsed AST (or accepted one), we could do a single parse, extract link positions, and annotate nodes directly for highlighting.
Workaround: Marker injection. Before passing markdown to glamour, we inject Unicode private-use-area codepoints (U+F0000 range) around each link's text inside the [...] brackets. Glamour treats them as literal characters and passes them through to the rendered output. After rendering, processMarkers scans the ANSI output, finds the markers, records their screen coordinates as linkRegion entries, and strips them (or replaces with ANSI reverse-video for highlighted links).
Goldmark AST quirks for link positions:
ast.Linknodes don't expose the byte offset of[or]directly. You have to walk the link's childast.Textnodes to get theirSegment.StartandSegment.Stop, then scan backward/forward in the source to find the brackets.- Links with inline formatting (e.g.,
[hello **world**](url)) have multiple child nodes. The**markers sit between text segments but aren't text nodes themselves, soSegment.Stopof one child doesn't equalSegment.Startof the next. link.Text(source)is deprecated in newer goldmark versions. Use the child text segments directly and build the text yourself.- Links with no text nodes (e.g.,
[](url)) produce no text segments.ExtractWithPositionshandles this by emitting aLinkInfowithOpenBracket: -1so the link is still in the navigation list but skipped during marker injection.
Region extension for clickable URLs: Glamour renders links as bold text followed by an underlined URL. The end marker sits after the text but before the URL. processMarkers extends each region past the end marker to also cover the URL portion, scanning forward through the space and URL characters and stopping at the next space. This makes both the text and URL clickable.
Marker limit: Start markers use U+F0000+i, end markers use U+F1000+i. Maximum 4096 links per document before the ranges overlap. injectLinkMarkers caps at maxMarkedLinks; excess links render normally but without highlighting or click detection.
Mouse mode: tea.WithMouseCellMotion() only delivers motion events when a button is held. Hover requires tea.WithMouseAllMotion().