Commit Graph
183 Commits
Author SHA1 Message Date
Claude d9dee8967b fix: resolve compiler warnings across modules
Clears real Kotlin compiler warnings surfaced across quartz, cli,
relayBench, amethyst, and desktopApp:

- quartz Sha256/EventHasher/ScratchLocal: ThreadLocal.get() is nullable
  in Kotlin; assert non-null (withInitial never yields null).
- quartz GitHttpClient: PriorityQueue.poll() under isNotEmpty() is
  non-null; assert it.
- relayBench CorpusDownloader: drop redundant !! on smart-cast Long;
  Jackson fields() -> properties().
- cli GrapeRankCommand: drop redundant ?. where latest is smart-cast.
- PodcastRemoteContent: OkHttp body is non-null; drop dead elvis.
- Dead/redundant expressions: remove no-op when-branch values and a
  redundant trailing Unit (HomeScreen, LocalCache, EmbeddedTabLayer,
  ParticipantHostActionsSheet, NestActionBar, ControlWhenPlayerIsActive,
  ShareNoteAsImageScreen exhaustive-when else).
- CalendarEventDetailScreen / SetPasswordDialog / ProfileClinkOfferResolver:
  drop always-true conditions (reorder to keep smart-casts).
- WalletColumnScreen: OkHttp body non-null; drop unreachable null-guards.
- PcmTapRegistry: the @OptIn used androidx.annotation.OptIn, which does
  not opt into Kotlin's ExperimentalCoroutinesApi; use kotlin.OptIn.
- GitRepositoryScreen: suppress the standard ViewModel-factory cast.
- PushNotificationReceiverService: suppress override-of-deprecated.
- Desktop GlobalScope call sites: @OptIn(DelicateCoroutinesApi::class).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GMqkg1ndvFihEwZcENiRs
2026-07-08 18:31:10 +00:00
Vitor PamplonaandGitHub 0ff48cfbe0 Merge pull request #3483 from nrobi144/feat/wot-shared-index-relays
feat(desktop): Web-of-Trust score badges + shared index relays + amy wot verbs
2026-07-08 12:53:08 -04:00
Vitor PamplonaandGitHub e3e9e2fa20 Merge pull request #3498 from vitorpamplona/claude/negentropy-sync-deletions-t2a7sf
NIP-77 deletion sync: two-pass settle over the reconcile residual
2026-07-08 12:05:07 -04:00
Claude 0145f8bdcb refactor: extract deletion-settle loop into a quartz INostrClient accessory
The two-pass deletion convergence is protocol logic, not CLI assembly, and the
geode mirror is a near-term second consumer — so move it out of SyncCommand into
a reusable accessory alongside the rest of the negentropy family.

quartz: negentropySettleDeletions(relay, filter, store, sendUp, applyDown, …) —
re-reconciles after a content settle and resolves only the residual: publishes
our covering deletions up (sendUp) and/or ingests the relay's kind-5 down
(applyDown, vanish never auto-applied), looping until a round resolves nothing.
Returns DeletionSettleResult(sentUp, appliedDown, rounds). Everything it needs is
already quartz (negentropyReconcileIds, fetchAll, deletionsCovering,
publishAndConfirm, Event.verify, IEventStore), so it carries no CLI dependency.

SyncCommand's pass 2 collapses to a single call; pass 1 (content) is unchanged.
Catalogued in the accessories README.

Tests: DeletionSyncTest drives the accessory end-to-end both ways (sendUp → relay
converges to gone; applyDown → local converges to gone), on top of the existing
deletionsCovering unit + manual-wiring cases.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 14:42:20 +00:00
Claude 677c0ee207 refactor: deletion sync as a post-settle residual pass (both directions, O(residual))
Replace the per-need-event fetch (which pulled the whole need set just to read
metadata — an O(db) regression on large syncs) with a second reconcile pass over
the residual, per the "settle, then diff, then explain what didn't converge" idea.

Pass 1 is the plain content sync again (drain needs, publish haves) — zero
deletion overhead. Pass 2+ re-reconciles; the leftover diff is exactly the
deletion mismatches, and only that (tiny) set is fetched:
- residual need (relay has it, we still lack it after --down) = we deleted it →
  publish our covering deletion up so the relay drops it;
- residual have (we have it, relay still lacks it after --up) = the relay deleted
  it → pull the relay's covering kind-5 down and apply locally (vanish is NOT
  auto-applied on pull — account-wide blast radius).
Loops until a round resolves nothing (converges + self-verifies).

So `amy sync` makes the relay honor our deletions; `--up` makes us honor the
relay's; `--up --down` converges both ways. Cost is one cheap reconcile + the
residual regardless of database size — the large-DB bottleneck is gone by
construction, not by heuristics.

quartz: deletionsCovering is now source-agnostic (takes a query lambda) so the
same coverage rule runs against the local store (up) or the relay (down); the
IEventStore overload is the local convenience.

Tests: DeletionSyncTest gains the down-direction end-to-end (relay deleted →
local removes) alongside the up-direction and the per-form unit cases.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 14:25:37 +00:00
Vitor PamplonaandClaude Opus 4.8 3cba102a09 perf(graperank): faster crawl (cap 100→16, dead-discovery shedding, fewer sweep barriers) + relay diagnostics
Speeds up a from-scratch GrapeRank crawl ~25-30% at equal completeness on a
drift-controlled A/B, by:
- lowering the per-relay concurrent-sub cap 100→16 — the old 100 drowned popular
  relays (damus/nos.lol) in concurrent giant REQs, driving them to time out; 16
  restores their responsiveness (damus yield 0%→14%) and is still generous for
  the single-user fetches other amy commands do,
- shedding proven-dead relays from the kind:10002 discovery sweep instead of
  re-hammering refusing indexers every round,
- trimming the sharded backbone sweep 6→2 rotations (Phase A was ~36% of the
  crawl at half Phase B's per-list efficiency; 2 clears the bulk with no
  completeness loss).

