From b3ba0b2632d38b81937df0618b5143a92c407ac7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 23:38:24 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E5=87=8F=E5=B0=91=E5=88=A9=E6=B6=A6?= =?UTF-8?q?=E6=8A=A5=E8=A1=A8=E6=8C=89=E7=94=A8=E9=87=8F=E9=80=90=E7=AC=94?= =?UTF-8?q?=E6=89=AB=E6=8F=8F=E6=B8=A0=E9=81=93=E5=8E=86=E5=8F=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/repository/profit_operations.go | 15 +++++++++++-- ...provider_profit_report_integration_test.go | 21 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/backend/internal/repository/profit_operations.go b/backend/internal/repository/profit_operations.go index b7d4943f670a..dbf51443f4c8 100644 --- a/backend/internal/repository/profit_operations.go +++ b/backend/internal/repository/profit_operations.go @@ -208,9 +208,20 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS u.total_cost AS cost_base FROM usage_logs u LEFT JOIN accounts_config c ON c.id=u.account_id LEFT JOIN provider_profit_charges e ON e.usage_log_id=u.id AND e.account_id=u.account_id AND e.local_created_at=u.created_at - LEFT JOIN LATERAL provider_profit_account_at(u.account_id,u.created_at) h ON true + -- Resolve only channel and assignment here. Joining the timelines directly + -- allows PostgreSQL to hash them once for the report window. A manual unlink + -- suppresses imported history but can still fall back to the current URL below. + LEFT JOIN provider_profit_manual_history manual ON manual.account_id=u.account_id + AND manual.effective_from<=u.created_at AND (manual.effective_until IS NULL OR u.created_atu.created_at) CROSS JOIN LATERAL (SELECT COALESCE(e.channel_id,h.channel_id,legacy.channel_id, CASE WHEN COALESCE(h.assignment,'') IN ('','manual_unlinked') AND c.url_key='unknown:oauth_dynamic_endpoint' THEN c.oauth_channel_id diff --git a/backend/internal/repository/provider_profit_report_integration_test.go b/backend/internal/repository/provider_profit_report_integration_test.go index aece571f0315..bbd5323b84fe 100644 --- a/backend/internal/repository/provider_profit_report_integration_test.go +++ b/backend/internal/repository/provider_profit_report_integration_test.go @@ -442,6 +442,27 @@ func TestProviderProfitUniqueSiteClaimsAfterUnlinkAndOAuthUsesBinding(t *testing require.Contains(t, rows, site+"/v1", "two providers sharing a site key must not auto-merge the unlinked URL") } +func TestProviderProfitReportHistoricalOwnerAtManualBoundaries(t *testing.T) { + f := newProfitChargeFixture(t) + override := f.id(`INSERT INTO upstream_channels(name,code) VALUES('Manual override','manual-boundary') RETURNING id`) + start := f.now() + end := start.Add(time.Second) + f.exec(`INSERT INTO provider_profit_manual_history(account_id,channel_id,revision,effective_from,effective_until) + VALUES($1,$2,1,$3,$4)`, f.account, override, start, end) + before := start.Add(-time.Microsecond) + f.usageWithIncome(f.account, nil, before, 1) + f.usageWithIncome(f.account, nil, start, 2) + f.usageWithIncome(f.account, nil, end, 4) + + w := service.ProviderProfitWindow{From: before, Until: end.Add(time.Microsecond)} + imported := f.report(f.channel, w) + require.Equal(t, "2", string(imported["requests"])) + require.JSONEq(t, "5", string(imported["request_income"])) + manual := f.report(override, w) + require.Equal(t, "1", string(manual["requests"])) + require.JSONEq(t, "2", string(manual["request_income"])) +} + func TestProviderProfitLegacyIncomeUnchangedByFirstLink(t *testing.T) { f := newProfitChargeFixture(t) channel := f.id(`INSERT INTO upstream_channels(name,code) VALUES('Legacy channel','legacy-fixture') RETURNING id`) From f070119ce18e9638f1ca24ba024dc2c8dbcc028e Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 20 Nov 2026 00:00:38 +0800 Subject: [PATCH 2/2] fix: preserve historical profit report join semantics --- .../internal/repository/profit_operations.go | 15 +- ...provider_profit_report_integration_test.go | 134 ++++++++++++++++++ 2 files changed, 145 insertions(+), 4 deletions(-) diff --git a/backend/internal/repository/profit_operations.go b/backend/internal/repository/profit_operations.go index dbf51443f4c8..65d6124b0fd1 100644 --- a/backend/internal/repository/profit_operations.go +++ b/backend/internal/repository/profit_operations.go @@ -211,17 +211,24 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS -- Resolve only channel and assignment here. Joining the timelines directly -- allows PostgreSQL to hash them once for the report window. A manual unlink -- suppresses imported history but can still fall back to the current URL below. + -- Preserve the ownership lookup's multiplicity: manual rows retain all source + -- and channel matches; imported rows retain only matching source/channel pairs. LEFT JOIN provider_profit_manual_history manual ON manual.account_id=u.account_id AND manual.effective_from<=u.created_at AND (manual.effective_until IS NULL OR u.created_atu.created_at) CROSS JOIN LATERAL (SELECT COALESCE(e.channel_id,h.channel_id,legacy.channel_id, CASE WHEN COALESCE(h.assignment,'') IN ('','manual_unlinked') AND c.url_key='unknown:oauth_dynamic_endpoint' THEN c.oauth_channel_id diff --git a/backend/internal/repository/provider_profit_report_integration_test.go b/backend/internal/repository/provider_profit_report_integration_test.go index bbd5323b84fe..19aba8d9871a 100644 --- a/backend/internal/repository/provider_profit_report_integration_test.go +++ b/backend/internal/repository/provider_profit_report_integration_test.go @@ -463,6 +463,140 @@ func TestProviderProfitReportHistoricalOwnerAtManualBoundaries(t *testing.T) { require.JSONEq(t, "2", string(manual["request_income"])) } +func TestProviderProfitReportPreservesHistoricalJoinMultiplicity(t *testing.T) { + // These are schema-permitted closed histories, not a reproduction through + // normal APIs. In particular, two identityless sources must not duplicate an + // unowned tenant-URL request. Other cases retain the old query's multiplicity. + for _, tc := range []struct { + name string + siteURL bool + sources string + manual string + extraChannel bool + ownershipRows int64 + requests int64 + assignment string + }{ + {"identityless_tenant", false, "identityless", "", false, 0, 1, "unbound_url"}, + {"identityless_site", true, "identityless", "", false, 0, 2, "provider_url"}, + {"mixed_tenant", false, "mixed", "", false, 1, 1, "provider_import"}, + {"verified_site", true, "verified", "", false, 2, 4, "provider_import"}, + {"verified_channel_overlap", false, "verified", "", true, 4, 4, "provider_import"}, + {"explicit_tenant", false, "identityless", "explicit", false, 2, 2, "explicit"}, + {"explicit_site_channel_overlap", true, "identityless", "explicit", true, 4, 8, "explicit"}, + {"unlink_tenant", false, "identityless", "unlink", false, 2, 2, "manual_unlinked"}, + {"unlink_site", true, "identityless", "unlink", false, 2, 4, "provider_url"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newProfitChargeFixture(t) + base := profitChargeBase + "/tenant/v1" + if tc.siteURL { + base = profitChargeBase + "/v1" + } + account := f.id(`INSERT INTO accounts(name,type,platform,credentials,extra) + VALUES('historical join fixture','apikey','openai',jsonb_build_object('base_url',$1::text,'api_key','fixture-only'),'{"cost_multiplier":0.5}') RETURNING id`, base) + until := f.now() + at := until.Add(-time.Microsecond) + for i := range 2 { + var identity any + if tc.sources == "verified" || (tc.sources == "mixed" && i == 0) { + identity = f.epoch + } else if tc.sources == "mixed" { + identity = f.epoch.Add(-time.Hour) // A non-NULL, unmatched epoch is also filtered. + } + f.exec(`INSERT INTO provider_profit_account_source_history(account_id,provider_id,key_id,origin_hash,identity_from,effective_from,effective_until) + VALUES($1,$2,'11',provider_profit_origin($3),$4,$5,$6)`, account, f.pid, profitChargeBase, identity, at, until) + } + if tc.manual != "" { + var channel any + if tc.manual == "explicit" { + channel = f.channel + } + f.exec(`INSERT INTO provider_profit_manual_history(account_id,channel_id,revision,effective_from,effective_until) + VALUES($1,$2,1,$3,$4)`, account, channel, at, until) + } + if tc.extraChannel { + f.exec(`INSERT INTO provider_profit_channel_history(provider_id,channel_id,revision,identity_from,effective_from,effective_until) + VALUES($1,$2,1000,$3,$4,$5)`, f.pid, f.channel, f.epoch, at, until) + } + f.usageWithIncome(account, nil, at, 7) + require.Equal(t, tc.ownershipRows, f.id(`SELECT count(*) FROM provider_profit_account_at($1,$2)`, account, at)) + // The unchanged ownership function plus its independent URL-source + // join is the pre-PR reference. Explicit counts keep the oracle honest. + require.Equal(t, tc.requests, f.id(`SELECT count(*) FROM (SELECT 1) anchor + LEFT JOIN LATERAL provider_profit_account_at($1,$2) own ON true + LEFT JOIN provider_profit_account_source_history src ON $3::boolean AND src.account_id=$1 + AND src.effective_from<=$2 AND (src.effective_until IS NULL OR $2