15c0c35df6
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
31 KiB
31 KiB
id, title, status, wave, depends_on, plan, spec
| id | title | status | wave | depends_on | plan | spec | |
|---|---|---|---|---|---|---|---|
| session-hostname-resolution-02 | Backend reverse-DNS lookup, cache, and streaming | pending | 2 |
|
docs/plans/session-hostname-resolution/plan.md | docs/specs/session-hostname-resolution/spec.md |
Backend reverse-DNS lookup, cache, and streaming
Inputs
The spec (Lookup pipeline,
Streaming, Persistence, Failure modes sections) and Task 01's
resolve_session_hostnames setting. Existing patterns:
internal/auth/store schema init, internal/gateway/websocket/user_notifications.go
broadcaster, internal/integrations/healthpoll Start/Stop goroutine shape,
backend AGENTS.md schema-replay rule (ADR 0027).
TDD sequence
- Add failing tests for
NormalizeHostname(trailing dot, empty,.in-addr.arpa/.ip6.arpasuffix rejection, first-valid-record selection: a generic first record followed by a valid second record yields the valid one). - Add failing tests for the cache store (
CacheEntryround trip viaGetMany, absent-vs-cached-empty distinction,resolved_atfixed 9-digit RFC3339 UTC text round trip, and a schema replay test: fresh-DBinitSchemaplus re-runninginitSchemaon the same DB is a no-op; include Postgres-gated fresh + replay coverage because the store is wired over the productiondbPool, mirroring the auth store test harness). - Add failing tests for the resolver:
- disabled gate: setting off returns an empty map (no cached values) and schedules nothing;
- gate read error: the settings provider returning an error behaves exactly like disabled — empty map, no lookups scheduled, no DNS queries, logged (fail closed, opt-in unknown means no lookups);
- cached values returned immediately when enabled (via one
GetManycall, not per-IP reads); - absent vs cached-empty: an IP with no cache row schedules a lookup;
an IP cached as no-answer (
hostname == ""with aResolvedAtwithinrecentResolveWindow) does not; - stale/fresh: an IP cached within
recentResolveWindowis not re-queried; an older one is; - in-flight dedup registers an interested user instead of a second lookup;
- raw-IP key contract: triggering with
::ffff:192.0.2.10and192.0.2.10runs ONE job (canonical dedup) and publishes two events, each carrying the triggering user's own raw spelling — including two sessions of the SAME user with different raw spellings of the same canonical IP (both rows must receive events); - interested-set lifecycle: snapshot+clear each IP's interested
pairs exactly once on every terminal path (publish, no-change,
dequeue-gate skip, cache-fresh equal, cache-read error,
Seterror, nil bus), with a churn/cleanup test asserting no completed interest survives and in-flight merges are retained; - a changed result persists + publishes once to all interested users; an unchanged result publishes nothing;
- DNS error classification: a
*net.DNSErrorwithIsNotFound(NXDOMAIN/no PTR — the common no-answer case) is a successful negative result: persisted ashostname = ""and published when changed, then skipped byrecentResolveWindowon the next trigger; a timeout / temporary / server error yields""not persisted, and is published only when the IP has no cache entry — never over an existing cached value (regression: stale cacheold.example+ transient error publishes nothing, and re-enable/list still returnsold.example); - Set-on-success: a same-value successful lookup (valid or
IsNotFound) stillSets and refreshesresolved_at(publishing nothing when the hostname is unchanged), so the very next trigger is skipped byrecentResolveWindow— a stale timestamp that never refreshes would re-query on every trigger; - cached-empty requery: a cached no-answer row whose freshness has
expired (
ResolvedAtolder thanrecentResolveWindow) is re-queried on the next trigger; when the retry finds a valid answer the change persists and publishes (regression: cached-empty → later valid answer after the window); - fire-and-forget trigger:
TriggerUserSessionsResolved(userID)returns immediately (does not block on settings/session/cache reads), the work runs on the resolver-owned context, andClose()joins the trigger goroutine (goleak); - admission never drops: more distinct IPs than workers all resolve
eventually (deterministic
N > lookupWorkerspending-set drain test with blocked/fake lookups proving the complete-then-recheck invariant); IPs admitted while all workers are busy are not stranded; - stale-read-after-completion race: user B's snapshot read sees the
old cache value, a concurrent job persists a new value (now fresh
within
recentResolveWindow), and B then enqueues from its stale read — the worker must skip the DNS query but publish the current cache value to B (their observed value differs), never silently drop the update; - context ownership: canceling the request context does not cancel the
in-flight lookup, and
Close()joins workers (goleak); - IP canonicalization: invalid IPs are skipped; equivalent IPv6 spellings produce one cache row and one job;
- cache-error semantics via the
Cacheinterface: aGetManyerror on the API path returns empty entries for the affected IPs and schedules nothing; on completion **ErrNotFoundis a successful absent baseline (absent + transient error publishes""without persisting; absent + valid result persists and publishes) while non-ErrNotFoundcache errors suppress both persist and publish; aSeterror publishes nothing (changed-only semantics; the next trigger retries the persist, and a later successfulSetthat changes the cache publishes) and does not panic; a nil event bus still returns cached values; - entry semantics:
CacheEntrycovers unknown (absent from map /ResolvedAtnil), cached-no-answer (ResolvedAtnon-nil,Hostname""), and durable (ResolvedAtnon-nil,Hostnamenon-empty); the handler emitshostname_resolved_atJSONnullwhenResolvedAtis nil;
- Add failing httpapi test:
GET /api/v1/auth/sessionsincludes per-sessionhostnamekeyed by raw IP; with the toggle off everyhostnameis""even when the cache has values (no leak); a cache/settings failure still returns 200 withhostname: ""(the resolver method never errors); user-service test: PATCH totruefires the resolver hook, and a non-canonical stored IP triggered through the hook (before any sessions GET) publishes an event with the raw stored spelling. - Add failing gateway tests in
user_notifications_test.go: memory and NATS-shaped delivery ofauth.session.hostname.resolvedroutes to theuser_idowner only, stripsuser_idfrom the payload, and leavesip,hostname, andresolved_atintact — for both a fixed 9-digit RFC3339 UTC timestamp and a JSONnullvalue (both must survive both transports; a droppedresolved_atbreaks the frontend newer-wins reconciliation). Also assert the internal event map the broadcaster receives containsuser_id(routing depends on it; an implementer publishing only{ip, hostname, resolved_at}would dead-end the stream). - Add a failing resolver event-handler test: a persisted
UserSettingsUpdatedevent withresolve_session_hostnames: truequeues a session pass for its user. A false or malformed event does not queue work. - Implement the smallest production code that makes the tests pass.
Implementation
- New package
apps/backend/internal/auth/hostnames:store.go:CacheEntry{Hostname string; ResolvedAt *time.Time}—ResolvedAtis*time.Time(nil = no row/unknown; a cached no-answer has a non-nilResolvedAtwithHostname == "");Storeover writer/reader*sqlx.DBwithinitSchemacreatingauth_hostname_cache (ip TEXT PRIMARY KEY, hostname TEXT NOT NULL DEFAULT '', resolved_at TEXT NOT NULL); implements a narrowCacheinterface:GetMany(ctx, ips []string) (map[string]CacheEntry, error)(one dialect-safeINquery, chunked to stay under parameter limits; absent IPs are simply absent from the map, so cached-no-answer (hostname == ""present) is distinguishable from never-resolved),Get(ctx, ip) (CacheEntry, error)(sentinelErrNotFound), andSet(ctx, ip, hostname, resolvedAt time.Time). Time representation: define ONE shared timestamp formatter as an exported API of thehostnamespackage —hostnames.FormatTimestamp(time.Time) stringandhostnames.ParseTimestamp(string) (time.Time, error)— backed by a singletimestampLayoutconstant ("2006-01-02T15:04:05.000000000Z07:00"). The helpers must be exported because thehttpapihandler (a different package) emits thehostname_resolved_atAPI field, and the resolver emits the WS eventresolved_at; unexported helpers would force duplication of the layout and risk drifting from the exact fixed-width UTC ordering contract. Use them everywhere: store reads and writes, the sessions APIhostname_resolved_atfield, and WS eventresolved_at.FormatTimestampwritesresolvedAt.UTC().Format(timestampLayout)(UTC, so the zone is alwaysZ, exactly 9 fractional digits). The fixed width makes the stored/emitted strings lexicographically comparable in chronological order in both Go and JavaScript (unliketime.RFC3339, which drops fractions, andtime.RFC3339Nano, which trims trailing zeros — either would break string ordering for same-second or same-millisecond changes). Add sub-millisecond ordering tests at the store, handler, and gateway layers asserting the exact 9-digit output, plus a cross-package test proving the handler emits the same helper output as the store (one formatter, one contract). This is dialect-portable across the SQLite/Postgresdb.Pool— scanning a raw TEXT column directly intotime.Timeis not — and matches the explicit-parse pattern used elsewhere in the codebase. New table, soCREATE TABLE IF NOT EXISTSininitSchemais the whole migration; it must be replay-safe (see TDD step 2), with required Postgres fresh+replay coverage because the resolver is wired over the productiondbPool(not conditional).normalize.go:NormalizeHostname(names []string) string— examine records in order and return the first one that normalizes to a valid hostname: trim trailing dot; reject empty names and names ending in.in-addr.arpa/.ip6.arpa(case-insensitive); if none is valid return"".resolver.go:Resolverwith constantslookupWorkers = 4,lookupTimeout = 3s,recentResolveWindow = 30s; injectableLookupAddrdefaulting tonet.DefaultResolver.LookupAddr; depends on theCacheinterface (not the concrete store) so tests can inject read and write failures.- Admission (no drops, no missed updates): pending entries carry
the observed cache value the trigger read (
pending map[canonicalIP]observedCacheEntry) plus the interested users; the worker loop selects on the wakeup channel / stop channel, then drains pending. - Dequeue-time privacy gate: immediately before calling
LookupAddr, the worker re-reads the settings gate for every interested user (fail closed on error) and drops users who disabled the toggle since admission; if no interested user remains enabled, the job is skipped entirely — no DNS query runs while the toggle is off, even for work admitted while it was on. Jobs whose DNS already started are "in flight" and may complete (their events go only to the still-interested users). Regression test: enable → admit an IP → disable before dequeue →LookupAddris never called and no event is published. For each admitted IP: if already in flight, merge the interested users into the running job; if the cache is now withinrecentResolveWindow(fresh), skip the DNS query but compare the current cached hostname against the observed hostname and publish the current value to the job's interested users when they differ — a user who scheduled from a stale snapshot must still learn of the change that happened since their read; if the observed hostname equals the current cached hostname, publish nothing (the diff compares the hostname, never the timestamp, which refreshes on every successful lookup). Otherwise run the lookup. Wakeup invariant: after completing a lookup, each worker must re-check and drainpendingagain before blocking on the wakeup channel — the wakeup channel only wakes idle workers; progress while all workers are busy comes from the complete-then-recheck loop. This is the complete-then-recheck invariant's companion: IPs are never discarded because the queue is full, never stranded because every completion re-drains, and never silently skipped past a value the requester already saw. - Context ownership: workers and the trigger goroutine run on a
resolver-owned context derived at
Startand canceled byClose(). Request/service contexts are used only for the synchronous cache and settings reads insideHostnamesForSessionIPs; they never reachnet.LookupAddrand never outlive their request. - In-flight set + interested-user set under one mutex. The interested
set is keyed by canonical IP and maps
userID -> set[rawIP](every triggering session's stored spelling, so one user with two spellings of the same IP keeps both):Start(ctx)spawning workers +Close()joining them (idempotent, goleak-verified). - Interested-set lifecycle (bounded, tested): each job snapshots
and clears its IP's interested pairs exactly once when it resolves
OR is skipped, on every terminal path — publish, no-change
(observed hostname equals current), dequeue-gate skip (no enabled
users), cache-fresh observed-diff equal, non-
ErrNotFoundcache-read error,Seterror, and nil event bus. Only interests merged into an already-running job (in-flight dedup) survive until that job's own terminal path. A user who triggers again after completion re-registers fresh. This prevents unbounded stale routing state under session/IP/user churn; add a churn/cleanup test that triggers, completes, re-triggers from many users/IPs and asserts the set never retains completed interests. - Fire-and-forget trigger: the resolver owns a buffered trigger
queue plus a pending-user set (same no-drop pattern as the IP pending
set);
TriggerUserSessionsResolved(userID string)enqueues the user and returns immediately. A trigger goroutine (spawned byStart, joined byClose) drains the queue on the resolver-owned context: read the settings gate (fail closed on error), fetch the user's raw session IPs, and schedule lookups. The PATCH hook path never blocks on settings/session/cache reads and never inherits the request context. HostnamesForSessionIPs(ctx, userID string, ips []string) map[string]CacheEntry— exact contract: keyed by the raw input spelling (the handler mapsm[session.IP]directly with no canonicalization of its own), one entry per valid input IP (Hostname""andResolvedAtnil when no hostname is known), invalid/empty input IPs absent from the map. The method never returns an error and never fails the caller: every degradation is logged internally — settings gate read error → empty map, no lookups (fail closed); cacheGetManyerror → empty entries for the affected IPs, no lookups scheduled for them (unknown baseline); per-IP invalid entries skipped. When the setting is off or unreadable, the map is empty (cached values must not leak and DNS must never run while opt-in is unknown). When on: validates each IP withnet.ParseIP(skipping invalid), keeps the raw spelling for interested registration, canonicalizes (ip.String()) for cache/job keys, reads the cache with oneGetManycall, returns cached hostnames with theirResolvedAt, and schedules lookups for IPs that are absent or stale. The synchronous portion is one settings read + one cache query (fast); scheduling is async.- On completion: canonical IP key; compare with the cache. Every
successful lookup — valid records and
IsNotFoundnegatives — persists viaSet(refreshingresolved_at) even when the hostname is unchanged, sorecentResolveWindowactually engages for no-answer and stable rows; a same-value success that skippedSetwould leave a stale timestamp and re-query on every trigger. Publishevents.AuthSessionHostnameResolved{user_id, ip, hostname, resolved_at}only when the hostname value changed (first resolution counts as changed), where the publishedipis each interested (user, raw spelling) pair (one event per pair) andresolved_atis the persisted row's fixed 9-digit RFC3339 UTC time, formatted with the shared exportedhostnames.FormatTimestamphelper (ornullfor a non-persisted transient result).ErrNotFoundis a successful absent baseline, not an error: with an absent row a transient failure may publish""(nothing to mask) and a valid/IsNotFoundresult persists normally. Only non-ErrNotFoundcache errors on completion skip persist + publish (baseline unknown). ASeterror logs and publishes nothing: the value was not persisted, so changed-only semantics do not admit an event (publishing a transient value would outlive its own retry and make the frontend ordering inconsistent); the next trigger retries the persist, and a later successfulSetthat changes the cache publishes normally.resolved_at: nullstays reserved for transient DNS errors streamed over an absent cache (empty-string events), never for failed writes. Neither ever panics or fails the caller. Result classification:- valid record(s): hostname from
NormalizeHostname(may be""for generic answers); *net.DNSErrorwithIsNotFound: successful negative answer,hostname = "", persisted;- other errors (timeout/temporary/server):
""not persisted, and published only when the IP has no cache entry — a transient failure must never stream""over an existing cached value, because the client treats the streamed map as authoritative and a masking empty would pin the row toN/Auntil identity reset. A nil event bus is guarded (skip publish, keep persisting).
- valid record(s): hostname from
- Admission (no drops, no missed updates): pending entries carry
the observed cache value the trigger read (
apps/backend/internal/auth/service.go: addSessionIPs(ctx, userID) ([]string, error)— the user's session IPs as raw stored spellings: skip empty values, validate withnet.ParseIP(skip invalid), dedupe exact string duplicates only. Canonicalization is the resolver's job (job/cache keys); raw spellings must survive for event payloads.apps/backend/internal/events/types.go:AuthSessionHostnameResolved = "auth.session.hostname.resolved".apps/backend/pkg/websocket/actions.go:ActionSessionHostnameResolved = "auth.session.hostname.resolved".apps/backend/internal/gateway/websocket/user_notifications.go: addb.subscribe(eventBus, events.AuthSessionHostnameResolved, ws.ActionSessionHostnameResolved). The resolver publishes amap[string]interface{}with literal keysuser_id,ip,hostname, andresolved_at(matching the map-shaped convention ofpublishUserSettingsEvent) so both memory and NATS transports route byuser_id, the broadcaster strips it correctly, and the frontend receives the timestamp it needs for newer-wins reconciliation.apps/backend/internal/auth/httpapi/handlers.go:RegisterRoutes(router, svc, resolver, log);listSessionsbuilds items fromresolver.HostnamesForSessionIPs(ctx, userID, ips)(raw-keyed, so no canonicalization in the handler; the method never returns an error):"hostname": entry.Hostname(or"") and"hostname_resolved_at": <hostnames.FormatTimestamp(entry.ResolvedAt), or null>when the entry has aResolvedAt; resolver degradations are already logged inside the resolver and never fail the sessions response. Handler test: a cache/settings failure still returns HTTP 200 withhostname: ""andhostname_resolved_at: nullper session, and a durable entry emits the exact 9-digit fixed-width string via the exported helper.apps/backend/internal/user/service/service.go: publish the complete persisted settings snapshot through the existingUserSettingsUpdatedevent. The service has no hostname-resolver dependency.apps/backend/internal/backendapp:- Construct the resolver in
startServicesright afterservices.Authis set (all ofdbPool,repos,eventBus,log,ctx,addCleanupare in scope): store overdbPoolwriter/reader,SessionIPs=services.Auth, settings gate = adapter overrepos.User.GetUserSettings(ctx, userID). - Call
resolver.Start(ctx)explicitly after construction; on error, log and abort startup. RegisteraddCleanup(resolver.Close)only after a successfulStart. - Queue-subscribe
resolver.HandleUserSettingsUpdatedtoevents.UserSettingsUpdated. The shared queue prevents duplicate DNS work across backend replicas. Register the subscription cleanup after the resolver cleanup so shutdown unsubscribes before it closes the resolver. - Keep the event handler small and idempotent. It reads the persisted user
ID and enabled flag, then calls
TriggerUserSessionsResolved. - Thread the resolver to the routes: attach it to
Services(SessionHostnameResolver *hostnames.Resolver; theServicesstruct is declared inapps/backend/internal/backendapp/types.go, notservices.go), which is already passed throughstartAgentInfrastructure→startGatewayAndServe→buildHTTPServer→registerRoutes;routeParamsreads it fromp.services.SessionHostnameResolver(or add an explicit parameter to every signature in that chain — pick one, do not leave the plumbing implicit). Extend theauthhttpapi.RegisterRoutescall inregisterRoutesand update all call sites/tests.
- Construct the resolver in
Files likely touched
apps/backend/internal/auth/hostnames/store.goapps/backend/internal/auth/hostnames/timestamp.go(exportedFormatTimestamp/ParseTimestamp+timestampLayout)apps/backend/internal/auth/hostnames/store_test.goapps/backend/internal/auth/hostnames/normalize.goapps/backend/internal/auth/hostnames/normalize_test.goapps/backend/internal/auth/hostnames/resolver.goapps/backend/internal/auth/hostnames/resolver_test.goapps/backend/internal/auth/hostnames/goleak_test.goapps/backend/internal/auth/service.goapps/backend/internal/auth/service_test.goapps/backend/internal/auth/httpapi/handlers.goapps/backend/internal/auth/httpapi/handlers_test.goapps/backend/internal/gateway/websocket/user_notifications.goapps/backend/internal/gateway/websocket/user_notifications_test.goapps/backend/internal/events/types.goapps/backend/pkg/websocket/actions.goapps/backend/internal/user/service/service.goapps/backend/internal/user/service/service_test.goapps/backend/internal/backendapp/main.go(orauth.go)apps/backend/internal/backendapp/types.go(Services struct field)apps/backend/internal/backendapp/services.go(provider wiring)apps/backend/internal/backendapp/helpers.goapps/backend/internal/backendapp/<provider or wiring test file>(Start/cleanup/routing smoke test)
Acceptance
HostnamesForSessionIPsreturns cached values immediately (oneGetManycall) and schedules lookups only when the setting is confirmed on; with the setting off or unreadable it returns an empty map, schedules nothing, and no cached hostname reaches the sessions response.- A changed resolution persists to
auth_hostname_cacheand publishes exactly one event per interested (user, raw-spelling) pair — including two sessions of one user with different spellings of the same IP; unchanged hostname resolutions publish nothing. The internal event-bus map is{user_id, ip, hostname, resolved_at}(theUserEventBroadcasterroutes byuser_idand strips it); the WS payload delivered to the client is{ip, hostname, resolved_at}. Gateway/wiring tests must assert the exact internal map (withuser_id) is what the broadcaster receives. Every successful lookup (including same-value andIsNotFound) refreshesresolved_atviaSet, sorecentResolveWindowengages for stable and no-answer rows. - DNS result classification:
IsNotFound(NXDOMAIN/no PTR) persists as a cached no-answer (""withresolved_at) and is skipped byrecentResolveWindow; timeout/temporary/server errors are never persisted and are published""only for IPs with no cache entry — a stale cache plus transient error publishes nothing, so the durable value survives re-enable and list refreshes. TriggerUserSessionsResolved(userID)returns immediately (PATCH latency unaffected by settings/session/cache reads), runs on the resolver-owned context, andClose()joins the trigger goroutine and workers (goleak).- Admission never drops an IP:
Ndistinct IPs withN > lookupWorkersall resolve; rapid re-triggers dedupe via in-flight +recentResolveWindow(driven byCacheEntry.ResolvedAt); equivalent IP spellings share one cache row and one job; absent and cached-empty IPs are treated distinctly (absent schedules, fresh cached-empty does not). - Request-context cancellation does not cancel lookups;
Close()joins workers with no goroutine leaks (goleak). - Invalid IPs are skipped; cache read/write errors and a nil event bus
follow the spec Failure modes (degrade, never fail the sessions API or
panic). A
Seterror publishes nothing (changed-only semantics; the next trigger retries the persist, and a later successfulSetthat changes the cache publishes).CacheEntry.ResolvedAtis*time.Time: nil = unknown (handler emits JSONnull), non-nil covers both cached-no-answer (Hostname == "") and durable values.resolved_at: nullin events is reserved for transient DNS errors over an absent cache (empty strings), never for failed writes. - The resolver is started in production wiring:
Start(ctx)is called after construction (abort on error),Closeis registered as cleanup, and the resolver reachesregisterRoutes/RegisterRoutesthrough the startup chain; a backendapp wiring smoke test asserts Start/cleanup/ route-threading (unit tests that callStartthemselves are not sufficient evidence). GET /api/v1/auth/sessionsincludeshostnameandhostname_resolved_at(fixed 9-digit RFC3339 UTC ornull) for every session, and both are empty/null while the toggle is off; non-canonical stored spellings still resolve (canonical lookup key, raw display key), including when the toggle hook fires before any sessions GET.- PATCH
resolve_session_hostnames: truetriggersTriggerUserSessionsResolvedfor the user; the PATCH response is unaffected by lookup results. - The WS gateway routes
auth.session.hostname.resolved({ip, hostname, resolved_at}) to the user inuser_id, stripped from the payload, for both memory and NATS-shaped deliveries (gateway tests added). - The
auth_hostname_cacheschema is replay-safe: fresh DB and same-DB re-run ofinitSchemaboth succeed, including Postgres-gated fresh + replay coverage (the store is wired over the productiondbPool);resolved_atfixed 9-digit RFC3339 UTC text round trips through both dialects.
Verification
(cd apps/backend && go test -race ./internal/auth/... ./internal/user/... ./internal/gateway/websocket/... ./internal/backendapp/... ./pkg/websocket/...)
make -C apps/backend lint
git diff --check
Dependencies
Task 01 (the resolver reads resolve_session_hostnames).
Risks
- Publishing an event per interested user for a shared IP is required;
publishing only to the triggering user drops updates for concurrent users,
and the event
ipmust be each (user, raw-spelling) pair or the frontend row match breaks. Amap[userID]rawIPinterested set silently drops a user's second spelling of the same IP — use a per-user set of raw spellings. - A resolver that drops jobs when busy strands IPs with no later trigger:
use a pending set drained by workers, never a drop-on-full queue — and
workers must re-drain
pendingafter every completion (the wakeup channel only wakes idle workers), or excess IPs strand while all workers are busy. - Storing
resolved_atin a dialect-typed column and scanning it directly intotime.Timeis not portable across the SQLite/Postgresdb.Pool; store fixed 9-digit RFC3339 UTC text (one shared formatter) and parse explicitly, with required Postgres fresh+replay coverage. - Lookups on a request context die with the HTTP response: all DNS work runs
on the resolver-owned context canceled by
Close. - Uncached
hostnamevalues can leak while the toggle is off: gate the returned map, not just scheduling. - Publishing transient
""over an existing cache entry masks the durable value in the client (the streamed map is authoritative there); transient errors publish""only for IPs with no cache entry. - An explicit
Start(ctx)is easy to omit in production wiring; unit tests that call Start themselves will pass while the real server never drains pending lookups. Pin the production Start + cleanup registration in the wiring change. - A per-IP cache read per session row turns the sessions list into an N+1
path: use
GetMany. - A cache interface that cannot distinguish absent from cached-empty, or
lacks
ResolvedAt, makesrecentResolveWindowand no-answer caching unimplementable: reads must returnCacheEntry{Hostname, ResolvedAt}and absent rows must be absent from the result map. - Canonicalizing in
SessionIPs(the toggle-hook provider) loses the raw stored spelling, so a hook-triggered completion publishes a canonicalipthe frontend cannot match: the provider returns raw validated spellings; canonicalization stays inside the resolver. - Resolver tests cannot inject cache failures against a concrete store: the
resolver must depend on the narrow
Cacheinterface. - A struct-typed event without a literal
user_idkey is unroutable through NATS: publish amap[string]interface{}with literal keys and pin memory + NATS-shaped gateway tests. goleakwill fail ifStart/Closeare not idempotent and joined; follow the healthpoll Start/Stop shape.- A new table that only works on a fresh DB fails the repo's replay rule:
cover fresh + same-DB
initSchemareplay in the store tests.