Skip to content

perf/fix(backend): page the runway worker, drop dead code, log by status, declare axe-core - #1936

Open
anitahhhh wants to merge 8 commits into
LabsCrypt:mainfrom
anitahhhh:fix/runway-paging-logging-cleanup
Open

anitahhhh wants to merge 8 commits into
LabsCrypt:mainfrom
anitahhhh:fix/runway-paging-logging-cleanup

Conversation

@anitahhhh

Copy link
Copy Markdown

One unbounded query loop, three pieces of dead weight, a log line that cried wolf, and an undeclared test dependency.

Closes #1899
Closes #1900
Closes #1901
Closes #1902

#1899 — the runway worker stops being O(n)

The hourly check loaded every active stream in one unbounded findMany, then
called alertHistory.findFirst once or twice per stream, awaited serially.
Memory grew with the stream count and each run cost O(n) round trips.

  • Streams are read in keyset pages of 500, ordered by streamId. A keyset
    cursor (not skip) means pages don't shift while streams are created during
    the run.
  • Dedup is one query per alert type per page (streamId IN (…) AND sentAt >= cutoff),
    which the (streamId, alertType) index answers directly.
  • calculateStreamRunway takes the Prisma Stream row instead of any.

1 200 streams now cost 3 stream queries + 6 history queries, against 1 +
up to 2 400 before.

#1900 — dead code

  • Deleted src/services/indexer.service.ts — an older fork of indexerService.ts,
    imported nowhere, named only in the vitest coverage excludes.
  • Removed /v1/streams/batch, /v1/streams/import and /v1/payroll/import
    from the 1mb body allowlist: no such routes exist, so the entries only reserved
    memory for requests that could never succeed. /v1/streams/simulate stays —
    that route exists and does carry a batch_withdraw payload.
  • The replay comment in indexerService.ts claimed withdrawnAmount was
    incremented unconditionally on replay and cited [Docs] replayFromLedger JSDoc falsely claims worker dedup guarantees idempotent replay #808. The handler checks for
    the duplicate before mutating, so the comment now describes what the code
    does.

The body-limit test asserted the phantom route kept its 1mb allowance; it now
asserts the request falls to the standard 100kb limit and gets a 413.

#1901 — log by status, don't echo errors

  • errorHandler logged Unhandled error before classifying anything, so
    every rejected request (Zod 400, duplicate-key 409) landed in the error stream.
    It now resolves the status first: 5xx at error, 4xx at warn with the route.
  • webhook.controller.ts no longer returns error.message; texts pass through
    sanitizeDatabaseErrorMessage, which is what exists for this.
  • graphql/routes.ts logs the failure with its stack and returns a stable
    message instead of error.message.

The existing P2002 test asserted the bug (it required logger.error for a 409),
so it now asserts warn was called and error was not.

#1902 — declare axe-core

a11y.test.tsx imports axe-core directly, but it was in no package.json; it
resolved only as a hoisted transitive dependency of eslint-plugin-jsx-a11y.
Declared in frontend/package.json (^4.11.1, the version already installed — the
lockfile records it without pulling anything new), and jsdom is removed: the
manifest listed it while vitest.config.ts runs happy-dom.

Checks

  • npx vitest run (backend): 957 passed, 21 skipped, 2 failed — the two
    failures are tests/token-routes.integration.test.ts, which fail identically
    with my changes stashed (the route returns 500 in this environment, no DB).
    They are pre-existing and unrelated; I did not touch the token routes.
  • New: tests/stream-runway-worker.test.ts — 2 tests (query bounds on 1 200
    streams, and dedup skipping an already-alerted stream)
  • tests/error.middleware.test.ts, tests/body-size-limit.test.ts,
    tests/webhook-delivery.test.ts, tests/notification.service.test.ts — all
    pass
  • npx tsc --noEmit (backend) — clean
  • npx vitest run src/__tests__/a11y.test.tsx (frontend) — 4 passed
  • npm install --package-lock-only — lockfile updated for the two manifest changes

The hourly runway check loaded every active stream in one unbounded query, then
asked the alert history once or twice per stream, awaited serially. Memory grew
with the number of streams and every run cost O(n) round trips (LabsCrypt#1899).

Streams are now read in keyset pages of 500 ordered by streamId, and the dedup
check is one query per alert type per page against the (streamId, alertType)
index: three stream queries and six history queries for 1_200 streams instead of
one plus up to 2_400.

The stream parameter is also typed as the Prisma Stream row instead of any,
which is what let the shape drift without a compiler complaint.

Test: 1_200 streams produce exactly 3 stream queries and 6 dedup queries, and a
stream already alerted in the window is skipped while its neighbour is not.
… limits

Three pieces of dead weight (LabsCrypt#1900):

- src/services/indexer.service.ts was an older fork of indexerService.ts,
  imported nowhere and named only in the vitest coverage excludes. Two
  near-identical indexer services invite edits to the wrong file.
- The JSON body allowlist granted 1mb to /v1/streams/batch, /v1/streams/import
  and /v1/payroll/import - none of which exist in src/. A route-less entry only
  reserves memory for requests that can never succeed, so those three are gone
  and /v1/streams/simulate is left.
- indexerService's replay comment still warned that withdrawnAmount is
  incremented unconditionally on replay and pointed at LabsCrypt#808. The handler now
  checks for the duplicate before mutating, so the comment describes a bug that
  is no longer there.

The body-limit test that asserted the phantom route keeps its 1mb now asserts it
falls to the standard limit: an allowlist entry with no route behind it is not a
feature to preserve.
The error middleware logged 'Unhandled error' before classifying anything, so a
400 from a Zod schema or a 409 from a duplicate key was logged at error level
alongside real incidents - which is how an on-call rotation learns to ignore the
error stream (LabsCrypt#1901).

The handler now resolves the status first and logs server-side failures at error,
rejections at warn with the route. The webhook controller and the GraphQL
executor no longer put exception text in the response: Prisma messages name
models and columns, and sanitizeDatabaseErrorMessage exists for exactly this.
GraphQL failures are logged with the stack and answered with a stable message.

The existing P2002 test asserted the bug - it required logger.error for a 409 -
so it now asserts warn and no error.
src/__tests__/a11y.test.tsx imports axe-core directly, but axe-core appeared in no
package.json: it resolved as a transitive dependency of eslint-plugin-jsx-a11y,
hoisted by npm. A change to the ESLint stack, or an installer that does not
hoist, breaks the a11y suite with a module-not-found and nothing in the manifest
to explain it (LabsCrypt#1902).

axe-core is now a declared devDependency, and jsdom - which the manifest listed
while vitest.config.ts uses happy-dom - is gone. The lockfile is updated; the
installed version was already 4.11.1, so nothing new is pulled.
…unway-paging-logging-cleanup

# Conflicts:
#	backend/src/controllers/webhook.controller.ts
#	backend/vitest.config.ts
resolveErrorStatus referenced LibApiError/TypeApiError, which do not exist,
and read .status off ApiError (it exposes statusCode). The merged tree failed
to compile, which failed Backend CI, the Docker image build and the ephemeral
preview.
Backend CI lints before it tests, so `callback` being unused in the
token-registry mock and the newline before `[method](path)` in the
webhook-auth owner test failed the job before vitest ran (and left no
coverage report). Rename the mock arg to `_callback` and put the dynamic
method call on the same line as the request object.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant