Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
7781746
fix(bankingcircle): EN-1095 keep same-second payments at the watermar…
Jun 26, 2026
c2a7f23
fix(generic): EN-1095 keep same-timestamp rows at the watermark (M-CON2)
Jun 26, 2026
9b2265f
fix(moneycorp): EN-1095 keep same-timestamp rows at the watermark (M-…
Jun 26, 2026
d6589af
fix(modulr): EN-1095 keep same-timestamp accounts at the watermark (M…
Jun 26, 2026
1a7ebf7
fix(currencycloud): EN-1095 keep same-timestamp rows + stop mid-pagin…
Jun 26, 2026
6bd869f
fix(mangopay): EN-1095 stop dropping same-second payments at the wate…
Jun 26, 2026
c398c9b
fix(generic): EN-1095 add page cursor so same-second groups > PageSiz…
Jun 29, 2026
e5f48fb
fix(moneycorp): EN-1095 add page cursor so same-second groups > PageS…
Jun 29, 2026
6a84435
fix(modulr): EN-1095 add page cursor so same-second groups > PageSize…
Jun 29, 2026
a878a5c
fix(currencycloud): EN-1095 add page cursor so same-second groups > P…
Jun 29, 2026
8b3fac7
fix(bankingcircle): EN-1095 track processed-ID set so same-second gro…
Jun 29, 2026
f28eceb
fix(mangopay): EN-1095 track processed-ID set instead of a drifting p…
Jun 29, 2026
a06c7e1
fix(connectors): EN-1095 don't advance page cursor past a drained sam…
Jun 29, 2026
193ea70
fix(connectors): EN-1095 track processed-ID set per watermark second,…
Jun 29, 2026
a4c6a55
fix(connectors): EN-1095 keep monotonic page cursor on unfiltered sca…
Jun 29, 2026
91b9c67
docs(connectors): EN-1095 clarify watermark dedup is exact-timestamp,…
Jun 29, 2026
f682e5d
test(currencycloud): EN-1095 close pagination-fixture gap dropping a …
Jul 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions ce/plugins/bankingcircle/payments.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bankingcircle
import (
"context"
"encoding/json"
"slices"
"time"

"github.com/formancehq/go-libs/v5/pkg/types/currency"
Expand All @@ -13,6 +14,15 @@ import (

type paymentsState struct {
LatestStatusChangedTimestamp time.Time `json:"latestStatusChangedTimestamp"`
// LatestProcessedIDs holds the PaymentIDs of ALL payments already emitted at
// exactly LatestStatusChangedTimestamp, accumulated across cycles while the
// watermark second is unchanged and reset when it advances. BankingCircle has
// no server-side time filter (we rescan the list from page 1 and filter
// client-side), so a single boundary ID is not enough: a same-second group
Comment thread
fguery marked this conversation as resolved.
Resolved
// larger than PageSize would re-emit earlier siblings and oscillate, never
// reaching later rows. Tracking the whole set lets the inclusive (>=) filter
// skip every already-emitted sibling so the scan reaches new rows.
LatestProcessedIDs []string `json:"latestProcessedIDs"`
}

func (p *Plugin) fetchNextPayments(ctx context.Context, req models.FetchNextPaymentsRequest) (models.FetchNextPaymentsResponse, error) {
Expand All @@ -25,6 +35,7 @@ func (p *Plugin) fetchNextPayments(ctx context.Context, req models.FetchNextPaym

newState := paymentsState{
LatestStatusChangedTimestamp: oldState.LatestStatusChangedTimestamp,
LatestProcessedIDs: oldState.LatestProcessedIDs,
}

var payments []models.PSPPayment
Expand All @@ -49,11 +60,33 @@ func (p *Plugin) fetchNextPayments(ctx context.Context, req models.FetchNextPaym
}

if !needMore {
// Trim both slices in lockstep so the watermark and LatestProcessedID are
// taken from the last *emitted* payment. Trimming only payments would set
// the watermark from a fetched-but-dropped payment and silently skip the
// trimmed ones on the next call.
payments = payments[:req.PageSize]
latestStatusChangedTimestamps = latestStatusChangedTimestamps[:req.PageSize]
}

if len(payments) > 0 {
newState.LatestStatusChangedTimestamp = latestStatusChangedTimestamps[len(latestStatusChangedTimestamps)-1]
lastTimestamp := latestStatusChangedTimestamps[len(latestStatusChangedTimestamps)-1]

// Collect the references emitted at exactly the new watermark second.
idsAtWatermark := make([]string, 0)
for i, ts := range latestStatusChangedTimestamps {
if ts.Equal(lastTimestamp) {
idsAtWatermark = append(idsAtWatermark, payments[i].Reference)
}
}

// Accumulate the processed-ID set while still inside the same watermark
// second; reset it when the watermark advances to a newer second.
if lastTimestamp.Equal(oldState.LatestStatusChangedTimestamp) {
newState.LatestProcessedIDs = append(oldState.LatestProcessedIDs, idsAtWatermark...)
} else {
newState.LatestProcessedIDs = idsAtWatermark
}
newState.LatestStatusChangedTimestamp = lastTimestamp
}

payload, err := json.Marshal(newState)
Expand All @@ -75,10 +108,13 @@ func fillPayments(
oldState paymentsState,
) ([]models.PSPPayment, []time.Time, error) {
for _, payment := range pagedPayments {
switch payment.LatestStatusChangedTimestamp.Compare(oldState.LatestStatusChangedTimestamp) {
case -1, 0:
// Inclusive watermark: skip payments strictly before the watermark, and
// the single already-processed payment at exactly the watermark. Distinct
// payments sharing that timestamp are kept (M-CON2: equal-timestamp rows
// were previously dropped at page/cycle boundaries).
cmp := payment.LatestStatusChangedTimestamp.Compare(oldState.LatestStatusChangedTimestamp)
if cmp < 0 || (cmp == 0 && slices.Contains(oldState.LatestProcessedIDs, payment.PaymentID)) {
continue
default:
}

p, err := translatePayment(payment)
Expand Down
114 changes: 113 additions & 1 deletion ce/plugins/bankingcircle/payments_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bankingcircle

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -155,7 +156,11 @@ var _ = Describe("BankingCircle Plugin Payments", func() {

It("should fetch next payments - with state pageSize < total payments", func(ctx SpecContext) {
req := models.FetchNextPaymentsRequest{
State: []byte(fmt.Sprintf(`{"latestStatusChangedTimestamp": "%s"}`, samplePayments[38].LatestStatusChangedTimestamp.UTC().Format(time.RFC3339Nano))),
State: []byte(fmt.Sprintf(
`{"latestStatusChangedTimestamp": "%s", "latestProcessedIDs": ["%s"]}`,
samplePayments[38].LatestStatusChangedTimestamp.UTC().Format(time.RFC3339Nano),
samplePayments[38].PaymentID,
)),
PageSize: 40,
}

Expand All @@ -180,6 +185,113 @@ var _ = Describe("BankingCircle Plugin Payments", func() {
Expect(err).To(BeNil())
// We fetched everything, state should be resetted
Expect(state.LatestStatusChangedTimestamp.UTC()).To(Equal(samplePayments[49].LatestStatusChangedTimestamp.UTC()))
Expect(state.LatestProcessedIDs).To(ConsistOf(samplePayments[49].PaymentID))
})

It("keeps distinct payments that share the watermark timestamp (M-CON2)", func(ctx SpecContext) {
ts := now.Add(-time.Hour).UTC()
sameSecond := make([]client.Payment, 0, 3)
for _, id := range []string{"a", "b", "c"} {
sameSecond = append(sameSecond, client.Payment{
PaymentID: id,
Status: "Processed",
ProcessedTimestamp: ts,
LatestStatusChangedTimestamp: ts,
DebtorInformation: client.DebtorInformation{AccountID: "123"},
Transfer: client.Transfer{Amount: client.Amount{Currency: "EUR", Amount: "120"}},
})
}

// Watermark sits exactly on the shared timestamp, with "a" already processed.
req := models.FetchNextPaymentsRequest{
State: []byte(fmt.Sprintf(
`{"latestStatusChangedTimestamp": "%s", "latestProcessedIDs": ["a"]}`,
ts.Format(time.RFC3339Nano),
)),
PageSize: 40,
}

m.EXPECT().GetPayments(gomock.Any(), 1, 40).Return(sameSecond, nil)

resp, err := plg.FetchNextPayments(ctx, req)
Expect(err).To(BeNil())
// "a" is the already-processed boundary row; "b" and "c" share its
// timestamp and must NOT be dropped.
Expect(resp.Payments).To(HaveLen(2))
refs := []string{resp.Payments[0].Reference, resp.Payments[1].Reference}
Expect(refs).To(ConsistOf("b", "c"))
})

It("re-emits the boundary payment once when migrating state without latestProcessedID", func(ctx SpecContext) {
// Old-format state: watermark only, no latestProcessedID. The row at
// exactly the watermark is re-emitted once (idempotent via upsert);
// no recrawl.
req := models.FetchNextPaymentsRequest{
State: []byte(fmt.Sprintf(`{"latestStatusChangedTimestamp": "%s"}`, samplePayments[38].LatestStatusChangedTimestamp.UTC().Format(time.RFC3339Nano))),
PageSize: 40,
}

m.EXPECT().GetPayments(gomock.Any(), 1, 40).Return(samplePayments[:40], nil)
m.EXPECT().GetPayments(gomock.Any(), 2, 40).Return(samplePayments[40:], nil)

resp, err := plg.FetchNextPayments(ctx, req)
Expect(err).To(BeNil())
// Indices 38..49: the boundary (38) re-emitted plus 39..49.
Expect(resp.Payments).To(HaveLen(12))
Expect(resp.Payments[0].Reference).To(Equal(samplePayments[38].PaymentID))
})

It("walks a same-second group larger than PageSize across cycles without stalling", func(ctx SpecContext) {
ts := now.Add(-time.Hour).UTC()
mk := func(id string) client.Payment {
return client.Payment{
PaymentID: id,
Status: "Processed",
ProcessedTimestamp: ts,
LatestStatusChangedTimestamp: ts,
DebtorInformation: client.DebtorInformation{AccountID: "123"},
Transfer: client.Transfer{Amount: client.Amount{Currency: "EUR", Amount: "120"}},
}
}
all := []client.Payment{mk("p0"), mk("p1"), mk("p2"), mk("p3"), mk("p4")}
// BankingCircle has no server filter: it rescans from page 1 each cycle.
// Serve the full list page by page so the processed-ID set has to skip
// already-emitted siblings to make progress.
m.EXPECT().GetPayments(gomock.Any(), gomock.Any(), 2).DoAndReturn(
func(_ context.Context, page, _ int) ([]client.Payment, error) {
start := (page - 1) * 2
if start >= len(all) {
return []client.Payment{}, nil
}
end := start + 2
if end > len(all) {
end = len(all)
}
return all[start:end], nil
},
).AnyTimes()
refs := func(ps []models.PSPPayment) []string {
out := make([]string, len(ps))
for i := range ps {
out[i] = ps[i].Reference
}
return out
}

// Cycle 1: page 1 -> p0, p1.
resp, err := plg.FetchNextPayments(ctx, models.FetchNextPaymentsRequest{State: []byte(`{}`), PageSize: 2})
Expect(err).To(BeNil())
Expect(refs(resp.Payments)).To(Equal([]string{"p0", "p1"}))

// Cycle 2: rescan skips p0,p1 (in set), page 2 -> p2, p3.
resp, err = plg.FetchNextPayments(ctx, models.FetchNextPaymentsRequest{State: resp.NewState, PageSize: 2})
Expect(err).To(BeNil())
Expect(refs(resp.Payments)).To(ConsistOf("p2", "p3"))

// Cycle 3: page 3 -> p4 (group fully drained, no stall).
resp, err = plg.FetchNextPayments(ctx, models.FetchNextPaymentsRequest{State: resp.NewState, PageSize: 2})
Expect(err).To(BeNil())
Expect(refs(resp.Payments)).To(ContainElement("p4"))
})
})
})
61 changes: 51 additions & 10 deletions ce/plugins/currencycloud/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,33 @@ package currencycloud
import (
"context"
"encoding/json"
"slices"
"time"

"github.com/formancehq/payments/ce/plugins/currencycloud/client"
"github.com/formancehq/payments/pkg/domain/models"
)

type accountsState struct {
// LastPage is a monotonic forward cursor. This endpoint has NO server-side
// time filter, so resuming the scan here (re-reading only the last page, not
// the whole history each poll) avoids a full historical rescan on every sync.
LastPage int `json:"lastPage"`
LastCreatedAt time.Time `json:"lastCreatedAt"`
// LastProcessedIDs holds the references of ALL accounts already emitted at
// exactly LastCreatedAt, accumulated while the watermark second is unchanged
// and reset when it advances. It dedups same-second rows on the re-read page,
// so a multi-row boundary settles to empty instead of oscillating (a single
// LastProcessedID could exclude only one of several tied rows).
//
// Migration: the old singular lastProcessedID is ignored; the watermark second
// is re-emitted once after deploy (idempotent via storage upserts), no recrawl.
//
// Precision: comparison and the ID set use the exact timestamp the API
// returns (full precision, as in the qonto reference), not a truncated
// second; "same-second" above is shorthand because these PSPs report
// timestamps at second granularity, so equal values represent the same second.
LastProcessedIDs []string `json:"lastProcessedIDs"`
}

func (p *Plugin) fetchNextAccounts(ctx context.Context, req models.FetchNextAccountsRequest) (models.FetchNextAccountsResponse, error) {
Expand All @@ -27,12 +45,17 @@ func (p *Plugin) fetchNextAccounts(ctx context.Context, req models.FetchNextAcco
}

newState := accountsState{
LastPage: oldState.LastPage,
LastCreatedAt: oldState.LastCreatedAt,
LastPage: oldState.LastPage,
LastCreatedAt: oldState.LastCreatedAt,
LastProcessedIDs: oldState.LastProcessedIDs,
}

var accounts []models.PSPAccount
hasMore := false
// No server-side time filter: resume the monotonic forward scan at the
// persisted page (re-reading only the last page, not the whole history) and
// skip already-emitted same-second rows via the ID set, so a multi-row final
// page cannot oscillate. We do NOT trim back to PageSize.
page := oldState.LastPage
for {
pagedAccounts, nextPage, err := p.client.GetAccounts(ctx, page, req.PageSize)
Expand All @@ -50,17 +73,34 @@ func (p *Plugin) fetchNextAccounts(ctx context.Context, req models.FetchNextAcco
}

var needMore bool
needMore, hasMore, accounts = shouldFetchMore(accounts, nextPage, req.PageSize)
// Ignore shouldFetchMore's trimmed slice; keep the full over-fetch.
needMore, hasMore, _ = shouldFetchMore(accounts, nextPage, req.PageSize)
if !needMore {
break
}

page = nextPage
}

newState.LastPage = page

if len(accounts) > 0 {
newState.LastCreatedAt = accounts[len(accounts)-1].CreatedAt
last := accounts[len(accounts)-1].CreatedAt

// Collect the references emitted at exactly the new watermark second.
idsAtWatermark := make([]string, 0)
for i := range accounts {
if accounts[i].CreatedAt.Equal(last) {
idsAtWatermark = append(idsAtWatermark, accounts[i].Reference)
}
}

// Accumulate the processed-ID set while still inside the same watermark
// second; reset it when the watermark advances to a newer second.
if last.Equal(oldState.LastCreatedAt) {
newState.LastProcessedIDs = append(oldState.LastProcessedIDs, idsAtWatermark...)
} else {
newState.LastProcessedIDs = idsAtWatermark
}
newState.LastCreatedAt = last
}

payload, err := json.Marshal(newState)
Expand All @@ -81,11 +121,12 @@ func fillAccounts(
oldState accountsState,
) ([]models.PSPAccount, error) {
for _, account := range pagedAccounts {
switch account.CreatedAt.Compare(oldState.LastCreatedAt) {
case -1, 0:
// Account already ingested, skip
// Inclusive watermark: skip accounts strictly before it, and any
// already-emitted account at exactly the watermark second. Distinct
// accounts sharing that timestamp are kept (M-CON2).
cmp := account.CreatedAt.Compare(oldState.LastCreatedAt)
if cmp < 0 || (cmp == 0 && slices.Contains(oldState.LastProcessedIDs, account.ID)) {
continue
default:
}

raw, err := json.Marshal(account)
Expand Down
Loading
Loading