Repository navigation
Conversation
LabsCrypt#1848 - depositedAmount had two writers applying the same top-up: the API handler incremented and the Soroban indexer wrote the absolute on-chain value, with nothing joining them. Both now run inside one transaction, take the stream's row lock, and key on the same (transactionHash, TOPPED_UP) marker, so whichever commits second leaves the amount alone. The API's marker records ledgerSequence 0, which the indexer treats as "never confirmed" and reconciles against the event instead of skipping, so chain state stays authoritative in both arrival orders. endTime is projected by one shared helper on both paths, and backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md documents how to audit and repair the rows the old race already drifted. LabsCrypt#1850 - topUpStreamHandler wrapped the chain call, the row lock and the bookkeeping in one catch that answered 400 TOP_UP_FAILED for all of them. Chain failures keep the 4xx; database and unexpected failures now surface as their own status (Prisma-mapped or 500 INTERNAL_SERVER_ERROR), and the `updatedStream!` assertion is gone because the writer returns the amount. LabsCrypt#1851 - two ApiError classes with swapped constructor arguments plus five response shapes meant a caller could silently swap code and message. One ApiError(statusCode, code, message, details?) and one {error:{code,message, details?}} envelope remain; the unused RFC 7807 schema-validator middleware and its tests are deleted. BREAKING for API consumers: every 4xx/5xx body, including 429 rate limits and the CORS rejection, now uses that envelope. Also: stream-lifecycle and cancel-status-filter wiped the whole Stream table in their fixtures. Both files run in parallel against one database, so each deleted the other's rows mid-assertion; their cleanup is now scoped to the streams they own.
LabsCrypt#1747's new subscribe tests asserted the flat `{ message }` and `{ message, errors }` bodies that LabsCrypt#1851 replaces with `{ error: { code, message, details } }`. Statuses, messages, the Retry-After header and the "no SSE headers committed" checks are unchanged.
LabsCrypt#1851 leaves exactly one envelope, so the prose has to stop advertising the shapes it replaced. AUTHENTICATION, SANDBOX_MODE, API_VERSIONING, DEPRECATION_POLICY and the backend README now show `{error:{code,message,details}}` with the codes the middleware really sends, and the sunset example is marked unimplemented instead of implying a 410 no route produces.
K1NGD4VID
marked this pull request as ready for review
November 21, 2026 16:15
13 of 16 tasks
MFrancis-dev
added a commit
to MFrancis-dev/flowfi
that referenced
this pull request
Nov 21, 2026
…ypt#1932 The API writer and the indexer share one dedup key, and the marker row the API leaves behind (ledgerSequence 0) is the only case where the indexer writes through a skip. Nothing pinned which of the two branches a given existing row takes.
K1NGD4VID
pushed a commit
that referenced
this pull request
Nov 21, 2026
#1932 moved the top-up writes behind applyToppedUpEvent, which takes the stream row lock through $executeRaw and selects only the columns it needs, and started storing the event timestamp as a BigInt. The fake client has to mirror that seam or the suite describes a shape the worker no longer has.
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.
Description
Three backend correctness issues that share one root cause — the error path and the top-up write path each had more than one version of the truth — solved together because they collide in the same files.
depositedAmounthad two independent writers.topUpStreamHandlerran a raw-SQL increment after the chain call, andhandleStreamToppedUpwrote the absolute on-chain value from the event. The handler wrote noTOPPED_UPevent row, so thetransactionHash_eventTypededup key protected neither write. If the indexer committed first, the handler added the amount on top and the stream was permanently overcounted.topUpStreamHandlerwrapped the chain call, thefindUniqueand the SQL increment in a singlecatchthat always answered400 TOP_UP_FAILED. A Postgres outage was reported to the client as "your transaction failed on chain", which invites a retry that pays twice.ApiErrorclasses with swapped constructor signatures, five response shapes, and an RFC 7807 middleware nothing imported.After this PR there is one
ApiError, onesendApiError, exactly onejson({ error … })literal left inbackend/src, and exactly one place that decides whether a top-up has already been applied.Type of Change
Related Issues
Closes #1848
Closes #1850
Closes #1851
Changes Made
#1848 — one writer decides, in either arrival order
backend/src/services/top-up-writer.ts(new) holds both writers, and both takeSELECT … FOR UPDATEon theStreamrow (top-up-projection.ts:37) and key their bookkeeping on the sameStreamEvent(transactionHash, "TOPPED_UP")row:applyTopUpOnce(handler) — applies the increment only when no marker exists, then writes a marker carryingledgerSequence: 0, which means "applied by a process that has no ledger position". It returns the authoritativedepositedAmounteither way, which is what the HTTP response now reports.applyToppedUpEvent(indexer) — treatsledgerSequence !== 0as "I already read this off the chain" and skips, so a replay cannot roll the row back to a stale absolute value. A0marker is not skipped: that event is the API's guess meeting its first confirmation, so the indexer overwrites the amount with the absolutenew_deposited_amountand rewrites the marker with the real ledger sequence.handleStreamToppedUpinsoroban-event-worker.tsis now a call into that function; the increment/decrement logic it used to own is gone.endTimealso stops being derived twice:projectedEndTime()is the one formula (startTime + deposited/rate + totalPausedDuration,nullat rate 0), used by both writers.Trade-off — why not the issue's preferred Option A. Option A makes the indexer the only writer and reduces the handler to reporting
txHash. ButTopUpResponse.depositedAmountis a required field in the published contract (backend/swagger/flowfi.openapi.json, mirrored intofrontend/src/lib/api-types.generated.ts:3738) and its description promises "New total deposited amount after the top-up" — a promise only a writer can keep. Option A therefore means either a spec change plus regenerated types plus a frontend release, or a required field that silently means "whatever the indexer last saw". This repo gates on exactly that drift, so I kept the contract and took the option the issue lists as acceptable: make the handler's write conditional, inside one transaction, keyed on the event the dedup index already covers. The cost is one new convention —ledgerSequence = 0now means "chain-unconfirmed", and any future reader ofStreamEventhas to know it. It is documented at the constant (top-up-writer.ts:9-14), andapplyTopUpOncereturns the row's authoritative amount whether or not this call applied it, so the response stays truthful.Existing damage.
backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.mdis the runbook: why the event log alone can prove or repair the drift (the handler wrote no event, so absent rows are indeterminate — chain is the only witness), a read-only audit query, the repair statement with its dry-run guard, a verification pass, and escalation for negative drift. No migration is included: repairing production rows from a PR is not something to do by hand at merge time.#1850 — status codes that mean what they say
topUpStreamHandlernow has three exits instead of one:400 TOP_UP_FAILED400 TOP_UP_FAILED(unchanged, narrowed to the chain call only)400 TOP_UP_FAILED404 NOT_FOUND, same code as the pre-flight read so a caller cannot tell which lookup missed400 TOP_UP_FAILEDfromPrismaErrormapping (409 DUPLICATE_ENTRY,404 RESOURCE_NOT_FOUND, …)400 TOP_UP_FAILED500 INTERNAL_SERVER_ERRORdepositedAmount: updatedStream!.depositedAmountis gone — the value now comes back from the writer, so there is no non-null assertion in the handler (grep '[A-Za-z_)\]]!\.' backend/src/controllers/stream.controller.tsreturns nothing) and no second read that can miss.#1851 — one envelope
lib/api-error.tsis the only implementation;types/api-error.tsis deleted. Both use(statusCode, code, message, details?)— the ordersendApiErroralready had, becausecodeis what clients branch on andmessageis display text.sendApiErroromitsdetailsentirely when it is undefined rather than sendingdetails: null.The five ad-hoc shapes are replaced at their sites, e.g.:
middleware/auth.ts{ error: 'Unauthorized', message }401 {error:{code:'UNAUTHORIZED',message}}controllers/stream/simulate.ts{ error, code }controllers/stream.controller.ts:135{ error, message }409 {error:{code:'STREAM_NOT_CONFIRMED',message,details:{hint}}}controllers/webhook.controller.ts:40{ error: error.message }400/500envelope with a stable codemiddleware/error.middleware.ts{ message: 'Internal server error' }500 {error:{code:'INTERNAL_SERVER_ERROR',…}}src/app.tsCORS rejection{ error: err.message }403 {error:{code:'FORBIDDEN',message}}middleware/schema-validator.middleware.tsapplication/problem+jsonerror.middleware.tsno longer reaches through(err as any)to find anApiError: it narrows withinstanceof ApiError, and a status-only duck-shaped error is handled by one explicitstatusOf()helper with a comment saying why it exists (thebody-parserandcorspackages throw their own errors we do not own).schema-validator.middleware.ts: deleted, not wired up. It was never imported, never in a route, and its contract contradicted both the shipped OpenAPIErrorschema and every test in the repo. Wiring it up would have meant migrating ~184 call sites to a second envelope; the issue asks for one envelope, so RFC 7807 is the thing that goes. Nothing inbackend/,frontend/ordocs/references it any more (grep -rn 'schema-validator\|7807\|problem+json'is empty outside ignoredbackend/dist).Repairs needed to make the suite green (not part of any issue)
tests/integration/cancel-status-filter.test.tsandtests/integration/stream-lifecycle.test.tseach ran an unscopeddeleteMany()overStream/StreamEvent/UserinbeforeEach. Vitest runs test files in parallel forks against one database, so whichever file seeded second had its fixtures deleted mid-test. Both cleanups are now scoped to the rows their own file seeds (explicitstreamIdlist plus the per-processKeypair.random()wallets). See Baseline below — this is a pre-existing failure onmain, reproduced on an untouched checkout.Documentation
The prose advertised the shapes this PR removes.
backend/README.mdnow states the envelope once (including429 RATE_LIMITED,413 PAYLOAD_TOO_LARGEand the CORS403 FORBIDDEN), andAUTHENTICATION.md,SANDBOX_MODE.md,API_VERSIONING.mdandDEPRECATION_POLICY.mdshow the codes the middleware really returns. The410 Gonesunset body in the deprecation docs is marked not yet implemented rather than silently reshaped, because no route insrc/produces it.Testing
Baseline (proves which failures are pre-existing)
Run against an untouched
git archiveexport oforigin/mainat2a1a259, same Postgres, same commands:That failure is the parallel-fork fixture race described above; it is red on
maintoday and this PR is what makes it green.This branch
Test Steps
cd backend && npm run buildDATABASE_URL=postgresql://postgres:password@127.0.0.1:5432/flowfi_test NODE_ENV=test npx vitest run --coverage tests/integration/top-up.test.ts— covers both arrival orders and two concurrent writers on one stream.tests/soroban-event-worker.test.ts— the marker-with-0reconcile path and the skip path.tests/integration/cancel-status-filter.test.ts tests/integration/stream-lifecycle.test.tsrun together; onmainthat pair is red, here it is green.Test Coverage
Breaking Changes
Breaking Changes:
body.erroras a string — or readbody.message/body.codeat the top level — must now readbody.error.messageand branch onbody.error.code. This includes429from the rate limiter,413from the body-size limiter, and the CORS403, which previously bypassed the funnel entirely.400 TOP_UP_FAILEDis no longer returned for server-side failures onPOST /v1/streams/:id/top-up; those are500 INTERNAL_SERVER_ERROR([Backend] Return accurate error codes from topUpStreamHandler instead of blanket 400s #1850). Monitors keyed on 400 for DB incidents will now see 5xx, which is the point of the issue.backend/src/types/api-error.tsis deleted. It was exported to nothing outsidesrc/(the build proves it), but anything importing it from a script breaks.StreamEvent.ledgerSequence = 0becomes meaningful: it marks a row written by the API, not by the indexer. Dashboards or queries that treat0as "unknown ledger" will now see it as a real state.Migration Guide:
The only frontend reader of the old flat shape was
fetchinfrontend/src/lib/api/webhooks.ts, updated here along with its test. Consumers should readcodeand treatmessageas display text — it is the part that is allowed to change.Checklist
0means unconfirmed; why the marker is reconciled rather than skipped; why Option B over the issue's Option A)docs/api/flowfi.postman_collection.jsonalready documents the envelope verbatim, so no edit was needednpm run codegen:openapiinbackend/, thennpm run codegen:api-typesinfrontend/) and committed the regeneratedflowfi.openapi.json/api-types.generated.ts— both ran; both files are byte-identical, becausecomponents.schemas.Errorin the spec already described{code,message,details}. The spec was aspirational and the code is what moved.backend/docs/observability/— no metric added or renamed; the only new log lines arelogger.infoAdditional Notes
Conflict with #1930 (Ajoke's wave-14 batch), same base
2a1a259, and GitHub reports both mergeable only because neither has merged yet. #1930 addsrequestIdtobackend/src/types/api-error.ts— the file this PR deletes — and movesrequestIdMiddlewareahead ofglobalRateLimiterinbackend/src/app.ts. Whichever lands second needs a small port:plus
requestId?: stringonApiErrorBodythere instead of intypes/api-error.ts, and #1930'ssoroban-event-worker.tschange re-applied insidetop-up-writer.tsrather than at the old call site. Suggested merge order: this PR first (it deletes a file #1930 edits), then #1930 rebases with the four lines above. Say the word and I will do that port on #1930's branch instead.Found and deliberately not changed:
handleFeeCollected(soroban-event-worker.ts:1242) does its dedup read and itsstreamEvent.upsertas two separate top-levelprismacalls, i.e. exactly the class of race [Backend] Fix top-up double-write race between API handler and event indexer #1848 describes for top-ups. fix(backend): fee-event atomicity, request-id propagation, and the #1764/#1766 coverage gaps #1930 already wraps that pair in$transaction, so this PR leaves it alone rather than colliding with it.src/now emits 54 distinct codes, six of which are lowercase:invalid_params,simulation_error,invalid_token_address,token_list_failed,token_lookup_failed,undecodable_payload. They predate this PR, they are pinned by teammate tests, and renaming them is a second breaking change clients would rather get separately. Happy to file it.VALIDATION_ERROR.detailshas two shapes for the same code. Four sites (stream.controller.ts:687,stream/simulate.ts:73,sse.controller.ts:128,compliance.routes.ts:117) pass raw zod issues, sopathis a string array;error.middleware.ts:62maps them and joinspathinto a dotted string. The README and the Postman collection document the zod-native array form because it is the majority. Normalising it means touching assertions in suites this PR does not own.webhook.controller.tsreturns500 INTERNAL_SERVER_ERRORwitherror.message || "Failed to create webhook"— an unfiltered exception string on a 500, unlikeerror.middleware.tswhich sanitises database detail throughfromPrismaError. Pre-existing ({ error: error.message }onmainat the same line); this PR changed the shape around it, not the text, so it is a live disclosure worth its own issue.Four commits, so the code change, the test migration and the prose can be read apart:
6ca5339(fix + tests + the #1848 runbook),5ae876b(test-only: upstream's newsse-auth-cleanup.test.tspinned six assertions to the flat bodies #1851 replaces),745c15e+a135653(docs). 60 files, +1416/−820.