Repository navigation
Worker: while the usage ledger is frozen or reconciling, run only recovery work and exit withdrawals - #546
Merged
Conversation
Agent: codex/gpt-6.1-terra
Agent: codex/gpt-6.1-terra
Agent: codex/gpt-6.1-terra
…hedule test Agent: codex/gpt-6.1-sol
…intent Agent: codex/gpt-6.1-sol
teddashh
added a commit
that referenced
this pull request
Nov 21, 2026
Co-Authored-By: Codex <noreply@openai.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.
After a database restore, the operator freezes the usage ledger before control and the worker start, and the ledger stays
frozenorreconcilinguntil recovery completes. In that time the worker should do only work that makes the restored state safe or converges it. Before this change,Dispatcher.Onceclaimed every due outbox event whatever the ledger's mode, so device discovery, fleet updates, provisioning, policy evaluation and exit publication were dispatched on restored data. Separately,exits.ExecuteOperationnever compared a publication operation with the exit's current intent. An operation that ran after a newer command, for example a retry after backoff, could publish a route that had since been withdrawn, or withdraw one that had since been published.What changes.
internal/db/outbox.go,apps/worker/worker.go).db.ClaimOutboxByLedgerModeis the candidate query ofClaimOutboxwith one more condition:usage_ledger_state.modeisnormal, or the event's type is in the allowed list, or the type isnode.publication_changedand the operation that the payload'soperation_idnames has a withdrawal kind.Dispatcher.Oncenow claims through it. A missing ledger row counts as restricted.ClaimOutboxitself is unchanged.WHERE, so an event that must wait is not locked, not leased and not counted: itsattemptdoes not rise and it is not dead-lettered for waiting. Older waiting events do not hold up an allowed one. When the mode isnormalagain, the next claim takes the oldest due event, as before.FOR UPDATE SKIP LOCKEDstill applies tooutbox_eventsonly. A claim does not wait for a transaction that holds the ledger row or an operation row.apps/worker/recovery_mode.go).normal:member.entitlement_changed,member.grant_revoked,member.suspended,device.authorized,device.revoked,netbird.device_sync,members.reconcile,billing.reconcile,billing.inbox_received,node.staleness.sweep,node.generation_hold.check,node.peer.observe,node.resolver_documents.reconcile,node.netbird_routes.reconcile,dns.publishanddns.feed.refresh.node.publication_changed:node.unpublish,node.disable,node.revokeandnode.retire. A publish waits.devices.discover,node.reconcile,fleet.update_created,fleet.first_sync_created,fleet.update_retry,fleet.release_support_changed,node.updated,node.provision.requested,node.peer.discover,release.verify,policy.activated,fup.evaluate,fup.member_generation_changed,usage.projection_rebuildandusage.retention_purge. A type that is in no list waits as well.operation_idis cast touuidonly when it is a JSON string thatpg_input_is_validaccepts. That function needs PostgreSQL 16 or later; CI and the deployment image run 17. While the mode is notnormal, an event without an id, with an id that is not a string or not a UUID, or with an id that names no operation waits. It cannot make the claim fail.apps/worker/jobs_members.go).scheduleMemberWorkenqueues a waiting type only when the mode isnormal. Of the three types it schedules, that isdevices.discover: its row id changes with every interval, so the rows would otherwise pile up during a long recovery.internal/exits/exits.go).ExecuteOperationalready holds the per-node publication lock and has re-read the operation. It now supersedes anode.publishoperation when the exit'spublication_intentis notpublished, and anode.unpublishornode.disableoperation when it ispublished. Nothing is sent to NetBird for a superseded operation, and the worker's handler already treatssupersededas finished. The status trigger letsfailedchange only torunning, so afailedoperation that contradicts the intent is moved torunningand then superseded in the same transaction.node.revokeandnode.retirealways run, apartially_succeededoperation is kept, and a node without an exit row is not affected. The guard applies in every mode.Tests (integration, against PostgreSQL, unless marked):
TestRecoveryModeT1_ClaimByMode(apps/worker): one due event for every registered type, for three unregistered types, and onenode.publication_changedevent for each of the five operation kinds. Innormalevery event is claimed. Infrozen, inreconcilingand without a ledger row, exactly the allowed types and the four withdrawal events are claimed; the test carries its own expected list and does not read the worker's. Two more subtests holdFOR UPDATEon the ledger row and on the operation row and require the claim to return the withdrawal event within two seconds, one inreconcilingand one innormal.TestRecoveryModeT2_WaitingRowsUntouched: inreconciling, with an event of every waiting type (one of them with an expired lease and two attempts), three unregistered types, a publish event, an event with an invalid operation id and a dead-lettered row, twenty dispatch rounds do no work and everyoutbox_eventsrow is unchanged, compared as JSON. Back innormal, the first claim is the oldest event, withattempt1.TestRecoveryModeT3_MalformedPublicationPayloads: with a withdrawal operation present, events with no id, a string that is not a UUID, a number and an unknown UUID are not claimed and do not change, and the claim returns no error.TestRecoveryModeT4_NoHeadOfLineBlocking: fifty older waiting events do not keep the dispatcher from an allowed one.TestRecoveryModeT6_MemberSchedule: infrozen, inreconcilingand without a ledger row, one schedule cycle enqueuesbilling.reconcileandmembers.reconcileand nodevices.discover; innormalit enqueues all three.TestRecoveryModeT7_RegistrationCoverage(unit): every type in the production registration is in exactly one of the lists.TestRecoveryModeT5_PublicationIntentGuard(internal/exits): an obsolete publish after a newer unpublish, and an obsolete unpublish or disable after a newer publish, endsupersededwith no call to the adapter and no change to the observed route. The same holds for an obsolete operation that had failed once. Apartially_succeededwithdrawal stays as it is, revoke and retire run although the intent ispublished, a current publish runs, and an operation of a node without an exit is not superseded.TestRecoveryModeT8_RevocationWithdrawal(internal/nodes/httpwire): a published exit, then a freeze and the start of recovery through the usage service, then a revocation command. The production dispatcher works until its claim is empty; the revoke operation endssucceededorpartially_succeeded, the route is observed as withdrawn, and the mode is stillreconciling. It runs with and without a node observation after the freeze.Deliberate breakages, each reverted afterwards. On the first three commits:
normal: the three restricted cases ofTestRecoveryModeT1_ClaimByModeandTestRecoveryModeT2_WaitingRowsUntouchedfailed;node.publication_changedevent is allowed whatever its operation's kind: the same three cases andTestRecoveryModeT3_MalformedPublicationPayloadsfailed;operation_idcast without its check:TestRecoveryModeT3_MalformedPublicationPayloadsfailed withSQLSTATE 22P02;publish_then_unpublish,unpublished_then_publishanddisabled_then_publishofTestRecoveryModeT5_PublicationIntentGuardfailed;devices.discoverin every mode: thereconcilingandmissingcases ofTestRecoveryModeT6_MemberSchedulefailed (thefrozencase did not exist yet);members.reconcileremoved from the allowed list:TestRecoveryModeT7_RegistrationCoverageand the three restricted cases ofTestRecoveryModeT1_ClaimByModefailed.On the final commit:
FOR SHAREon the ledger read of the claim: onlydoes_not_lock_ledger_in_normal_modefailed, at its two-second deadline;FOR SHAREon the operation read: onlydoes_not_lock_ledger_or_operationfailed, at its deadline;frozenasnormal: only thefrozencase ofTestRecoveryModeT6_MemberSchedulefailed;partially_succeeded_withdrawal_is_keptfailed, withinvalid operation transitionfrom the status trigger;failedtorunningremoved: onlyfailed_publish_then_unpublishandfailed_unpublish_then_publishfailed.Validation: on the exact source
befaf969:go vetofinternal/db,internal/exits,internal/nodes/httpwireandapps/worker, plain and with the integration tag, for linux/amd64 and linux/arm64;TestRecoveryMode*tests (six inapps/worker, one ininternal/exits, one ininternal/nodes/httpwire), and ofTestRecoveryModeT1_ClaimByModethe subtestsdoes_not_lock_ledger_or_operation,does_not_lock_ledger_in_normal_modeandmissing_ledger_state;TestRecoveryModeT7_RegistrationCoveragealso once without the integration tag;Test15_1_SchemaGuards,Test15_1_Uint64Bounds,Test15_5_Migrations,Test15_5_MigrationsRoundTrip,Test15_5_MigrationDownLintandTest14_1_OpenScansTimestamptzUTCeach passed exactly once;internal/db, which the database job above ran;go-lint,go test ./...(95 packages ok; 2 of them came from Go's test cache (internal/fleetupdateandinternal/releases: their tests had passed a few minutes earlier in the same tree, in the fleet update job's unit test step above; no changed package was cached)), the build of every command for amd64 and arm64, and the tidy check;TestD096_RealNetBird), build;e2e-configstep not run);fvpn-controlandfvpn-worker(12 tests passed, none failed, flaky or skipped);Then the same checks on a temporary merge of this source into main
2d04cffc, which merged without conflicts:go vetofinternal/db,internal/exits,internal/nodes/httpwireandapps/worker, plain and with the integration tag, for linux/amd64 and linux/arm64;TestRecoveryMode*tests (six inapps/worker, one ininternal/exits, one ininternal/nodes/httpwire), and ofTestRecoveryModeT1_ClaimByModethe subtestsdoes_not_lock_ledger_or_operation,does_not_lock_ledger_in_normal_modeandmissing_ledger_state;TestRecoveryModeT7_RegistrationCoveragealso once without the integration tag;Test15_1_SchemaGuards,Test15_1_Uint64Bounds,Test15_5_Migrations,Test15_5_MigrationsRoundTrip,Test15_5_MigrationDownLintandTest14_1_OpenScansTimestamptzUTCeach passed exactly once;internal/db, which the database job above ran;go-lint,go test ./...(96 packages ok; 2 of them came from Go's test cache (internal/fleetupdateandinternal/releases: their tests passed earlier on the same merge tree in the fleet update job's unit test step; no changed package was cached)), the build of every command for amd64 and arm64, and the tidy check;TestD096_RealNetBird), build;e2e-configstep not run);fvpn-controlandfvpn-worker(12 tests passed, none failed, flaky or skipped);These are local runs; no CI result is claimed here.
Review: An independent review of the first three commits asked for changes. Two points were about tests: the lock subtest ran only in
reconciling, where the ledger read returns no row, so it could not see a row lock on that read, and the schedule test had nofrozencase. It also noted that the guard skipped an operation leftfailed. The worker's handler moves such an operation back torunningwhile attempts remain, but a worker that stops between the two writes leaves itfailedfor the next delivery. The guard's status condition was untested as well. The last two commits add thenormallock subtest and thefrozencase, supersede a contradictingfailedoperation, and test the status condition. The review's last point is left for a later change: an allowed handler whose compile waits for a node observation after the freeze can use up its retry budget during recovery, as it can before this change.A second review, of the last two commits, found those points resolved and rated one interleaving a blocker: an intent change that commits between the guard's two statements leaves a
failedoperation unsuperseded, and it is executed. The project lead's analysis was that this ends in the same state as an intent change that commits just after the guard, which a check made before the NetBird call cannot exclude. The command that changes the intent also creates the operation for the new intent, and that operation runs afterwards under the same per-node lock, so the last operation executed for the node matches the intent. Because the reviewer had rated it a blocker, a third model was asked to adjudicate from the code without seeing that analysis. It reached the same conclusion, and no code changed for it. The second review also suggested a subtest for afailedoperation whose intent still matches; that was not required.Agent: codex/gpt-6.1-sol
Prepared with Codex; implementation and review attribution are recorded above.