Also adds relay observability under --diagnose to document how relays reply to
our queries: per-relay telemetry (outcome mix, yield, latency, worst time-sinks),
a LIVE / THROTTLED / UNREACHABLE classification table with the limits we settled
on per relay, and per-round Phase-A/Phase-B timing; plus contact_lists_by_hop in
the sync result for per-hop completeness.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 10:02:24 -04:00
Claude 0af65b4296 refactor: use quartz INostrClient.fetchAll instead of a bespoke Context.fetchRaw
fetchAll already does exactly what the need-metadata fetch needs — subscribe,
collect (deduped by id), return on EOSE/timeout, no verify, no store — so drop
the duplicated Context.fetchRaw and call the existing extension.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 12:59:47 +00:00
Claude af7c6c11e1 feat: send exactly the deletions that cover a relay's need events (id/addr/vanish)
Refine the sync deletion rule to what was asked: for the events the relay HAS
that we LACK (the reconcile need set), publish only the local deletions that
would actually make the relay remove them — and nothing else, not other
deletions by the same author.

Determining coverage needs the need event's author/address/created_at, which we
don't have for an id we lack, so we fetch the need events (raw — no verify, no
store) purely for metadata. quartz gains IEventStore.deletionsCovering(events,
relay), which maps server-held events to the covering local deletions across all
three forms:
- NIP-09 id-based: a kind-5 with an `e` tag naming the event id;
- NIP-09 address-based: a kind-5 with an `a` tag naming the event's
  addressable/replaceable coordinate, at/after it (created_at <= deletion);
- NIP-62 vanish: a kind-62 by the event's author, targeting this relay, issued
  after it (created_at < vanish).

SyncCommand's need workers now fetch each need batch once (Context.fetchRaw),
publish its covering deletions (deduped across workers), and — when --down —
store the rest; anything we deleted is rejected by the store's own tombstone.
Nothing is pulled down or applied locally, so it cannot over-delete the store.

DeletionSyncTest covers each form (with cutoff and wrong-relay negatives) plus an
end-to-end reconcile → cover → publish that removes the note on the relay.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 02:45:47 +00:00
Claude e09a939b08 refactor: reduce deletion sync to "send deletions for need ids", nothing else
Per the actual requirement, deletion propagation is exactly: for the ids the
relay HAS that we LACK (the negentropy need set), if we hold a kind-5 deletion
targeting one of them, publish that deletion up — so a note we deleted is
deleted on the relay too instead of being re-downloaded. Only the need ids,
only kind-5, up only.

This removes all the machinery the earlier approach accreted and that the audit
flagged as over-broad / data-loss-prone:
- deleted NostrClientDeletionSyncExt (the bidirectional side-channel, author
  scoping, vanish gating, kind selection);
- reverted geode MirrorWorker to base (no deletion side-channel, live-sub
  changes, catch-up ordering, or convergence changes);
- dropped the 3-phase SyncCommand flow (deletions-first pull, author-scope
  derivation, reject-reaction backstop, --sync-vanish, deletions_* output).

The new path pulls nothing down and applies nothing locally, so it cannot
over-delete the store, and it needs no author scoping — the need set already
bounds it. Kind-62 is intentionally excluded: a vanish is not "of an id".

Emits deletions_sent. DeletionSyncTest now exercises the exact wiring
(reconcile → look up local kind-5 by its e tag for the need ids → publish),
including the negative case (a need id we never had sends nothing).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 02:29:52 +00:00
Claude 17687e43fc fix: bound deletion sync scope; stop mass over-deletion (audit fixes)
An audit (adversarial-verified) found the deletion side-channel over-deletes
and over-propagates. Root cause: deletionSideChannelFilter fell open to
authors=null for any non-author-scoped content sync, so `amy sync --kind 1`
reconciled the RELAY'S ENTIRE kind-5/62 history and applied it to the personal
FsEventStore — every kind-5 deleting its targets + installing an id-tombstone
for every target id, every ALL_RELAYS kind-62 wiping all of a pubkey's events
(all kinds), and pushing our whole local deletion history up. Data loss plus a
full-history reconcile on every scoped sync.

Fixes:
- Bound the side-channel to the authors we actually hold content for (filter
  authors ∪ local matched-set authors), never the relay's population. Skip when
  that scope is empty; Phase 3's reject-reaction covers the author-less case.
