Repository navigation
fix(risk): record a clicked host's verdict for every link on the host - #478
Open
polylane[bot] wants to merge 1 commit into
Open
polylane[bot] wants to merge 1 commit into
polylane[bot] wants to merge 1 commit into
Conversation
Co-authored-by: polylane[bot] <277585245+polylane[bot]@users.noreply.github.com>
|
Important Review skippedBot user detected. To trigger a single review, invoke the
|
|
React Doctor found no new issues. 🎉 Reviewed by React Doctor for commit |
leanest: 6 of 79 playwright test files selectedThe judge wasn't sure enough to skip 5 and it thinks 1 is affected.
73 skipped
|
baronunread
added a commit
that referenced
this pull request
Nov 12, 2026
…#506) ## What was wrong **#489, three D1 costs that grow with traffic or history** 1. `revalidateOnRedirect` ran an `UPDATE links ... WHERE risk_checked_at < ?` on every click of an org link. The condition made it a no-op for a link scored in the last day, but it was still one D1 statement per click, on a path whose comment says it should cost one KV read. 2. `sweepDedupeIds` selects `dedupe_id IS NOT NULL AND ts < ?`. The planner picked `idx_clicks_ts`, which walks every click older than the cutoff (up to 400 days) on every loop, including the last empty one. 3. `withSession` queued `markSeen` on every signed-in request, and API-key requests wrote `api_keys.last_used_at` on every call. Both were mostly no-ops. **#491.** `zod` was overridden to 4.6.5, which `bun audit` flags (GHSA-mrhx-c7xc-m3w5, high, memory exhaustion on oversized collections). Fixed in 4.6.6. ## Why this fix - **Risk update (1):** a per-isolate memo (`recentlyStamped` in `risk.ts`) of link + destination → "skip until". A click that finds it skips the statement. It adds no D1 read (that would replace the write it saves) and no KV write (the issue's other option, carrying the check time in the link's KV value, costs a KV write per link per day). A write that changed the row is skipped for the whole 24 h verdict TTL; a write that changed nothing (scored at a time we did not read) is skipped for an hour. A cache miss always writes. The destination is in the key, so an edit does not inherit the skip. The cost is that each isolate writes a given link at most once per window instead of never skipping; a cold isolate still sends one statement. The memo is bounded (10 000 entries, oldest dropped). - **Dedupe sweep (2):** partial index `idx_clicks_live_dedupe_ts ON clicks(ts) WHERE dedupe_id IS NOT NULL` (migration 0058). I chose it over a cursor because a cursor is state to lose and the index is the same fix in one line. Only about a day of clicks ever has a dedupe id, so the index stays small. Cost: one extra index entry per click insert (and its removal at sweep). That is one more D1 row written per click, against a scan that read all of history on each loop; at any real volume the scan is the bigger cost (reads of 400 days of clicks times the number of loops, daily). - **Last-seen and key writes (3):** the marks are read with the caller (`user.lastSeenAt` is now a better-auth user field, so `getSession` returns it; the API key and OAuth lookups already select the row). `markSeen` returns nothing if the mark is under an hour old. The key's `last_used_at` is rewritten at most every 5 minutes; the keys page shows a relative date, so it can lag by that much. The SQL conditions stay, so two concurrent requests with a stale mark still produce one change. - **zod (#491):** override bumped, `bun install`, `bun audit` no longer lists zod (the remaining undici and other advisories are unrelated and untouched). Built Worker: one `function $constructor` and one `var $ZodType` definition (both in `assets/schemas-*.js`), so there is still a single copy. - `bun run db:migrate:local` added (ship-issue and this change both tell you to run it; no script existed). ## Query plan, before and after (local D1, `explain query plan`) ``` BEFORE SEARCH clicks USING INDEX idx_clicks_ts (ts<?) AFTER SEARCH clicks USING INDEX idx_clicks_live_dedupe_ts (ts<?) ``` Same statement as `DEDUPE_SWEEP_SQL` in `clicks.ts`. Local D1 returns no `rows_read` meta, so I did not measure row counts; a worker test asserts the plan uses the new index. ## Interaction with #478 #478 rewrites the same block in `revalidateOnRedirect`: on every click it selects the org's stale links on the clicked host and updates them all. That is a better fix for the "other links on the host stay unscored" problem, but it also makes the per-click statement a `SELECT ... LIKE` instead of a no-op `UPDATE`, so it needs the same skip. Whichever lands second should key the memo by `orgId` + hostname instead of link + destination, and skip the select and update on a memo hit (the memo helpers are separate from the SQL, so this is a small change). #478 also deletes the "second click on another link" half of an existing test, which this PR leaves alone, so expect a trivial conflict in `tests/worker/link-risk.worker.ts`. Not done here to avoid pre-empting #478's design. ## Left out - Nothing carried in the KV link value (see above). - better-auth (1.7.14 → 1.7.21) and hono bumps mentioned in #491: separate change, different review. - No UI changes. Nothing to screenshot; the keys page reads the same field. ## Tests - `tests/worker/request-writes.worker.ts` (new): last-seen and key writes with `recordingEnv()` (new helper in `support.ts`) that records the SQL the Worker prepares. - `link-risk.worker.ts`: a repeat click sends no SQL; an edited destination is still stamped. - `clicks.worker.ts`: the sweep's plan uses the new index. - Mutation-tested: dropped the memo check, the `markSeen` check, the key check, the destination from the memo key, and the migration. Each broke exactly its own tests. - One thing the throttle surfaced: `lastSeenAt` as a user field changed the shape of the sign-up reply, which the account-enumeration test (#53) caught. `pendingSignUpResponse` now carries `lastSeenAt: null`. - `bun run verify` on a loaded machine (two runs competing) timed out in unrelated worker tests and failed the enumeration test, which was a real regression and is fixed above. Final head: `bun run test:worker` passed 1008 of 1009 run tests; the one failure, `mcp-oauth` "a granted access token authenticates a real tool call", was a 5 s timeout under load and passes alone (11/11). `format:check`, `lint`, `check`, `test`, `test:worker:self-host` and `bun run fallow` pass. Closes #489 Closes #491 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When somebody clicked a link to a host whose risk verdict was stale, only that one link was marked. Every other link on the same host stayed unmarked, so the admin risk view showed them as unremarkable. This change records the verdict for all of the organization's links on that host after one click. The function's own documentation and its test both say the verdict belongs to every link on the host, but the code saved it to the clicked link alone. The test now clicks one of two links on a host and checks that both carry the verdict, which fails against the old code.
Fix walkthrough
Watch the fix explained (57 s). Recorded for commit
80c1315e9c06e3382370cfd22a7f71841a52eeac.Detection evidence
Affected:
int_1a7ddf18a0010py9bcmkrimsProduction impact
Risk verdict write stays inside the clicked organization's links
I checked the repository node baronunread/rdyrct: it has no outgoing edges and the workspace has no connected cloud accounts, so the change reaches no deployed resource. The changed statement binds
org_id = ?to the clicking link's organization and writes only the fourrisk_*columns, which admin routes read.Observability
risk_revalidate_failedis logged when the revalidation throws (existing, unchanged).linksrow on the host carriesrisk_scoreandrisk_checked_at.Polylane assessed this pull request at
80c1315.Causal chain
where id = ?and binds hit.linkId, so the cached or freshly computed host verdict is written to the clicked link alone; sibling links on the same host keep a null risk_score until each is clicked.update links ... where id = ? and destination = ?binds hit.linkId, so only the clicked row is written.risk:host:${hostname}holds the verdict, but nothing applies it to the sibling links.2 files changed (+21/-15)
src/worker/risk.ts: modified, +19/-11tests/worker/link-risk.worker.ts: modified, +2/-4Generated by Polylane. You can ask follow-ups by mentioning @polylane in a comment. If you close this pull request without merging, add a comment that says why. Polylane reads it to make its next fixes better.