//go:build integration package integration_test import ( "context" "errors" "fmt" "log/slog" "sync" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" "lincodex/backend/internal/usecase/consent" identityusecase "lincodex/backend/internal/usecase/identity" invitationusecase "lincodex/backend/internal/usecase/invitation" "lincodex/backend/internal/usecase/policy" "lincodex/backend/internal/worker/jobrunner" "lincodex/backend/internal/worker/retry" ) const ( // invitationExpiryMigrationVersion adds the pending limit, the pause, and // the expiry at the response deadline. invitationExpiryMigrationVersion = 43 // invitationExpiryJobKind is the kind of the response deadline job. invitationExpiryJobKind = "invitation.response_deadline" ) // noopDeliveryNotifier stands in for the notification outbox: these tests // check the invitation rules, not the events of a delivery. type noopDeliveryNotifier struct{} func (noopDeliveryNotifier) InvitationDelivered(context.Context, outbound.UnitOfWork, domain.Invitation) error { return nil } // invitationLimitsFixture drives the invitation usecases against one isolated // database with the real repositories, quota, consent ledger, and scheduled // job store. Candidates resolve through a table of handles, because the card // visibility rules are tested elsewhere. type invitationLimitsFixture struct { ctx context.Context databaseURL string pool *pgxpool.Pool transactor *postgresadapter.Transactor identity identityFixture organizations organizationFixture clock *testClock service *invitationusecase.Service key domain.CandidateViewPseudonymKey handles map[string]uuid.UUID organization domain.Organization owner domain.User secondOwner domain.User } func newInvitationLimitsFixture(ctx context.Context, t *testing.T, env *testEnvironment, databaseURL string) invitationLimitsFixture { t.Helper() applyMigrations(ctx, t, databaseURL) pool := newPoolFor(ctx, t, databaseURL) if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { t.Fatalf("EnsureDemoProductPolicy() error = %v", err) } // The policy takes effect when it is stored, after the first read of the // clock, as in the HTTP harness. clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)} transactor := postgresadapter.NewTransactor(pool) identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()} organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()} owner := organizations.employer(t, "limits-owner@example.test") confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute)) organization := organizations.create(t, owner, organizations.completeProfile(t, "Limits company"), clock.Now()) secondOwner := identities.createUser(t, "limits-second-owner@example.test", domain.ScenarioEmployer, clock.Now().Add(-time.Hour)) confirmEmail(ctx, t, pool, secondOwner, clock.Now().Add(-time.Minute)) insertOwnerMembership(ctx, t, transactor, organization.ID(), secondOwner.ID, clock.Now()) keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret)) if err != nil { t.Fatalf("NewKeyring() error = %v", err) } key, err := keyring.CandidateViewPseudonymKey() if err != nil { t.Fatalf("CandidateViewPseudonymKey() error = %v", err) } fixture := invitationLimitsFixture{ ctx: ctx, databaseURL: databaseURL, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock, key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, secondOwner: secondOwner, } quota := companyquota.NewService(clock.Now) service, err := invitationusecase.NewService(invitationusecase.Dependencies{ Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) { candidateID, ok := fixture.handles[handle] if !ok || organizationID != organization.ID() { return uuid.Nil, candidateview.ErrCandidateCardNotFound } return candidateID, nil }, Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveInvitation(ctx, unit, organization, invitationID) }, Notifier: noopDeliveryNotifier{}, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now, }) if err != nil { t.Fatalf("invitation.NewService() error = %v", err) } fixture.service = service return fixture } // insertOwnerMembership adds an active owner, which the MVP allows beside the // first one: every owner may send and answer for the organization. func insertOwnerMembership(ctx context.Context, t *testing.T, transactor *postgresadapter.Transactor, organizationID, userID uuid.UUID, at time.Time) { t.Helper() membership, err := domain.NewOwnerMembership(organizationID, userID, at) if err != nil { t.Fatalf("NewOwnerMembership() error = %v", err) } if err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return unit.Memberships().Insert(ctx, membership) }); err != nil { t.Fatalf("insert owner membership: %v", err) } } // confirmEmail marks the account's email confirmed at the given time. The // invitation commands require a confirmed email of both the employer and the // candidate. func confirmEmail(ctx context.Context, t *testing.T, pool *pgxpool.Pool, user domain.User, at time.Time) { t.Helper() if _, err := pool.Exec(ctx, ` UPDATE users SET email_verified_at = $2, version = version + 1 WHERE id = $1`, user.ID, at); err != nil { t.Fatalf("confirm the email of %s: %v", user.ID, err) } } // candidate makes a candidate account that can sign in and gives it a card // handle for the organization. func (fixture *invitationLimitsFixture) candidate(t *testing.T, email string) domain.User { t.Helper() user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour)) confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute)) handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } fixture.handles[handle] = user.ID return user } func (fixture *invitationLimitsFixture) handleOf(t *testing.T, candidateID uuid.UUID) string { t.Helper() handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } return handle } // need stores a need of the organization with its first requirements version. func (fixture *invitationLimitsFixture) need(t *testing.T, title string) domain.InvitationNeedRef { t.Helper() need := newIntegrationNeed(t, fixture.organization.ID(), title, fixture.clock.Now()) fixture.organizations.createNeed(t, need) return domain.InvitationNeedRef{NeedID: need.ID(), RequirementsVersion: need.RequirementsVersion()} } // draft creates a draft for the candidate, under the need when one is given. func (fixture *invitationLimitsFixture) draft( t *testing.T, actor domain.User, candidateID uuid.UUID, need *domain.InvitationNeedRef, period *int32, ) domain.OrganizationInvitationView { t.Helper() key := "create-" + uuid.NewString() view, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{ ActorID: actor.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key, CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID), Need: need, ResponsePeriodDays: period, Terms: invitationStorageTerms(), }) if err != nil { t.Fatalf("Create() error = %v", err) } return view } func (fixture *invitationLimitsFixture) sendCommand(actor domain.User, view domain.OrganizationInvitationView) invitationusecase.SendCommand { return invitationusecase.SendCommand{ ActorID: actor.ID, OrganizationID: fixture.organization.ID(), InvitationID: view.ID, IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: view.Version, } } // send delivers a draft and fails the test when the send is refused. func (fixture *invitationLimitsFixture) send(t *testing.T, actor domain.User, view domain.OrganizationInvitationView) domain.OrganizationInvitationView { t.Helper() sent, err := fixture.service.Send(fixture.ctx, fixture.sendCommand(actor, view)) if err != nil { t.Fatalf("Send() error = %v", err) } return sent } // count reads one number of the database, scoped to the organization. func (fixture *invitationLimitsFixture) count(t *testing.T, query string, args ...any) int64 { t.Helper() var value int64 if err := fixture.pool.QueryRow(fixture.ctx, query, args...).Scan(&value); err != nil { t.Fatalf("count %q: %v", query, err) } return value } // enlargeQuota makes the organization E1, whose weekly invitation quota is // larger than the E0 quota of the demo policy, so that the pending limit is // the rule under test. func (fixture *invitationLimitsFixture) enlargeQuota(t *testing.T) { t.Helper() if _, err := fixture.pool.Exec(fixture.ctx, ` UPDATE organizations SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 WHERE id = $1`, fixture.organization.ID(), fixture.clock.Now()); err != nil { t.Fatalf("raise the organization to E1: %v", err) } } func TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) defer cancel() fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) fixture.enlargeQuota(t) candidate := fixture.candidate(t, "limits-candidate-pending@example.test") need := fixture.need(t, "Pending need") needRef := need for index := range 19 { draft := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil) fixture.send(t, fixture.owner, draft) if index == 18 && fixture.count(t, `SELECT count(*) FROM invitations WHERE need_id = $1 AND state = 'delivered'`, need.NeedID) != 19 { t.Fatal("nineteen invitations are not waiting") } } first := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil) second := fixture.draft(t, fixture.secondOwner, candidate.ID, &needRef, nil) var group sync.WaitGroup results := make([]error, 2) for index, sender := range []struct { actor domain.User view domain.OrganizationInvitationView }{{fixture.owner, first}, {fixture.secondOwner, second}} { group.Go(func() { _, results[index] = fixture.service.Send(ctx, fixture.sendCommand(sender.actor, sender.view)) }) } group.Wait() admitted, refused := 0, 0 for _, err := range results { switch { case err == nil: admitted++ case errors.Is(err, invitationusecase.ErrSendBlocked): refused++ default: t.Fatalf("concurrent Send() error = %v, want success or ErrSendBlocked", err) } } if admitted != 1 || refused != 1 { t.Fatalf("admitted %d and refused %d of two sends with nineteen waiting; want one each", admitted, refused) } waiting := fixture.count(t, ` SELECT count(*) FROM invitations WHERE need_id = $1 AND state IN ('delivered', 'viewed', 'counter')`, need.NeedID) if waiting != 20 { t.Fatalf("waiting invitations under the need = %d, want exactly the limit of 20", waiting) } if charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, fixture.organization.ID()); charges != 20 { t.Fatalf("quota charges = %d, want one per admitted send", charges) } // The refused draft is still a draft and carries no charge. refusedDraftState := fixture.count(t, ` SELECT count(*) FROM invitations WHERE need_id = $1 AND state = 'draft'`, need.NeedID) if refusedDraftState != 1 { t.Fatalf("drafts under the need = %d, want the refused draft only", refusedDraftState) } } func TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) defer cancel() fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) candidate := fixture.candidate(t, "limits-candidate-pause@example.test") firstNeed := fixture.need(t, "Declined need") secondNeed := fixture.need(t, "Another need") // The candidate receives and declines an invitation under the first need. first := fixture.draft(t, fixture.owner, candidate.ID, &firstNeed, nil) sent := fixture.send(t, fixture.owner, first) declinedAt := sent.DeliveredAt.Add(time.Hour) fixture.clock.Set(declinedAt) if _, err := fixture.service.DeclineMine(ctx, invitationusecase.DeclineCommand{ ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "decline-pause", ExpectedVersion: sent.Version, Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, }); err != nil { t.Fatalf("DeclineMine() error = %v", err) } // Another owner of the same organization sends under another need. next := fixture.draft(t, fixture.secondOwner, candidate.ID, &secondNeed, nil) fixture.clock.Set(declinedAt.Add(29 * 24 * time.Hour)) if _, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); !errors.Is(err, invitationusecase.ErrSendBlocked) { t.Fatalf("Send(day 29 after the decline) error = %v, want ErrSendBlocked", err) } if state := fixture.count(t, `SELECT count(*) FROM invitations WHERE id = $1 AND state = 'draft'`, next.ID); state != 1 { t.Fatal("a send refused by the pause changed the draft") } // The same draft goes out on day 30, with a new key. fixture.clock.Set(declinedAt.Add(30 * 24 * time.Hour)) if view, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); err != nil || view.State != domain.InvitationDelivered { t.Fatalf("Send(day 30 after the decline) = %v, %v; want delivered", view.State, err) } } func TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) defer cancel() fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) threeDays := int32(3) // Each round delivers a fresh invitation with a three-day deadline and lets // an acceptance at the deadline race the expiry job. for round := range 3 { candidate := fixture.candidate(t, fmt.Sprintf("limits-candidate-race-%d@example.test", round)) draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays) sent := fixture.send(t, fixture.owner, draft) deadline := *sent.ResponseDeadlineAt charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID) worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock) fixture.clock.Set(deadline) acceptCommand := invitationusecase.AcceptCommand{ ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-" + uuid.NewString(), ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01", Fields: []domain.ContactField{domain.ContactFieldEmail}, } var group sync.WaitGroup var acceptErr error var runErr error group.Go(func() { _, acceptErr = fixture.service.AcceptMine(ctx, acceptCommand) }) group.Go(func() { _, runErr = worker.RunDue(ctx) }) group.Wait() if runErr != nil { t.Fatalf("round %d: RunDue() error = %v", round, runErr) } if !errors.Is(acceptErr, invitationusecase.ErrAnswerBlocked) { t.Fatalf("round %d: AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", round, acceptErr) } assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges) if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 { t.Fatalf("round %d: %d contact grants after a late acceptance, want none", round, grants) } if consents := fixture.count(t, `SELECT count(*) FROM consent_records WHERE invitation_id = $1 AND purpose = 'c4'`, sent.ID); consents != 0 { t.Fatalf("round %d: %d consent C4 records after a late acceptance, want none", round, consents) } var jobStatus string var jobError *string if err := fixture.pool.QueryRow(ctx, `SELECT status, last_error_class FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`, invitationExpiryJobKind, sent.ID.String()).Scan(&jobStatus, &jobError); err != nil { t.Fatalf("round %d: read the deadline job: %v", round, err) } if jobStatus != "done" { t.Fatalf("round %d: the deadline job is %s with error %v, want done", round, jobStatus, jobError) } } } func TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) defer cancel() fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) threeDays := int32(3) candidate := fixture.candidate(t, "limits-candidate-job-first@example.test") draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays) sent := fixture.send(t, fixture.owner, draft) deadline := *sent.ResponseDeadlineAt charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID) // The job runs first at its due time and expires the invitation. fixture.clock.Set(deadline) worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock) if _, err := worker.RunDue(ctx); err != nil { t.Fatalf("RunDue() error = %v", err) } assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges) // The acceptance that arrives afterwards finds the expiry and grants nothing. _, err := fixture.service.AcceptMine(ctx, invitationusecase.AcceptCommand{ ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-after-job", ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01", Fields: []domain.ContactField{domain.ContactFieldEmail}, }) if !errors.Is(err, invitationusecase.ErrAnswerBlocked) { t.Fatalf("AcceptMine(after the job) error = %v, want ErrAnswerBlocked", err) } if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 { t.Fatalf("contact grants = %d after the job won, want none", grants) } if events := fixture.count(t, `SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'expired'`, sent.ID); events != 1 { t.Fatalf("expiry events = %d, want one", events) } } // newDeadlineJobWorker builds the scheduled job worker with the response // deadline handler, against the store of the isolated test database and the // fixture clock, as the application does. func newDeadlineJobWorker(ctx context.Context, t *testing.T, databaseURL string, clock *testClock) *jobrunner.Worker { t.Helper() pool := newPoolFor(ctx, t, databaseURL) settings := jobrunner.Settings{ BatchSize: 10, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3, Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second, } worker, err := jobrunner.New( []inbound.JobHandler{invitationusecase.NewResponseDeadlineJob(clock.Now)}, postgresadapter.NewScheduledJobStore(pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, clock.Now, ) if err != nil { t.Fatalf("jobrunner.New() error = %v", err) } return worker } // assertExpiredAtDeadline checks the stored state of an expired invitation: the // deadline and terms are kept, the timeout reason is set, the audit event has // no actor, and the quota charge is unchanged. func assertExpiredAtDeadline(t *testing.T, fixture invitationLimitsFixture, invitationID uuid.UUID, deadline time.Time, charges int64) { t.Helper() var state, reason string var storedDeadline time.Time if err := fixture.pool.QueryRow(fixture.ctx, ` SELECT state, expiry_reason, response_deadline_at FROM invitations WHERE id = $1`, invitationID).Scan(&state, &reason, &storedDeadline); err != nil { t.Fatalf("read invitation: %v", err) } if state != string(domain.InvitationExpired) || reason != string(domain.InvitationExpiryTimeout) || !storedDeadline.Equal(deadline) { t.Fatalf("invitation = %s/%s deadline %v, want expired by the timeout at %v", state, reason, storedDeadline, deadline) } events := fixture.count(t, ` SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'expired' AND actor_id IS NULL AND cardinality(changed_fields) = 0`, invitationID) if events != 1 { t.Fatalf("expiry events without an actor = %d, want one", events) } if stored := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, invitationID); stored != charges { t.Fatalf("quota charges of the invitation = %d, want the %d of the send", stored, charges) } } func TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) migrator := newMigrator(t, databaseURL) if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion-1) // A delivery made before the migration has no deadline job yet. draft := fixture.draft(t) delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) if err != nil { t.Fatalf("Deliver() error = %v", err) } event, err := delivered.DeliveryEvent(fixture.owner.ID) if err != nil { t.Fatalf("DeliveryEvent() error = %v", err) } if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) }); err != nil { t.Fatalf("Deliver() through the repository error = %v", err) } deadline := *delivered.Snapshot().ResponseDeadlineAt if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up(43) error = %v", err) } var jobs int var dueAt time.Time if err := pool.QueryRow(ctx, ` SELECT count(*), coalesce(max(due_at), now()) FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2 AND status = 'pending'`, invitationExpiryJobKind, delivered.ID().String()).Scan(&jobs, &dueAt); err != nil { t.Fatalf("read the backfilled job: %v", err) } if jobs != 1 || !dueAt.Equal(deadline) { t.Fatalf("backfilled jobs = %d due %v, want one due at the deadline %v", jobs, dueAt, deadline) } // The trigger refuses an expiry that is recorded before the deadline, and // an expiry of an invitation that is not waiting for an answer. if _, err := pool.Exec(ctx, ` UPDATE invitations SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2 WHERE id = $1`, delivered.ID(), deadline.Add(-time.Second)); err == nil { t.Fatal("an expiry before the deadline was stored") } if _, err := pool.Exec(ctx, ` UPDATE invitations SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2 WHERE id = $1`, delivered.ID(), deadline); err != nil { t.Fatalf("expiry at the deadline error = %v", err) } // A rollback keeps the expiry, which the previous schema cannot represent. if _, err := migrator.DownOne(ctx); err == nil { t.Fatal("rollback with an expired invitation succeeded, want it refused") } var expired int if err := pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE state = 'expired'`).Scan(&expired); err != nil || expired != 1 { t.Fatalf("expired invitations after the refused rollback = %d, %v; want the stored expiry", expired, err) } }