fix(cas): acquire document advisory lock before OH13 CAS

Pass 5 P1b — assertCampaignDocCas now requires a transaction req, locks
campaign-doc-cas:{collection}:{id}, and re-reads updatedAt under the lock.
Leadership form updates and chip deltas share that key; political trend
goes through the same helper. Concurrent writers int pin added.
This commit is contained in:
Cursor Agent 2026-08-02 06:59:20 +00:00
parent caec1237ff
commit af01817f57
No known key found for this signature in database
6 changed files with 141 additions and 71 deletions

View file

@ -238,8 +238,8 @@ Statuses: pending · in-progress · awaiting-evidence · done · deferred: \<rea
| WS | Content | Status | | WS | Content | Status |
| ------ | --------------------------------------------------------------------------------------------------- | ------------- | | ------ | --------------------------------------------------------------------------------------------------- | ------------- |
| P5-P0 | Logout always clears persisted outbox+mirror adapters (singleton-independent) + pins | in-session PR | | P5-P0 | Logout always clears persisted outbox+mirror adapters (singleton-independent) + pins | merged (#233) |
| P5-P1a | Activity hybrid: disable offline-unsupported fields; send null on cleared relations + pins | in-session PR | | P5-P1a | Activity hybrid: disable offline-unsupported fields; send null on cleared relations + pins | merged (#234) |
| P5-P1b | CAS: advisory lock around assert+mutate paths (document key) + concurrent int pin | in-session PR | | P5-P1b | CAS: advisory lock around assert+mutate paths (document key) + concurrent int pin | in-session PR |
| P5-M\* | GUARDRAILS provenance → public issue #s; harden dodgeable miss guards; `Closes #48 #49 #50 #54 #41` | in-session PR | | P5-M\* | GUARDRAILS provenance → public issue #s; harden dodgeable miss guards; `Closes #48 #49 #50 #54 #41` | in-session PR |

View file

@ -86,9 +86,9 @@ Ledger of known engineering debt. Items large enough to be scheduled work become
| ---------- | ---------------- | ----- | | ---------- | ---------------- | ----- |
| (none yet) | | | | (none yet) | | |
| Logout wipe for campaignOps outboxes/mirror is gated on in-memory singletons — after cold reload IndexedDB (`teqo-ops-*`) + mirror OPFS/IDB survive `clearCampaignOpsStorage` | `clearCampaignOpsStorage.ts`; `ops*Outbox.ts` `clear*ForLogout`; `opsMirrorClient.clearOpsMirrorPersistenceForLogout` | privacy / shared-device | high — next actor can hydrate prior queue/mirror | M | P0 | open — Pass 5 (remediation in-session) | P5-P0 | | Logout wipe for campaignOps outboxes/mirror is gated on in-memory singletons — after cold reload IndexedDB (`teqo-ops-*`) + mirror OPFS/IDB survive `clearCampaignOpsStorage` | `clearCampaignOpsStorage.ts`; `ops*Outbox.ts` `clear*ForLogout`; `opsMirrorClient.clearOpsMirrorPersistenceForLogout` | privacy / shared-device | high — next actor can hydrate prior queue/mirror | M | P0 | closed 2026-08-02 (Pass 5 P5-P0): wipe opens adapters even when singletons are null; pin `tests/unit/opsLogoutWipe.unit.spec.ts` | P5-P0 |
| Activity hybrid edit renders tasks/demands and omits cleared `responsible`/`leadership` (null never sent); outbox payload is a fork of the server FormData contract | `ActivityForm.tsx` hybrid submit (~599-616); message admits tasks need connection but fields stay editable | correctness | high — silent data loss on edit | M | P1 | open — Pass 5 (remediation in-session) | P5-P1a | | Activity hybrid edit renders tasks/demands and omits cleared `responsible`/`leadership` (null never sent); outbox payload is a fork of the server FormData contract | `ActivityForm.tsx` hybrid submit (~599-616); message admits tasks need connection but fields stay editable | correctness | high — silent data loss on edit | M | P1 | closed 2026-08-02 (Pass 5 P5-P1a): offline-unsupported fields disabled; cleared relations send `null`; pin `tests/unit/activityHybridUpdatePayload.unit.spec.ts` | P5-P1a |
| `assertCampaignDocCas` is check-then-write without document lock — concurrent writers both pass CAS (0 concurrent pins) | `assertCampaignDocCas.ts`; ≥4 call sites without advisory lock around assert+mutate | correctness (OH13 CAS) | high under concurrent/offline conflict | M | P1 | open — Pass 5 (remediation in-session) | P5-P1b | | `assertCampaignDocCas` is check-then-write without document lock — concurrent writers both pass CAS (0 concurrent pins) | `assertCampaignDocCas.ts`; ≥4 call sites without advisory lock around assert+mutate | correctness (OH13 CAS) | high under concurrent/offline conflict | M | P1 | closed 2026-08-02 (Pass 5 P5-P1b): CAS requires txn `req`, acquires `campaign-doc-cas:{collection}:{id}`, re-reads under lock; leadership form+chips share the key; concurrent pin in `domainWritesCas.int.spec.ts` | P5-P1b |
| Push dispatch `queueMicrotask` inside domain transaction — sender re-reads outside txn; can fire for rolled-back rows or miss uncommitted ones | `createCampaignNotification.ts:20-40`; `sendCampaignPush.ts:39-66`; hooks in Supporter/Activity/MunicipalityUpdate | correctness | medium — unreliable push; unhandled rejection | M | P1 | open — Pass 5 | P5-E | | Push dispatch `queueMicrotask` inside domain transaction — sender re-reads outside txn; can fire for rolled-back rows or miss uncommitted ones | `createCampaignNotification.ts:20-40`; `sendCampaignPush.ts:39-66`; hooks in Supporter/Activity/MunicipalityUpdate | correctness | medium — unreliable push; unhandled rejection | M | P1 | open — Pass 5 | P5-E |
| Three offline outbox runtimes re-spell init/collapse/conflict/clear (~1 854 LOC) | `opsMunicipalityOutbox.ts` 711, `opsDomainOutbox.ts` 652, `opsEstimateOutbox.ts` 208 | duplication | medium — logout/CAS bugs copy three times | L | P2 | open — Pass 5 | P5-A | | Three offline outbox runtimes re-spell init/collapse/conflict/clear (~1 854 LOC) | `opsMunicipalityOutbox.ts` 711, `opsDomainOutbox.ts` 652, `opsEstimateOutbox.ts` 208 | duplication | medium — logout/CAS bugs copy three times | L | P2 | open — Pass 5 | P5-A |
| Outbox UI lifecycle (pending/conflict toasts) copied ×7 (~300 LOC) | PledgeEstimateForm, DeclareVotesForm, MunicipalityListAdvisorsControl, DemandWorkflowCard, LeadershipListSupportStatusControl, LeadershipInternalForm, ActivityForm | duplication | low | M | P2 | open — Pass 5 | P5-B | | Outbox UI lifecycle (pending/conflict toasts) copied ×7 (~300 LOC) | PledgeEstimateForm, DeclareVotesForm, MunicipalityListAdvisorsControl, DemandWorkflowCard, LeadershipListSupportStatusControl, LeadershipInternalForm, ActivityForm | duplication | low | M | P2 | open — Pass 5 | P5-B |

View file

@ -3,13 +3,19 @@ import type { Payload } from 'payload'
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas' import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
import type { CampaignUser } from '@/payload-types' import type { CampaignUser } from '@/payload-types'
import type { PayloadTransactionRequest } from '@/utilities/payloadTransaction' import type { PayloadTransactionRequest } from '@/utilities/payloadTransaction'
import { acquireTextAdvisoryLocks } from '@/utilities/postgresTransactionLocks'
type CasCollection = 'leadership' | 'campaignDemand' | 'activity' | 'stateDeputy' | 'municipality' type CasCollection = 'leadership' | 'campaignDemand' | 'activity' | 'stateDeputy' | 'municipality'
/** Shared advisory-lock key for document CAS — form + relation writers must agree. */
export const campaignDocCasLockKey = (collection: CasCollection, id: number): string =>
`campaign-doc-cas:${collection}:${id}`
/** /**
* OH13 — shared CAS gate used by domain writes (3+ call sites). When armed, * OH13 / Pass 5 P1b — shared CAS gate. When armed, acquires a per-document
* loads the doc's `updatedAt` under the actor's row access and refuses on * advisory lock, re-reads `updatedAt` under the actor's row access, and refuses
* mismatch. Does not replace RBAC or wrap the mutation itself. * on mismatch. Callers must pass an active transaction `req` whenever CAS is
* enforced — check-then-write without a lock is not CAS.
*/ */
export const assertCampaignDocCas = async ( export const assertCampaignDocCas = async (
payload: Payload, payload: Payload,
@ -19,11 +25,15 @@ export const assertCampaignDocCas = async (
actor: CampaignUser actor: CampaignUser
enforceCas: boolean enforceCas: boolean
baseUpdatedAt: string | null | undefined baseUpdatedAt: string | null | undefined
req?: PayloadTransactionRequest req: PayloadTransactionRequest
}, },
): Promise<void> => { ): Promise<void> => {
if (!args.enforceCas || args.baseUpdatedAt === undefined) return if (!args.enforceCas || args.baseUpdatedAt === undefined) return
await acquireTextAdvisoryLocks(payload, args.req, [
campaignDocCasLockKey(args.collection, args.id),
])
const current = await payload.findByID({ const current = await payload.findByID({
collection: args.collection, collection: args.collection,
id: args.id, id: args.id,
@ -31,7 +41,7 @@ export const assertCampaignDocCas = async (
select: { updatedAt: true }, select: { updatedAt: true },
user: args.actor, user: args.actor,
overrideAccess: false, overrideAccess: false,
...(args.req ? { req: args.req } : {}), req: args.req,
}) })
assertOpsUpdatedAtCas(true, args.baseUpdatedAt, current.updatedAt) assertOpsUpdatedAtCas(true, args.baseUpdatedAt, current.updatedAt)

View file

@ -3,6 +3,10 @@
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import {
assertCampaignDocCas,
campaignDocCasLockKey,
} from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
import { nextMunicipalityIdsAfterLeadershipMembership } from '@/lib/leadershipMunicipalityMembership' import { nextMunicipalityIdsAfterLeadershipMembership } from '@/lib/leadershipMunicipalityMembership'
import { nextStateDeputyIdsAfterMembership } from '@/lib/leadershipStateDeputyMembership' import { nextStateDeputyIdsAfterMembership } from '@/lib/leadershipStateDeputyMembership'
import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship' import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship'
@ -182,37 +186,55 @@ export const updateLeadershipInternalRecord = async (
const { id, municipalities, organizations, stateDeputies, baseUpdatedAt, ...data } = const { id, municipalities, organizations, stateDeputies, baseUpdatedAt, ...data } =
leadershipInternalUpdateSchema.parse(input) leadershipInternalUpdateSchema.parse(input)
const enforceCas = options?.cas === true const enforceCas = options?.cas === true
const currentActor = await getFreshStaffActor(payload, actor)
// Row access verifies the current record is in the actor's scope. return withPayloadTransaction(
const current = await payload.findByID({ payload,
collection: 'leadership', async ({ req }) => {
id, const currentActor = await getFreshStaffActor(payload, actor, req)
depth: 0,
user: currentActor,
overrideAccess: false,
})
// Stamp already loaded with the row — avoid a second find via assertCampaignDocCas. // Lock + re-read under CAS (Pass 5 P1b). When CAS is not armed, keep the
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt) // row-access preflight so out-of-scope updates fail closed before mutate.
await assertCampaignDocCas(payload, {
collection: 'leadership',
id,
actor: currentActor,
enforceCas,
baseUpdatedAt,
req,
})
if (!enforceCas || baseUpdatedAt === undefined) {
await payload.findByID({
collection: 'leadership',
id,
depth: 0,
select: { id: true },
user: currentActor,
overrideAccess: false,
req,
})
}
if (municipalities !== undefined) { if (municipalities !== undefined) {
await assertMunicipalitiesWithinScope(payload, currentActor, municipalities) await assertMunicipalitiesWithinScope(payload, currentActor, municipalities, req)
} }
return payload.update({ return payload.update({
collection: 'leadership', collection: 'leadership',
id: current.id, id,
data: { data: {
...data, ...data,
...(municipalities === undefined ? {} : { municipalities }), ...(municipalities === undefined ? {} : { municipalities }),
...(organizations === undefined ? {} : { organizations: organizations ?? [] }), ...(organizations === undefined ? {} : { organizations: organizations ?? [] }),
...(stateDeputies === undefined ? {} : { stateDeputies: stateDeputies ?? [] }), ...(stateDeputies === undefined ? {} : { stateDeputies: stateDeputies ?? [] }),
},
depth: 0,
user: currentActor,
overrideAccess: false,
req,
})
}, },
depth: 0, { beginFailureMessage: 'Não foi possível iniciar a atualização da liderança.' },
user: currentActor, )
overrideAccess: false,
})
} }
export const listMunicipalityLeaderships = async ( export const listMunicipalityLeaderships = async (
@ -400,26 +422,17 @@ const revalidateLeadershipStateDeputyPaths = (leadershipId: number, stateDeputyS
} }
} }
const LEADERSHIP_RELATION_LOCK_KEYS = {
municipalities: 'leadership-municipalities',
stateDeputies: 'leadership-state-deputies',
} as const
/** /**
* Opens a leadership for a delta write on one of its relations: reloads the * Opens a leadership for a delta write on one of its relations: reloads the
* actor, takes the lock that belongs to THAT relation, and reads the current * actor, takes the **document** CAS lock (same key as `assertCampaignDocCas` /
* ids under the actor's row access (the same guard * ficha form), and reads the current ids under the actor's row access.
* `updateLeadershipInternalRecord` relies on).
* *
* The pairing is the point: relation and lock key used to be two independent * Relation-specific keys were dropped in Pass 5 P1b: the ficha form replaces
* string literals a few lines apart, so a third relation could quietly take a * the whole array under `campaign-doc-cas:leadership:{id}`, so a chip delta
* lock that guards a different column. The rest of the two delta writes — the * on a different lock could still lost-update against the form. Chip×chip on
* delta shape, the scope assertion, the slug lookup, the return — is genuinely * the same leadership now serializes too — correct and cheap at our write rate.
* different in each, and hoisting it would cost six callbacks to share ~24 lines.
*/ */
const openLeadershipForRelationDelta = async < const openLeadershipForRelationDelta = async <Relation extends 'municipalities' | 'stateDeputies'>(
Relation extends keyof typeof LEADERSHIP_RELATION_LOCK_KEYS,
>(
payload: Payload, payload: Payload,
actor: CampaignUser, actor: CampaignUser,
req: PayloadTransactionRequest, req: PayloadTransactionRequest,
@ -428,9 +441,7 @@ const openLeadershipForRelationDelta = async <
) => { ) => {
const currentActor = await getFreshStaffActor(payload, actor, req) const currentActor = await getFreshStaffActor(payload, actor, req)
await acquireTextAdvisoryLocks(payload, req, [ await acquireTextAdvisoryLocks(payload, req, [campaignDocCasLockKey('leadership', leadershipId)])
`${LEADERSHIP_RELATION_LOCK_KEYS[relation]}:${leadershipId}`,
])
const current = await payload.findByID({ const current = await payload.findByID({
collection: 'leadership', collection: 'leadership',

View file

@ -2,6 +2,7 @@
import type { Payload } from 'payload' import type { Payload } from 'payload'
import { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
import { import {
ENGAGEMENT_LEVEL_PATTERN_ID, ENGAGEMENT_LEVEL_PATTERN_ID,
EngagementLevelBlockedError, EngagementLevelBlockedError,
@ -89,29 +90,30 @@ export const setMunicipalityPoliticalTrendRecord = async (
const { municipality, status, note, baseUpdatedAt } = const { municipality, status, note, baseUpdatedAt } =
municipalityPoliticalTrendSchema.parse(input) municipalityPoliticalTrendSchema.parse(input)
const enforceCas = options?.cas === true const enforceCas = options?.cas === true
const currentActor = await getFreshStaffActor(payload, actor)
if (enforceCas && baseUpdatedAt !== undefined) { return withPayloadTransaction(payload, async ({ req }) => {
const current = await payload.findByID({ const currentActor = await getFreshStaffActor(payload, actor, req)
await assertCampaignDocCas(payload, {
collection: 'municipality', collection: 'municipality',
id: municipality, id: municipality,
actor: currentActor,
enforceCas,
baseUpdatedAt,
req,
})
return payload.update({
collection: 'municipality',
id: municipality,
data: {
politicalTrend: { status, note },
},
depth: 0, depth: 0,
select: { updatedAt: true },
user: currentActor, user: currentActor,
overrideAccess: false, overrideAccess: false,
req,
}) })
assertOpsUpdatedAtCas(true, baseUpdatedAt, current.updatedAt)
}
return payload.update({
collection: 'municipality',
id: municipality,
data: {
politicalTrend: { status, note },
},
depth: 0,
user: currentActor,
overrideAccess: false,
}) })
} }

View file

@ -124,6 +124,53 @@ describe('updateLeadershipInternalCas (OH13)', () => {
expect(updated.supportStatus).toBe('engajado') expect(updated.supportStatus).toBe('engajado')
expect(updated.updatedAt).not.toBe(leadership.updatedAt) expect(updated.updatedAt).not.toBe(leadership.updatedAt)
}) })
it('serializes concurrent CAS writers — exactly one wins, the other conflicts', async () => {
const fixtures = campaignFixtures()
const municipality = await fixtures.getMunicipality()
const advisor = await fixtures.createCampaignUser('advisor')
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
const contact = await fixtures.createContact()
const leadership = await fixtures.createLeadership({
contact: contact.id,
municipalities: [municipality.id],
supportStatus: 'a_abordar',
})
const baseUpdatedAt = leadership.updatedAt
const results = await Promise.allSettled([
updateLeadershipInternalCasRecord(payload, advisor, {
id: leadership.id,
supportStatus: 'engajado',
baseUpdatedAt,
}),
updateLeadershipInternalCasRecord(payload, advisor, {
id: leadership.id,
supportStatus: 'em_disputa',
baseUpdatedAt,
}),
])
const fulfilled = results.filter((r) => r.status === 'fulfilled')
const rejected = results.filter((r) => r.status === 'rejected')
expect(fulfilled).toHaveLength(1)
expect(rejected).toHaveLength(1)
const conflict = (rejected[0] as PromiseRejectedResult).reason
expect(conflict).toBeInstanceOf(Error)
expect(isOpsUpdatedAtConflictMessage((conflict as Error).message)).toBe(true)
const current = await payload.findByID({
collection: 'leadership',
id: leadership.id,
depth: 0,
overrideAccess: true,
})
const winnerStatus = (fulfilled[0] as PromiseFulfilledResult<{ supportStatus: string }>).value
.supportStatus
expect(current.supportStatus).toBe(winnerStatus)
expect(['engajado', 'em_disputa']).toContain(current.supportStatus)
})
}) })
describe('transitionCampaignDemandCas (OH13)', () => { describe('transitionCampaignDemandCas (OH13)', () => {