- Kind-5 (precise, owner-scoped) propagates by default; kind-62 vanish is opt-in
  via --sync-vanish (its blast radius always exceeds a content sync's scope).
- excludesDeletionKinds() now checks each deletion kind independently
  (`--kind 1,5` no longer silently drops kind-62); the side-channel reconciles
  only the missing kinds.
- amy Phase 1 is best-effort: a deletion-reconcile failure records deletions_error
  and falls through to content, never aborting the primary sync (matches geode).
- Mirror up-catch-up converges on whether a PUBLISHABLE event was pushed, not raw
  haveCount — a vanish targeting another relay no longer burns all 8 rounds every
  startup. Mirror keeps its (correct) global scope for relay-to-relay replication.

Helper API: negentropyPropagateDeletions gains scopeAuthors + deletionKinds;
deletionSideChannelFilter takes authors + deletionKinds and returns only the
missing kinds. Tests updated for the new semantics.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 02:14:08 +00:00
Claude f8b2f17979 feat: deletions-first ordering + reject-reaction backstop in sync
Reorder amy sync so both sides fully reflect each other, including deletions:

1. Deletion side-channel now runs FIRST, before content, in both directions.
   The content snapshot is taken AFTER it, closing a resurrection bug: a
   deletion pulled down mid-sync removes a local event, but the old top-of-run
   snapshot still listed it and would re-offer it up — resurrecting it on a
   relay that also lacked the deletion.
2. Content reconcile, over the post-deletion snapshot.
3. Reject-reaction backstop: when the relay blocks a content push (usually it
   holds a deletion we lack), pull that author's kind-5/62 and ingest locally
   so we stop re-offering the dead event. Verify-by-fetch — only a real
   deletion the store accepts has any effect; fires only on an actual reject.

The up-push of deletions is already verified per-event: ctx.publish awaits the
relay's OK, and ingesting the kind-5 runs the delete synchronously, so OK=true
confirms the remote applied it.

Mirror catch-up gets the same deletions-first ordering (down and up), so a
deletion lands, or the reject-trigger is armed, before its target — no
add-then-delete churn.

Tests: MirrorDeletionSyncTest gains scopedUpMirrorPushesDeletion (authoritative
push — local holds the deletion, remote drops the note).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 01:25:18 +00:00
Claude 683f993c7b feat: propagate deletions (NIP-09/62) across negentropy sync
NIP-77 reconciles by event id over the content filter, so a scoped sync
(`--kind 1`) never carries the kind-5/62 that deletes one of those notes:
the deletion stays stuck on whichever side issued it while the target
lives on forever on the other. Add a deletion side-channel that reconciles
kinds 5 & 62 on their own, independent of the content filter.

quartz: NostrClientDeletionSyncExt — DELETION_PROPAGATION_KINDS,
Filter.excludesDeletionKinds()/deletionSideChannelFilter() (kinds 5/62 scoped
to the same authors, no time window since a deletion's created_at is not its
target's), shouldPropagateDeletionUp() (kind-5 always; kind-62 only to a relay
it targets, honoring the vanish's declared relays), and
negentropyPropagateDeletions() — one bidirectional reconcile that streams
have→upload and need→download.

amy sync: run the side-channel bidirectionally regardless of --up/--down
whenever the filter excludes 5/62; emits deletions_{need,have,downloaded,
uploaded}; --no-sync-deletions opts out.

geode MirrorWorker: thread a per-upstream deletionScope through both catch-up
phases and both live subs (down + up), in the mirror's configured direction;
relax down containment to accept in-scope deletions, gate kind-62 pushes by
target relay, and carry the deletion filter on re-subscribe so a reconnect
never drops it.

Tests: DeletionSyncTest (up/down propagation + filter/vanish-gate units) and
MirrorDeletionSyncTest (a kind-scoped down mirror still removes the note).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JgL1WTV4Hkp2uuXcUHCHGt
2026-07-08 00:00:24 +00:00
Claude 24c1ef3100 Merge remote-tracking branch 'origin/main' into claude/graperank-wot-cli-qreg2a
# Conflicts:
#	cli/src/main/kotlin/com/vitorpamplona/amethyst/cli/commands/StoreCommands.kt
2026-07-07 23:18:50 +00:00
Claude c6f90b20a0 feat(cli): split graperank into sync (load) and score (compute) sub-verbs
The crawl persists everything to the store and the score is a pure function
over it, so separate them: `amy graperank sync` crawls the reachable graph into
the store (idempotent + cumulative — run it a few times to be sure it's loaded)
and reports what it loaded without scoring; `amy graperank score` builds from the
store and scores instantly, repeatable with different params and no re-crawl
(same as bare `--offline`). Bare `amy graperank` stays the sync+score combo.

Extract the shared crawler wiring into newCrawler(); score() just forces the
offline path, and sync() runs a persist-only crawl (null builder).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 23:09:09 +00:00
Vitor PamplonaandGitHub 325eb3ccfe Merge pull request #3492 from vitorpamplona/claude/amethyst-status-command-yf5be6
Add `amy status` command for cross-account disk overview
2026-07-07 19:05:26 -04:00
Claude 439b85a8e1 feat(cli): let read-only verbs run without an account
amy gated every non-primitive verb behind a chosen account: `DataDir.resolve`
threw when `~/.amy/` had no unambiguous account, and every networked command
called `Context.open`, which requires an identity — even though queries only
read relays and the shared store and never sign. `store` maintenance and the
local `offer`/`debit info` decoders were caught by the same gate despite
touching no account state.

Reads now work anonymously; only signing needs an account:

- `DataDir.resolveOptional` hands back an accountless dir (`hasAccount = false`)
  pointing only at the shared event store when there is no unambiguous account,
  instead of throwing.
- `Context.openOrAnonymous` uses the resolved account when present, else an
  ephemeral key-less `Identity.anonymous()` — can read, can't sign. Marmot
  stores are now lazy and run-state isn't persisted for anonymous runs, so an
  accountless read leaves `~/.amy/shared/` clean.
- `Context.open` (signing path) re-asserts the requirement with the "which
  account?" hint, so ambiguous/no-account signing verbs still exit 2.
- Main resolves optionally for every verb except the identity-lifecycle ones
  (`init`/`create`/`login`/`logoff`/`whoami`), which still need a concrete
  account. `offer info` / `debit info` join the stateless primitive block.
- Read subverbs (fetch, subscribe, count, publish, outbox, search, sync,
  store, profile/git/podcast/podcast20 reads, nsite/napplet fetch·serve·list,
  blossom download·check) switch to `openOrAnonymous`.

No `--json` shapes change. Docs updated (help text, README, DEVELOPMENT).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRaoqGod5LUeSwq4GHRSNF
2026-07-07 22:58:22 +00:00
Claude 85d6f5a162 feat(cli): add amy status overview command
A cross-account, read-only snapshot of everything amy holds under
`~/.amy/`, built for the returning user: which accounts exist, which
one is pinned as current, each signer type (local keychain/ncryptsec/
plaintext, NIP-46 bunker, or read-only) and whether it can still sign,
the per-account local footprint (aliases, Marmot groups, published
KeyPackage bundle, Cashu wallet, sync cursors), and the shared event
store's size.

Like `use`, it dispatches before account resolution so it works with
zero, one, or many accounts. Strictly metadata-only: it never unlocks a
private key (no keychain prompt / NIP-49 passphrase) and never touches
the network.

Factors the on-disk event-store walk into a shared `StoreStats` helper
reused by both `status` and `store stat`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K3GJb11JkvopP61ETWAVyy
2026-07-07 22:32:06 +00:00
Claude a013bcd9d9 feat(cli): quiet quartz DEBUG logging by default, add --verbose/-v
The CLI ran at the library's default Log.minLevel = DEBUG, so quartz internal
chatter (relay-auth init, MLS restore, URL-rejection, throttle notices) leaked
onto stderr around every command's real output. Set Log.minLevel = WARN at
startup, before dispatch, so a normal run shows only warnings/errors plus the
command's own progress. A new global --verbose / -v flag restores full DEBUG;
it's parsed with the other global flags so subcommands never see it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 22:27:19 +00:00
Vitor PamplonaandGitHub 16357b0a9f Merge pull request #3491 from vitorpamplona/claude/account-logout-uc4ych
Add logoff command to CLI for account deletion
2026-07-07 18:14:14 -04:00
Claude c8c4111e0c feat(cli): add amy logoff to clear an account's local data
Adds `amy logoff [--yes] [--keep-events]`, the CLI counterpart to logging
out: it removes everything an account left on the machine.

  - the identity file and any backend-held secret (keychain / ncryptsec /
    plaintext), via DataDir.deleteIdentity
  - the rest of the per-account directory ~/.amy/<account>/ (run-state
    cursors, aliases, cashu counters, all Marmot/MLS state)
  - the ~/.amy/current pin, when it points at this account
  - the account's events in the SHARED ~/.amy/shared/events-store/

The event store is shared across accounts, so logoff does not wipe it
wholesale — it deletes only the events that involve this account: those it
authored plus those addressed to it via a #p tag (gift wraps, nutzaps,
reactions, mentions). Other accounts' cached events are left untouched.
`--keep-events` skips the shared-cache purge entirely.

The public key is read straight from identity.json (never unlocking the
private key), so logoff needs no passphrase and pops no keychain prompt.
Destructive and irreversible, so it follows the `marmot reset` precedent:
`--yes` is required to execute; without it the command prints a dry run of
what would be deleted and exits 2.

Thin-assembly only — event deletion is quartz's FsEventStore.delete; this
just resolves the account, counts, and wires the filesystem teardown.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PH3rqz5KaA7CYFPAtxgoz1
2026-07-07 22:11:52 +00:00
Claude 01d61b0851 fix: resolve remaining Kotlin compiler warnings in commons and cli
- Suppress DEPRECATION on REASONABLE_SIGN_KINDS, which intentionally lists the
  deprecated TorrentCommentEvent kind.
- Replace deprecated readLine() with readlnOrNull() in SecureKeyStorage.
- Drop unnecessary !! non-null assertions in KeyCommands and NostrConnect where
  the receiver is already smart-cast to non-null.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018nqdy4VTLKidUWzGTJPja9
2026-07-07 21:39:04 +00:00
Claude 6b957e1950 perf(graperank): park slow relays in the background instead of blocking rounds
The crawl was round-synchronised: each hop drained all its relays and only
started the next hop after the slowest one reached EOSE or the timeout. That
made waiting for slow-but-alive relays expensive — every hop paid its slow
tail before the next hop's fast relays could begin — so a long timeout for
completeness cost ~2x wall-clock (measured), and a short one dropped the slow
relays' data.

Diagnostics on a ~190k-user crawl showed the genuinely-slow set is a stable
~30 relays that DO reach EOSE, just in 5-25s. So decouple the two concerns:

- drainGated now drains on the FAST `timeoutMs` that sets the round cadence. A
  relay still streaming when it elapses is not cut but PARKED: it hands its
  open subscription to a background scope (releasing its AdaptiveRelayLimiter
  permit so the round moves on), keeps receiving for up to the new
  `parkTimeoutMs`, and its late events are persisted + its late contact lists
  pushed to a crawl-wide lateHarvest channel.
- The round loop folds late harvest into the graph between rounds and won't
  converge until the frontier is empty AND no relay is still parked — so the
  crawl waits for slow relays for completeness without paying that wait in each
  round's wall-clock.

Graph state stays single-writer: parked coroutines only touch the store,
seenIds, and the channel — never hopOf/done/builder. Persistence moved from a
single per-drain consumer to a shared `persist()` that fast and parked units
both call; crawl-wide dedup is now race-safe via ConcurrentSet.add's atomic
test-and-set (an id is added only after a good signature, so no duplicate
reaches the store's UNIQUE constraint and a forged copy can't suppress the
genuine one).

Also carries the --diagnose slow-relay logging (relay + filter + elapsed for
every slow/parked REQ, so a human can replay it) and keeps --drain-concurrency
at the validated default of 24 (an A/B at 64 was ~2x slower with more dead
relays). New --park-timeout flag (default 40s; set <= --timeout to disable).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 20:13:21 +00:00
Claude c9ee79beba feat(graperank): log slow/timed-out relays with their query under --diagnose
Add a --diagnose slow-relay log: every content drain that reaches its terminal
(EOSE or timeout) slower than SLOW_DRAIN_LOG_MS, or times out entirely, is
recorded with the offending relay URL, the failure/EOSE reason, elapsed ms, and
the exact filter shape (kinds + author count + first authors). This lets a human
replay that precise REQ later to understand why the relay lags. Gated on
--diagnose so there is no per-group timing/collection overhead otherwise.

Make the content-drain fan-out configurable via a new --drain-concurrency flag
(Config.drainConcurrency), replacing the DRAIN_CONCURRENCY constant. Default
stays at the validated 24: an A/B at 64 ran ~2x slower with more dead relays
(a higher global fan-out re-floods busy hubs faster than the per-relay demotion
catches up), so the flag is a probe knob, not a speedup. Client WebSocket pings
were also tried and reverted — busy-but-alive relays don't reliably pong while
their query handler runs, so pinging just cut them as dead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 19:10:33 +00:00
Claude 9da382b698 refactor(quartz): extract GrapeRankPublisher from the CLI command
Mirror the crawler extraction on the emit side: the NIP-85 kind:30382 card
reconcile + publish logic (existingCards read-back, rank-diff upsert, stale-card
kind:5 retraction batched under the 64KB event cap) moves out of GrapeRankCommand
into a reusable GrapeRankPublisher in quartz experimental/graperank. It takes an
IEventStore for the prior-card read-back and an injected publish function
(event + relays -> per-relay ack), so the store/relay wiring stays in the app
while the reconcile logic is reusable (e.g. by the Android app).

GrapeRankCommand is now a thin orchestrator: crawl (GrapeRankDataCrawler) ->
score (GrapeRank) -> publish (GrapeRankPublisher). The account-specific bits stay
in the CLI: operator-key derivation, the observer's kind:10040 discovery pointer,
and the operator/register/providers sub-verbs.
2026-07-07 17:56:06 +00:00
Claude f7c3aef6fc perf(quartz): batch inserts + crawl-wide dedup in GrapeRankDataCrawler
The crawl re-verified and re-inserted the same event many times: the outbox
model mirrors each event (especially kind:10002 relay lists) across relays,
indexers, and rounds, but dedup lived in a per-drain SeenIds, so only the copies
within one drain were caught. Add a crawl-wide seen-set (thread-safe ConcurrentSet
of event ids, shared across all 24 concurrent drains and every round), checked
before verify and added only after verify so a forged copy can't suppress the
genuine one. Group-commit the store writes via IEventStore.batchInsert instead of
one transaction per event.

Measured on a from-scratch --max-hops 3 crawl: events actually verified+stored
dropped ~34% (112k -> 74k) and verify time fell in lockstep. The write path now
also reports verify/insert timing + events_stored in Stats, exposed as verify_ms/
insert_ms/events_stored on the CLI, and takes an --insert-batch knob.

Finding: with the work reduced, inserts serialize on SQLite's single writer
mutex rather than transaction count, and the crawl's wall-clock ceiling is the
drain-timeout retry tail on dead outboxes, not the disk.
2026-07-07 17:51:27 +00:00
Claude 41e88695e0 refactor(quartz): simplify GrapeRankDataCrawler after extraction review
Cleanups from a reuse/simplification/efficiency/altitude review of the crawler
extraction:

- Collapse the redundant `discovered` set into `hopOf` — a user is discovered
  iff it has a hop stamp, so the two always held the same key set. The frontier
  is now `hopOf.keys`; one fewer collection to keep in sync.
- Drop the unused `Stats.discovered` / `Stats.deadRelays` fields (no reader —
  the CLI reports rounds / relaysContacted / hopHistogram / downloadMs).
- Extract a single shared verify-then-store sink, `IEventStore.verifyAndInsert`,
  and route both the crawler and `Context.verifyAndStore` through it instead of
  each carrying its own verify + insert + UNIQUE-swallow copy.
- Fast-path the present-key hit in `ConcurrentMap.getOrPut` (jvmAndroid) so the
  crawl's hot relay-hint accumulation stops allocating a mapping-function closure
  on every call.
- Hoist the repeated `crawlStats?.hopHistogram` null-plumbing in GrapeRankCommand.
2026-07-07 16:00:39 +00:00
Claude 667358a06a refactor(quartz): extract GrapeRankDataCrawler to commonMain
The web-of-trust crawl (~400 lines: outbox routing, sharded backbone sweep,
Phase-B worker pool, relay-list discovery, report-deletion fetch, warm pool)
was making the CLI's GrapeRankCommand unmaintainably large. Move it into a
reusable, KMP-portable GrapeRankDataCrawler in quartz commonMain.

The crawler takes a NostrClient + IEventStore + AdaptiveRelayLimiter, injected
relay policy (discovery + content-fallback sets, since those defaults live in
app code, not the protocol library), and a log callback; it streams contact
lists into a TrustGraphBuilder and returns crawl Stats. GrapeRankCommand shrinks
to arg-parsing + offline load + scoring + publish + sub-verbs, delegating the
online path to the crawler.

To reach commonMain (portable to every target, incl. iOS):

- Add ConcurrentMap / ConcurrentSet expect classes under utils/concurrent, with
  jvmAndroid actuals (java.util.concurrent) and native actuals (copy-on-write
  over kotlin.concurrent.atomics.AtomicReference, mirroring ConcurrentHashCache).
  commonMain has no ConcurrentHashMap, and the crawl's producer/consumer/drain-
  worker state needs atomic getOrPut/merge plus a concurrent set.
- Move AdaptiveRelayLimiter and DrainFailure/classifyDrainFailure from cli to
  quartz commonMain (java atomics -> kotlin.concurrent.atomics, ConcurrentHashMap
  -> ConcurrentMap, System.currentTimeMillis -> TimeUtils.nowMillis, stderr -> Log).
- The gated drain (REQ-size splitting, per-relay permits, verify+store) moves into
  the crawler; Context.drain loses its now-unused gatePerRelay path.

Net: cli -1077 lines; the crawler + relay machinery are now reusable by the
Android app. Adds ConcurrentCollectionsTest; verified via JVM + commonMain
metadata compile, the wot/graperank suites, and a bounded live crawl.
2026-07-07 15:41:31 +00:00
Claude 6bbc1b7d22 fix(cli): cap kind:5 retractions at 400 a-tags to stay under 64KB events
Each addressable coordinate is ~130 bytes, so 500 pushed the deletion event to
~65KB — over the 64KB event-size cap many relays enforce (stricter than the
256KB message cap). Drop DELETE_PER_EVENT to 400 (~52KB).
2026-07-07 14:42:35 +00:00
Claude be6ff5456d docs(cli): document graperank operator keys + publish reconciliation
README + amy usage: add the `graperank operator [status|relay|providers]`
sub-verb, update the `graperank --publish` description to the per-observer
service-key model (sign with a derived key, publish to the operator relay,
reconcile new/changed/skip/retract, cutoff rank>=2, NIP-09-drop retracted
reports), and add a 'Publishing GrapeRank scores' section explaining the
operator master, deterministic per-observer key derivation, and the kind:10040
discovery wiring.
2026-07-07 14:39:32 +00:00
Claude 840f8f3153 feat(cli): publish 30382 cards under per-observer service keys, reconciled
Rewire `graperank --publish` onto the operator-key model:

- Sign each observer's kind:30382 cards with the dedicated service key derived
  for that observer (OperatorKeys), not the account key — a stable per-observer
  identity so re-signing replaces the addressable prior card.
- Publish to the operator's configured relay(s) (new `graperank operator relay
  <url>` sub-verb; --publish-relay still overrides). Errors clearly if unset.
- Three-way reconciliation against what the provider key already published:
  upsert cards whose rank tag string changed (or are new), skip unchanged, and
  RETRACT (kind:5, same service key, addressable `a`-tag, chunked under the
  message cap) any existing card whose target is no longer publishable — dropped
  from the graph, or below the cutoff.
- Raise the default publish cutoff to rank >= 2 (drops the barely-trusted tail);
  the retract rule removes any now-sub-cutoff cards.
- When we hold the observer's key (observer == active account), publish/refresh
  their kind:10040 pointing 30382:rank -> providerPubkey at the operator relay,
  to their outbox — the pointer clients follow to find the cards.

Adds `operator [status|relay|providers]` for managing the machine's operator.
2026-07-07 14:23:26 +00:00
Claude 0deae996bb feat(cli): operator-key module for GrapeRank provider signing
A machine holds one operator master seed, independent of any amy account, stored
under ~/.amy/operator/ via the same SecretStore backend the accounts use. From it
OperatorKeys deterministically derives one service key per observer —
serviceKey(observer) = sha256(masterPriv || "graperank-provider:" || observerHex)
— which will sign that observer's kind:30382 rank cards and their retractions.

Deterministic derivation gives a stable per-observer identity (so re-signing a
card replaces the addressable prior one instead of orphaning it) and one-secret
backup (every service key re-derives from the master alone). The manifest
(operator.json) records the master pubkey, operator relay(s), and observer ->
provider-pubkey mapping — public data; only the master rides the SecretStore.
Exposed via DataDir.operatorKeys(). Wiring into publish comes next.
2026-07-07 14:18:32 +00:00
Claude c637d1984d fix(cli): cap REQ frame size so relays don't reject oversized subscriptions
A REQ carries all of a subscription's filters in one frame, so a popular relay
routed thousands of authors produced a multi-MB frame that most relays reject
outright ("message too large (2MB > 256KB)"), silently dropping every author
in it. The gated drain now splits each relay's filters into REQ-sized groups by
total entry count (authors + ids + tag values), MAX_REQ_ENTRIES=2500 (~167KB,
under the common 256KB cap), and opens one gated subscription per group. A relay
with more authors simply gets several smaller REQs instead of one rejected huge
one. Each group carries its own subId/listener/terminal signal; per-relay
failure classification takes HARD over TRANSIENT across a relay's groups.
2026-07-07 14:11:14 +00:00
Claude 8d4dfedd68 perf(cli): skip duplicate events before verify in the gated drain
The outbox model — and especially the wide relay-list broadcast — delivers the
same event from many relays at once, and the gated drain ran a Schnorr verify
(and a store insert) on every copy before the store's UNIQUE constraint dropped
it. On a fan-out that asks hundreds of relays for the same kind:10002s, that is
hundreds of redundant verifications per event and pegged a core.

Add a per-drain SeenIds skip-before-verify to the consumer, mirroring
drainAllPages: an id is marked seen only after it verifies, so a forged copy
(valid id, bad signature) delivered first can't suppress the genuine one. Cuts
the redundant verification across the whole crawl, not just the wide sweep.
2026-07-07 13:44:23 +00:00
Claude 98709ef933 refactor(cli): use quartz DeletionIndex for retracted-report detection
Replace the hand-rolled report-id/author matching with quartz's DeletionIndex —
the same NIP-09 indexer the Android app's LocalCache uses. It keys each deletion
under the deleter's pubkey, so hasBeenDeleted(report) is authoritative only when
the report's own author deleted it, and it also handles created_at ordering (and
addressable events, for free). Deletions come from the store, which already
verified them, so they're added as pre-verified.
2026-07-07 13:31:04 +00:00
Claude 8ee8ebdb00 feat(cli): drop retracted reports via NIP-09 deletions in the graph
A report the author has since deleted should not count as a negative trust
edge. After the crawl, ask each reporter's outbox for kind:5 deletion requests
that cite the reports we gathered — #e-filtered to those report ids, so we pull
only the deletions that affect our reports, not every deletion the user ever
made. When building the graph, a report is dropped iff a kind:5 in the store
cites its id AND is signed by the report's own author (NIP-09: a deletion is
authoritative only from the event's author). Reports the reporter never
retracted are unaffected. The run reports reports_deleted.
2026-07-07 13:26:53 +00:00
Claude dd6384b19e feat(cli): only publish a 30382 card when its rank tag string changed
Gate publishing on the exact rank TAG VALUE STRING, not a re-parsed Int. A
card carries only a `rank` tag (plus the d-tag target), and RankTag.assemble
writes `rank.toString()`, so we diff that string against the one on the newest
kind:30382 card the signing key already published (read back from the store).
An unchanged score is skipped — no new signature, no new event id — so a client
that syncs the provider's cards by id only ever downloads the ranks that
actually moved. Replaces the prior Int comparison with a faithful
what-would-be-written string diff.
2026-07-07 13:18:47 +00:00
Claude dad703baed perf(cli): fresher relay lists, wider discovery, and busy-vs-dead pruning
Three crawl fixes:

1. Fetch kind:10002 alongside content. The content query asked only for
   3/10000/1984, so a user's freshest relay list — which lives on their own
   outbox — was never pulled from there; we trusted a possibly-stale indexer
   copy. Fold 10002 into the same fetch. The store keeps newest-by-created_at,
   so pulling it from popular relays too can't stale it.

2. Widen ensureRelayLists Tier 2. It only asked the top-30 backbone for a
   still-missing 10002. A stray relay list can sit on any one relay, so Tier 2
   now asks EVERY relay we've seen work — fired fire-and-forget on a background
   scope so the large fan-out never blocks the round; results enrich routing
   for later rounds.

3. Classify dead relays instead of striking everything the same. A connect
   TIMEOUT is a busy relay — retried, never marked dead. A HARD failure (bad
   domain, TLS misconfig, dead HTTP code — see DrainFailure/classifyDrainFailure,
   keyed on the exception type now in the failure message) is dropped on the
   first strike. Transient failures (refused/reset/unreachable, 429/5xx) keep
   the multi-strike leniency. Connect timeout raised 5s -> 7s so slow-but-alive
   relays finish the handshake.
2026-07-07 13:11:12 +00:00
Claude 59d5fc752c perf(cli): split rate-limit from subscription-count limit in the crawl
A relay pushes back for two different reasons that need two different fixes,
and treating them the same mishandles the relay:
  - a subscription-COUNT cap ("too many subscriptions", "maximum concurrent
    subscription count") is fixed by fewer CONCURRENT subs — demote the
    per-relay concurrency cap (100 -> 20 -> 10), as before;
  - a RATE limit ("rate-limited: too many messages", "burst exhausted") is
    too many subscription CHANGES per second — fewer concurrent subs don't
    help; the fix is to SPACE the REQs out in time.

AdaptiveRelayLimiter now routes each complaint to its own actuator by matching
the notice text, and adds a per-relay rate gate: a growing minimum interval
between subscription opens (250ms -> 500ms -> 1s -> 2s), enforced in withPermit
before the concurrency permit. A relay can be under both controls at once. The
snapshot reports each dimension separately.
2026-07-07 13:10:58 +00:00
Claude 9611be4135 perf(cli): stream the crawl through a worker pool, no batch barriers
Phase B drained DRAIN_CONCURRENCY batches, waited for the SLOWEST (a dead
relay's full timeout), ingested, then started the next group — so every
batch's long tail idled the whole pool, and connections were torn down and
rebuilt between groups. Replace the chunked awaitAll barriers with a
continuous producer -> workers -> consumer pipeline:

- Producer (1 coroutine) routes each author-batch by outbox and feeds a
  bounded queue (keeps writeRelayFreq single-writer, backpressured so we
  don't precompute every filter map at once).
- DRAIN_CONCURRENCY workers pull a batch, drain it, and grab the next the
  instant the drain returns — no worker waits on a slow sibling, and hot
  relays stay connected because some worker is always subscribed to them.
- Consumer (1 coroutine) ingests serially (discovered/done/builder/hopOf
  stay single-writer), now overlapped with draining instead of blocked
  behind each batch.

The four structures now crossed between producer/worker/consumer
(relayHints, attempts, deadRelays, relayStrikes) become concurrent; all
graph mutation stays single-writer on the consumer. Removes the dead-relay
timeout stalls that were serializing the crawl and cuts reconnect churn.
2026-07-07 12:25:48 +00:00
Claude df0cf49876 perf(cli): widen OkHttp dispatcher + tighten connect timeout for the crawl
The crawl's client ran on OkHttp defaults: Dispatcher.maxRequests=64 and a
10s connectTimeout. Every relay WS-upgrade handshake is an async call through
that shared dispatcher, so 64 caps the connection-ramp width — and a dead
relay squats on a slot for the full connectTimeout, starving live relays
queued behind it (observed: only ~150 sockets open at once during an active
wave touching hundreds of relays). Raise maxRequests to 256 /
maxRequestsPerHost to 16 and drop connectTimeout to 5s so unreachable relays
release their slot fast.

This is orthogonal to REQ concurrency (bounded per-relay by
AdaptiveRelayLimiter on already-open sockets), so it can't trip a relay's
REQ rate-limit — it only speeds connection setup. The dispatcher's executor
pool grows threads on demand, and FD headroom is ample (4096 limit vs ~150
in use), so the wider cap just lets more short-lived handshakes run at once.
2026-07-07 12:13:14 +00:00
Claude 0c0a8caaff perf(cli): dial crawl fan-out back to 24 under the adaptive cap
Measured 48 against the per-relay adaptive limiter (hop-4 A/B): it demoted
the right hubs and cut rate-limited CLOSEDs further (1433 -> 501), but the
higher fan-out re-floods busy relays faster than demotion catches up — a
new dominant complaint ("max concurrent subscription count reached")
appeared and download_ms regressed ~11% vs the 24 baseline. Keep the
adaptive per-relay cap (it targets the misbehaving relays precisely) but
return the global fan-out to 24, where the 20/10 ladder still bites below
the global bound and wall-time stays at its best-observed value.
2026-07-07 12:05:46 +00:00
Claude 143a63c520 refactor(quartz): move GrapeRank web-of-trust algorithm into quartz
The GrapeRank engine, TrustGraph (compact int-CSR) and TrustGraphBuilder
are pure Nostr-social-graph computation over HexKeys — no UI, no Compose,
and no commons-only dependency. They're a utility for implementing the
NIP-85 rank assertions quartz already models, so they belong in quartz
rather than commons. Move commons/wot -> quartz experimental/graperank
(package com.vitorpamplona.quartz.experimental.graperank), including both
commonTest suites, and repoint the CLI import. TrustGraphBuilder was already
protocol-agnostic (takes HexKey lists; the caller does the event->edge
extraction), so nothing had to change but the package. Makes the algorithm
reusable by the Android app for spam/trust filtering without pulling in
commons.
2026-07-07 12:03:59 +00:00
Claude de8648f3f1 perf(cli): adaptive per-relay subscription cap for the crawl
Replace the blunt global concurrency number with per-relay back-pressure.
Every relay starts generous (100 concurrent subscriptions) and is demoted
down a ladder (100 -> 20 -> 10) only when it complains about concurrency —
a CLOSED rate-limited, or a NOTICE like "too many concurrent REQs" /
"too many subscriptions" / "burst exhausted". Well-behaved relays keep
the full cap; only the busy hubs that push back get throttled, and only as
far as they keep pushing.

AdaptiveRelayLimiter registers as a RelayConnectionListener so demotions
are driven straight off the same NOTICE/CLOSED frames RelayDiagnostics
already observes, keyed by relay.url. Context.drain gains a gatePerRelay
path that opens one subscription per relay, each held behind that relay's
gate, so our concurrent subs on it never exceed its current cap. The gate
is a fair FIFO bounded semaphore whose limit can only be lowered; shrinking
below the in-use count admits no new subs until enough finish, so
concurrency converges down to the new cap.

Because a hot relay can no longer be flooded, the global content-drain
fan-out is raised (18 -> 48) to crawl the many well-behaved relays faster.
The crawl emits a relay_throttling summary (which relays were capped, and
to what) alongside relay_feedback.
2026-07-07 11:44:54 +00:00
Claude fb0011129d perf(cli): cap crawl at ~20 subscriptions per relay
Each concurrent content drain opens exactly one subscription per relay it
touches, so DRAIN_CONCURRENCY is effectively the per-relay concurrent-sub
cap. RelayDiagnostics showed the previous value (24) blew past typical
relay limits — rate-limited=1433, "too many concurrent REQs"=1286,
"too many subscriptions"=710 — causing dropped fetches and retry churn.
Lower it to 18 so the peak (18 drain subs + 1 persistent warm-pool sub)
stays ~19, just under the common ~20 cap.
2026-07-07 11:11:32 +00:00
nrobi144 bb2a83c1fe feat(desktop,cli): route WoT kind-3 fetch through OutboxDispatcher (NIP-65)
Phase 3 of the outbox refactor (PR #3483, per Vitor's directive). The
WoT service's kind-3 seeding on Desktop and the `amy wot sync` verb now
go through OutboxDispatcher — index relays discover each author's
kind-10002 write relays, then per-outbox-relay REQs fetch kind-3.

Changes:

  Desktop:
    - DesktopRelaySubscriptionsCoordinator gains an inner
      OutboxCacheGateway that bridges DesktopLocalCache
      (cachedAdvertisedRelayList / consume) to OutboxDispatcher.
    - New suspend loadKind3ViaOutbox(pubkeys) method returns the
      dispatcher's Result for observability.
    - Main.kt WoT-seed effect now:
        1. gates on wotService.isDisabled to preserve MAX_FOLLOWS
           guardrail (fix 2 from Phase 1)
        2. calls loadKind3ViaOutbox instead of the direct
           loadKind3Batched on index relays
        3. keeps the 2s markReady safety net for cold-start UX
    - clear() now also clears outboxDispatcher's dedup markers.

  amy:
    - WotCommand.sync rewritten to construct an OutboxDispatcher, buffer
      events in the gateway, and persist to ctx.store after fetch
      returns (store.insert is suspending; can't call from non-suspend
      gateway callbacks).
    - --json output additively gains kind10002_received,
      outbox_covered_authors, fallback_authors, persisted keys.
    - --timeout N still supported; now maps to overallTimeoutMs.

Not in this commit (deferred to a follow-up on same PR if reviewers
want it):
  - Routing stranger-avatar kind-0 fetch through the outbox path
    (MetadataPreloader wiring is more invasive; keeps this diff focused
    on the primary WoT concern).

Plan: commons/plans/2026-07-06-fix-wot-outbox-model-and-review-fixes-plan.md
2026-07-07 13:31:41 +03:00
Claude 6060c50f79 perf(cli): keep a warm connection pool to the top relays during the crawl
The client's relay pool reconciles open sockets to the relays that active
subscriptions currently need, so between-round gaps (routing + contactsOf scans
> ~300ms) and niche-relay churn dropped connections we reuse every round, then
reconnected them — a TCP+TLS+WS handshake each time.

Hold a persistent do-nothing subscription (WARM_SUB_ID) open to the busiest
WARM_POOL_SIZE(20) live relays, refreshed to the current top set at each round
start (same subId → just updates the desired-relay set) and closed when the
crawl finishes. Its filter matches an impossible event id, so the relay EOSEs
immediately and streams nothing — it only keeps the socket warm.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 04:53:38 +00:00
Claude 82f0c3cc6c feat(cli): NIP-42 auth + relay-feedback diagnostics in the crawl
Two blind spots in the crawl's relay I/O:

- No NIP-42 auth. Auth-gated relays sent AUTH, the client never answered, and
  their sub CLOSed 'auth-required' — so those outboxes served us nothing. Wire a
  RelayAuthenticator into Context that signs the AUTH challenge with the account
  key (local signer only; a remote bunker is skipped to avoid a per-relay
  round-trip storm mid-crawl). Signing with any key still unlocks relays that
  just want some auth.
- No visibility into REQ failures. Add RelayDiagnostics, a connection listener
  that tallies NOTICE frames, CLOSED reasons by NIP-01 prefix (auth-required /
  rate-limited / restricted / …), and AUTH challenges. Surfaced in the crawl's
  stderr summary and as relay_feedback in the JSON, so a failed fetch can be
  explained instead of guessed at.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 04:40:35 +00:00
Claude 3af168eff9 perf(cli): preserve crawl recall — wider broadcast pool, softer dead-strike
Review of the sharded-sweep restructure flagged two recall regressions vs the
removed last-mile:
- the sweep + broadcast only ever hit the top SHARD_RELAYS (10), while the old
  last-mile reached busy relays ranked 11-80 where a user's kind:3 is often
  mirrored. Broadcast the small remainder to BROADCAST_RELAYS (60) top live
  relays instead of just the rotation's 10, restoring that reach (indexers are
  intentionally excluded — they don't serve kind:3).
- MAX_DEAD_STRIKES was 2 with no recovery, so two transient connect blips
  evicted a relay for the whole run. Raise to 3 for a safety margin; drain still
  only counts hard connect failures, not slow relays.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 04:00:50 +00:00
Claude 6e51f9c262 perf(cli): faster graperank crawl — dead-relay pruning, higher concurrency, sharded backbone sweep
The download phase was ~90% idle, blocked on the per-wave drain timeout waiting
on dead/stalled outbox relays. Three changes:

1. Dead-relay pruning. Context.drain now reports relays that failed to CONNECT
   via a deadOut set; the crawl strikes them (MAX_DEAD_STRIKES=2) into a
   deadRelays set and excludes them from routeByOutbox and the sweep, so a wave
   stops re-paying the timeout on the same dead outboxes.
2. DRAIN_CONCURRENCY 8 -> 24, safe now that dead relays are pruned rather than
   piling up as stalled connections.
3. Sharded backbone sweep (Phase A each round): split the pending authors across
   the top-SHARD_RELAYS(10) live relays — one shard per relay, no relay gets the
   same list twice — drain all concurrently, rotate the still-missing onto
   different relays for up to SHARD_ROTATIONS(6) passes, then broadcast the
   remainder to all top relays only once it drops below SHARD_BROADCAST_THRESHOLD
   (2000). Phase B then outbox-routes only whoever the popular relays lacked. The
   old broadcast-everyone last-mile is removed (the sweep subsumes it).

Each concurrent drain uses its own dead-set (no shared-HashSet race); harvest
feeds from the drain's returned events instead of re-scanning contactsOf over
the whole missing set. Adds download_ms so the crawl phase is timed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 03:58:01 +00:00
Claude 35078c460d feat(cli): measure crawl/download time in graperank (download_ms)
The online crawl phase — the network-bound fetch of the whole graph off the
relays (rounds + last-mile sweep) — was untimed; only the offline store-load
had a phase timer. Add download_ms around the crawl block and fold it into the
"crawl complete" log and the JSON, so a from-scratch run reports every phase:
download -> graph build -> scoring (and, with --bench-sign, card signing).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWk2ZMrGBSr4WenKgwqmbB
2026-07-07 02:48:49 +00:00