Open-source personal finance manager. Self-hosted, privacy-first.
fix: model institutions as first-class rows so SimpleFIN accounts show their own bank (#654)
Michael Verrilli318459b4de06
diff --git a/backend/alembic/versions/075_account_institution.py b/backend/alembic/versions/075_account_institution.pynew file mode 100644index 00000000..04f856e4--- /dev/null+++ b/backend/alembic/versions/075_account_institution.py@@ -0,0 +1,95 @@+"""model institutions as first-class rows under a connection (issue #345)++Revision ID: 075+Revises: 074+Create Date: 2026-08-21++One SimpleFIN connection can span multiple institutions, but Securo applied+the connection's single institution_name/logo_url to every account under it.+A connection now has institutions, and each account points at its own.++Additive and nullable: existing rows keep working unchanged (serialization+falls back to the connection) and institution rows appear on the next sync.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "075"+down_revision: Union[str, None] = "074"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "institutions",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "connection_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("bank_connections.id", ondelete="CASCADE"),+ nullable=False,+ ),+ # The provider's stable id for the org (SimpleFIN conn_id). Renames+ # update the matched row in place instead of minting a new one. Null+ # for servers that only send a name.+ sa.Column("external_id", sa.String(255), nullable=True),+ sa.Column("name", sa.String(255), nullable=False),+ sa.Column("logo_url", sa.String(500), nullable=True),+ )+ # Identity is the org id when the provider sends one, the name otherwise.+ # Split into two partial unique indexes so two same-named orgs (two logins+ # at one bank) stay distinct rows, while both paths keep two racing syncs+ # from double-inserting. Partial indexes can't serve a bare connection_id+ # lookup (the planner needs the predicate), so the eager-loaded+ # BankConnection.institutions gets a plain index of its own.+ op.create_index(+ "uq_institutions_connection_external_id",+ "institutions",+ ["connection_id", "external_id"],+ unique=True,+ postgresql_where=sa.text("external_id IS NOT NULL"),+ )+ op.create_index(+ "uq_institutions_connection_name",+ "institutions",+ ["connection_id", "name"],+ unique=True,+ postgresql_where=sa.text("external_id IS NULL"),+ )+ op.create_index("ix_institutions_connection_id", "institutions", ["connection_id"])+ op.add_column(+ "accounts",+ sa.Column(+ "institution_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("institutions.id", ondelete="SET NULL"),+ nullable=True,+ ),+ )+ # Indexed: the per-sync orphan reap anti-joins on it, and each reaped+ # row's ON DELETE SET NULL scans it too.+ op.create_index("ix_accounts_institution_id", "accounts", ["institution_id"])+ # Synced wallets are per investment account, so they carry the backing+ # institution for their "Synced from …" subtitle.+ op.add_column(+ "asset_groups",+ sa.Column(+ "institution_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("institutions.id", ondelete="SET NULL"),+ nullable=True,+ ),+ )+ op.create_index("ix_asset_groups_institution_id", "asset_groups", ["institution_id"])+++def downgrade() -> None:+ op.drop_index("ix_asset_groups_institution_id", table_name="asset_groups")+ op.drop_column("asset_groups", "institution_id")+ op.drop_index("ix_accounts_institution_id", table_name="accounts")+ op.drop_column("accounts", "institution_id")+ op.drop_table("institutions")diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex 9f115d06..a308ceee 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -165,7 +165,12 @@ async def update_account(raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not account:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")- return account_service.serialize_account(account, None, None)+ # Re-read post-commit so the response resolves the institution/display+ # name pair exactly like GET (update_account leaves the row expired).+ account = await account_service.get_account(session, account_id, ctx.workspace.id)+ if not account:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")+ return account_service.serialize_account(account, None, None, account.connection)@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 501df3a8..1d91e9d3 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -4,6 +4,7 @@ from app.models.workspace import Workspace, WorkspaceMemberfrom app.models.category import Categoryfrom app.models.category_group import CategoryGroupfrom app.models.bank_connection import BankConnection+from app.models.institution import Institutionfrom app.models.account import Accountfrom app.models.transaction import Transactionfrom app.models.rule import Rule@@ -38,6 +39,7 @@ __all__ = ["Category","CategoryGroup","BankConnection",+ "Institution","Account","Transaction","Rule",diff --git a/backend/app/models/account.py b/backend/app/models/account.pyindex 6f3f64ce..d407fd2f 100644--- a/backend/app/models/account.py+++ b/backend/app/models/account.py@@ -11,6 +11,7 @@ from app.core.database import Baseif TYPE_CHECKING:from app.models.bank_connection import BankConnection+ from app.models.institution import Institutionfrom app.models.transaction import Transaction@@ -40,8 +41,19 @@ class Account(Base):minimum_payment: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)card_brand: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)card_level: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ # The institution this account is actually at. One connection can span+ # several (SimpleFIN — issue #345); null falls back to the connection's+ # own institution_name/logo_url. Eager (selectin) because serialization+ # always reads it and lazy loads raise in async sessions.+ institution_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("institutions.id", ondelete="SET NULL"),+ nullable=True, index=True,+ )is_closed: Mapped[bool] = mapped_column(Boolean, default=False)closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)connection: Mapped[Optional["BankConnection"]] = relationship(back_populates="accounts")+ institution: Mapped[Optional["Institution"]] = relationship(+ back_populates="accounts", lazy="selectin"+ )transactions: Mapped[list["Transaction"]] = relationship(back_populates="account", cascade="all, delete-orphan")diff --git a/backend/app/models/asset_group.py b/backend/app/models/asset_group.pyindex 7cd54dee..ed2cbc34 100644--- a/backend/app/models/asset_group.py+++ b/backend/app/models/asset_group.py@@ -1,7 +1,7 @@import uuidfrom typing import TYPE_CHECKING, Optional-from sqlalchemy import ForeignKey, Integer, String+from sqlalchemy import ForeignKey, Index, Integer, String, textfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import Mapped, mapped_column, relationship@@ -9,6 +9,7 @@ from app.core.database import Baseif TYPE_CHECKING:from app.models.asset import Asset+ from app.models.institution import Institutionfrom app.models.user import User@@ -25,6 +26,19 @@ class AssetGroup(Base):"""__tablename__ = "asset_groups"+ # Mirrors migration 034 so the test schema enforces the same wallet-key+ # uniqueness the sync code's adoption guards rely on.+ __table_args__ = (+ Index(+ "ux_asset_groups_user_source_external",+ "user_id",+ "source",+ "external_id",+ unique=True,+ postgresql_where=text("external_id IS NOT NULL"),+ sqlite_where=text("external_id IS NOT NULL"),+ ),+ )id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))@@ -43,6 +57,14 @@ class AssetGroup(Base):UUID(as_uuid=True), ForeignKey("bank_connections.id", ondelete="SET NULL"), nullable=True)external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ # The institution backing a synced wallet (issue #345); null for manual+ # wallets. Renders the "Synced from …" subtitle without falling back to+ # the connection's first institution.+ institution_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("institutions.id", ondelete="SET NULL"),+ nullable=True, index=True,+ )user: Mapped["User"] = relationship()assets: Mapped[list["Asset"]] = relationship(back_populates="group")+ institution: Mapped[Optional["Institution"]] = relationship(lazy="selectin")diff --git a/backend/app/models/bank_connection.py b/backend/app/models/bank_connection.pyindex 866954f2..53c59ef0 100644--- a/backend/app/models/bank_connection.py+++ b/backend/app/models/bank_connection.py@@ -11,6 +11,7 @@ from app.core.database import Baseif TYPE_CHECKING:from app.models.user import Userfrom app.models.account import Account+ from app.models.institution import Institutionclass BankConnection(Base):@@ -37,3 +38,8 @@ class BankConnection(Base):user: Mapped["User"] = relationship(back_populates="bank_connections")accounts: Mapped[list["Account"]] = relationship(back_populates="connection", cascade="all, delete-orphan")+ # Institutions reached through this link (issue #345). Eager (selectin) so+ # the connections API can summarize them without async lazy loads.+ institutions: Mapped[list["Institution"]] = relationship(+ back_populates="connection", cascade="all, delete-orphan", lazy="selectin"+ )diff --git a/backend/app/models/institution.py b/backend/app/models/institution.pynew file mode 100644index 00000000..e561fcd7--- /dev/null+++ b/backend/app/models/institution.py@@ -0,0 +1,59 @@+import uuid+from typing import TYPE_CHECKING, Optional++from sqlalchemy import ForeignKey, Index, String, text+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.account import Account+ from app.models.bank_connection import BankConnection+++class Institution(Base):+ """One financial institution reached through a bank connection.++ Most providers are one institution per connection, but a single SimpleFIN+ Setup Token can span several (bank + brokerages — issue #345), so org+ identity lives here rather than on the connection.+ """++ __tablename__ = "institutions"+ # Identity is the org id when the provider sends one, the name otherwise.+ # Two partial unique indexes so two same-named orgs (two logins at one+ # bank) stay distinct rows, while both paths keep two racing syncs from+ # double-inserting. Partial indexes can't serve a bare connection_id+ # lookup, so the eager-loaded relationship indexes the FK itself.+ __table_args__ = (+ Index(+ "uq_institutions_connection_external_id",+ "connection_id",+ "external_id",+ unique=True,+ postgresql_where=text("external_id IS NOT NULL"),+ sqlite_where=text("external_id IS NOT NULL"),+ ),+ Index(+ "uq_institutions_connection_name",+ "connection_id",+ "name",+ unique=True,+ postgresql_where=text("external_id IS NULL"),+ sqlite_where=text("external_id IS NULL"),+ ),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ connection_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("bank_connections.id", ondelete="CASCADE"), index=True+ )+ # The provider's stable id for the org (SimpleFIN conn_id). Renames update+ # the matched row in place instead of minting a new one (review on #654).+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ name: Mapped[str] = mapped_column(String(255))+ logo_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)++ connection: Mapped["BankConnection"] = relationship(back_populates="institutions")+ accounts: Mapped[list["Account"]] = relationship(back_populates="institution")diff --git a/backend/app/providers/base.py b/backend/app/providers/base.pyindex 0d68a1fe..54bad0f8 100644--- a/backend/app/providers/base.py+++ b/backend/app/providers/base.py@@ -70,6 +70,13 @@ class AccountData:# provider exposes one. Disambiguates accounts a bank reports under an# identical name (issue #408). Never the full identifier — see mask_last4.masked_number: Optional[str] = None+ # Per-account institution override (SimpleFIN — issue #345). None = same+ # as connection. The external id is the provider's stable org id+ # (SimpleFIN conn_id) so a renamed bank updates its row instead of+ # minting a new one; name-only hints fall back to name identity.+ institution_external_id: Optional[str] = None+ institution_name: Optional[str] = None+ institution_logo_url: Optional[str] = None@dataclass@@ -158,6 +165,12 @@ class HoldingData:maturity_date: Optional[date] = Noneis_withdrawn: bool = False # provider signaled the position was sold/transferredmetadata: Optional[dict] = None+ # Owning-account hint (SimpleFIN — issue #345): holdings are reported per+ # account, so each investment account gets its own wallet ("401(k)" apart+ # from "Rollover IRA"). None = the connection-default wallet, for+ # providers whose holdings aren't attributable to an account.+ account_external_id: Optional[str] = None+ account_name: Optional[str] = None@dataclassdiff --git a/backend/app/providers/simplefin.py b/backend/app/providers/simplefin.pyindex 9fa11671..0bb51efb 100644--- a/backend/app/providers/simplefin.py+++ b/backend/app/providers/simplefin.py@@ -360,12 +360,57 @@ class SimpleFinProvider(BankProvider):# ----- account / transaction reads --------------------------------------+ @staticmethod+ def _institutions_by_conn_id(payload: dict) -> dict[str, tuple[str, Optional[str]]]:+ """conn_id → (institution name, favicon logo URL) from connections[].++ One Setup Token can span several institutions; connections[] has one+ entry per institution, matched to accounts by conn_id (issue #345).+ """+ by_conn_id: dict[str, tuple[str, Optional[str]]] = {}+ for conn in payload.get("connections") or []:+ conn_id = conn.get("conn_id")+ name = conn.get("name")+ if not conn_id or not name:+ continue+ url = conn.get("org_url") or conn.get("url") or conn.get("sfin_url")+ by_conn_id[str(conn_id)] = (name, favicon_url_for(url) if url else None)+ return by_conn_id++ @staticmethod+ def _account_institution_hint(+ raw_acc: dict, by_conn_id: dict[str, tuple[str, Optional[str]]]+ ) -> tuple[Optional[str], Optional[str], Optional[str]]:+ """(external_id, name, logo) of the institution owning one account.++ The Bridge puts institutions in a top-level connections[] matched by+ conn_id; spec-style servers attach an ``org`` object to each account+ instead — same fallback _org_website already does. All-None when the+ payload carries neither.+ """+ conn_id = raw_acc.get("conn_id")+ if conn_id and str(conn_id) in by_conn_id:+ name, logo = by_conn_id[str(conn_id)]+ return str(conn_id), name, logo+ org = raw_acc.get("org") or {}+ name = org.get("name") or org.get("domain")+ if not name:+ return None, None, None+ url = org.get("url") or org.get("domain") or org.get("sfin-url")+ ext = org.get("id") or org.get("domain")+ return (+ str(ext) if ext else None,+ name,+ favicon_url_for(url) if url else None,+ )+@staticmethoddef _parse_accounts(payload: dict) -> tuple[str, list[AccountData]]:connections = payload.get("connections") or []institution_name = (connections[0].get("name") if connections else "SimpleFIN Connection")+ by_conn_id = SimpleFinProvider._institutions_by_conn_id(payload)accounts: list[AccountData] = []for raw in payload.get("accounts") or []:balance = _to_decimal(raw.get("balance")) or Decimal("0")@@ -374,6 +419,10 @@ class SimpleFinProvider(BankProvider):if not account_id:continuename = raw.get("name") or "Account"+ inst_ext, inst_name, inst_logo = SimpleFinProvider._account_institution_hint(+ raw, by_conn_id+ )+accounts.append(AccountData(external_id=account_id,@@ -381,6 +430,9 @@ class SimpleFinProvider(BankProvider):type="checking", # SimpleFIN doesn't expose an account typebalance=balance,currency=currency,+ institution_external_id=inst_ext,+ institution_name=inst_name,+ institution_logo_url=inst_logo,))return institution_name or "SimpleFIN Connection", accounts@@ -476,6 +528,8 @@ class SimpleFinProvider(BankProvider):holdings: list[HoldingData] = []for raw_acc in payload.get("accounts") or []:acc_currency = raw_acc.get("currency") or "USD"+ acc_id = str(raw_acc.get("id") or "") or None+ acc_name = raw_acc.get("name")for raw in raw_acc.get("holdings") or []:holding_id = str(raw.get("id") or "")if not holding_id:@@ -503,6 +557,8 @@ class SimpleFinProvider(BankProvider):if raw.get("cost_basis") is not Noneelse None,},+ account_external_id=acc_id,+ account_name=acc_name,))return holdingsdiff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex ae582413..f0eec9d7 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -50,9 +50,9 @@ class AccountRead(AccountBase):# Last 4 chars of the bank's identifier, when the provider exposes one.# Read-only: absent from AccountUpdate because sync owns it.masked_number: Optional[str] = None- # Denormalized from the linked BankConnection so every surface that shows- # an account (transactions list, accounts page, dashboard) can render the- # bank identity without a separate join. Null for manual accounts.+ # The account's own institution (issue #345), falling back to the linked+ # BankConnection's when the provider doesn't distinguish. Null for manual+ # accounts.institution_name: Optional[str] = Noneinstitution_logo_url: Optional[str] = Nonecurrent_balance: float = 0.0diff --git a/backend/app/schemas/bank_connection.py b/backend/app/schemas/bank_connection.pyindex d081c3fa..4517ad9e 100644--- a/backend/app/schemas/bank_connection.py+++ b/backend/app/schemas/bank_connection.py@@ -10,6 +10,17 @@ class BankConnectionBase(BaseModel):institution_name: str+class ConnectionInstitutionRead(BaseModel):+ """One institution reached through a connection (issue #345). Distinct+ from InstitutionRead below, which is a provider's connectable-bank+ catalog entry, not a linked institution."""++ name: str+ logo_url: Optional[str] = None++ model_config = ConfigDict(from_attributes=True)++class BankConnectionRead(BankConnectionBase):id: uuid.UUIDuser_id: uuid.UUID@@ -20,6 +31,9 @@ class BankConnectionRead(BankConnectionBase):status: strlast_sync_at: Optional[datetime] = Nonecreated_at: datetime+ # Institutions this link spans. Empty for providers that are one+ # institution per connection — institution_name above covers those.+ institutions: list[ConnectionInstitutionRead] = []model_config = ConfigDict(from_attributes=True)diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex c53dfa65..b1d6a2d6 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -133,10 +133,26 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c]-def _institution_name(connection: Optional[BankConnection]) -> Optional[str]:- if not connection:- return None- return connection.display_name or connection.institution_name+def _institution(+ acc: Account, connection: Optional[BankConnection]+) -> tuple[Optional[str], Optional[str]]:+ # (name, logo) resolved as a pair so both always describe the same+ # institution. The account's own institution (SimpleFIN — issue #345)+ # only outranks a connection rename when the link actually spans several+ # institutions — on a single-bank link the rename keeps working. The logo+ # falls back to the connection's only on single-institution links, where+ # it belongs to the same bank; on multi links a missing favicon beats+ # another bank's.+ if acc.institution is None:+ if not connection:+ return None, None+ return connection.display_name or connection.institution_name, connection.logo_url+ if connection is None:+ return acc.institution.name, acc.institution.logo_url+ if len(connection.institutions) > 1:+ return acc.institution.name, acc.institution.logo_url+ name = connection.display_name or acc.institution.name+ return name, acc.institution.logo_url or connection.logo_urldef serialize_account(@@ -152,6 +168,7 @@ def serialize_account(else:resolved_balance = float(current_balance or 0)+ institution_name, institution_logo_url = _institution(acc, connection)payload = {"id": acc.id,"user_id": acc.user_id,@@ -173,8 +190,8 @@ def serialize_account("minimum_payment": float(acc.minimum_payment) if acc.minimum_payment is not None else None,"card_brand": acc.card_brand,"card_level": acc.card_level,- "institution_name": _institution_name(connection),- "institution_logo_url": connection.logo_url if connection else None,+ "institution_name": institution_name,+ "institution_logo_url": institution_logo_url,"available_credit": None,"next_close_date": None,"next_due_date": None,diff --git a/backend/app/services/asset_group_service.py b/backend/app/services/asset_group_service.pyindex 0ad5a885..0b5a52dc 100644--- a/backend/app/services/asset_group_service.py+++ b/backend/app/services/asset_group_service.py@@ -3,6 +3,7 @@ from decimal import Decimalfrom typing import Optionalfrom sqlalchemy import func, select+from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.config import get_settings@@ -100,17 +101,21 @@ async def _rollup(async def _institution_name_for(- session: AsyncSession, connection_id: Optional[uuid.UUID]+ session: AsyncSession, group: AssetGroup) -> Optional[str]:"""Fetch the bank/broker institution name for a synced wallet.- Returns None for manual wallets (no connection) or if the connection- was deleted — callers render the subtitle conditionally on this.+ Prefers the wallet's own institution (issue #345), falling back to the+ connection's label. Returns None for manual wallets (no connection) or+ if the connection was deleted — callers render the subtitle+ conditionally on this."""- if connection_id is None:+ if group.institution is not None:+ return group.institution.name+ if group.connection_id is None:return Nonerow = await session.execute(- select(BankConnection.institution_name).where(BankConnection.id == connection_id)+ select(BankConnection.institution_name).where(BankConnection.id == group.connection_id))return row.scalar_one_or_none()@@ -143,7 +148,7 @@ async def get_groups(# "MeuPluggy 4 · 0 items" after reconnects/migrations.if g.source != "manual" and count == 0:continue- institution = await _institution_name_for(session, g.connection_id)+ institution = await _institution_name_for(session, g)reads.append(_group_to_read(g, count, cv, cvp, institution))return reads@@ -162,7 +167,7 @@ async def get_group(return Noneprimary = await _primary_currency_for(session, user_id)count, cv, cvp = await _rollup(session, group, primary)- institution = await _institution_name_for(session, group.connection_id)+ institution = await _institution_name_for(session, group)return _group_to_read(group, count, cv, cvp, institution)@@ -222,7 +227,7 @@ async def update_group(await session.refresh(group)primary = await _primary_currency_for(session, user_id)count, cv, cvp = await _rollup(session, group, primary)- institution = await _institution_name_for(session, group.connection_id)+ institution = await _institution_name_for(session, group)return _group_to_read(group, count, cv, cvp, institution)@@ -245,6 +250,8 @@ async def ensure_group_for_connection(source: str,external_id: Optional[str],default_name: str,+ institution_id: Optional[uuid.UUID] = None,+ workspace_id: Optional[uuid.UUID] = None,) -> AssetGroup:"""Return (creating if absent) the group that owns a connection's assets.@@ -254,6 +261,21 @@ async def ensure_group_for_connection(otherwise (user_id, source, connection_id). The name is only appliedon creation — users are free to rename synced groups later."""++ def _align(g: AssetGroup) -> AssetGroup:+ # Re-link if the connection was recreated. Name is preserved. The+ # wallet key is unique per (user, source) across workspaces, so a+ # match from another workspace means the bank moved there — the+ # wallet follows its connection.+ if g.connection_id != connection_id:+ g.connection_id = connection_id+ if workspace_id is not None and g.workspace_id != workspace_id:+ g.workspace_id = workspace_id+ # Backfills groups that predate institution tracking (issue #345).+ if institution_id is not None and g.institution_id != institution_id:+ g.institution_id = institution_id+ return g+# Prefer matching by external_id (Pluggy item id). Falls back to# connection_id which is less stable (connection can be deleted/recreated).query = select(AssetGroup).where(@@ -268,18 +290,16 @@ async def ensure_group_for_connection(result = await session.execute(query)group = result.scalar_one_or_none()if group:- # Re-link if the connection was recreated. Name is preserved.- if group.connection_id != connection_id:- group.connection_id = connection_id- return group+ return _align(group)position = await _next_position(session, user_id)# Disambiguate when the user has multiple connections from the same# institution (common with Pluggy sandbox, where every item comes back# as "MeuPluggy"). Appends " 2", " 3", etc. until we find a free name.# User can rename freely afterwards without affecting sync matching,- # which keys on external_id, not on name.- unique_name = await _unique_default_name(session, user_id, default_name)+ # which keys on external_id, not on name. Clamped so the disambiguating+ # suffix still fits the 100-char name column.+ unique_name = await _unique_default_name(session, user_id, default_name[:95])group = AssetGroup(user_id=user_id,name=unique_name,@@ -289,19 +309,38 @@ async def ensure_group_for_connection(source=source,connection_id=connection_id,external_id=external_id,+ institution_id=institution_id,)- session.add(group)- await session.flush()+ if workspace_id is not None:+ group.workspace_id = workspace_id+ # A concurrent sync (scheduled + manual) can mint the same key; the+ # savepoint keeps the loser's IntegrityError from poisoning the+ # session — re-select and use the winner's row.+ try:+ async with session.begin_nested():+ session.add(group)+ await session.flush()+ except IntegrityError:+ result = await session.execute(query)+ group = _align(result.scalar_one())return groupasync def _unique_default_name(- session: AsyncSession, user_id: uuid.UUID, base: str+ session: AsyncSession,+ user_id: uuid.UUID,+ base: str,+ exclude_group_id: Optional[uuid.UUID] = None,) -> str:- """Return `base` or the first free `base N` for this user."""- existing_rows = await session.execute(- select(AssetGroup.name).where(AssetGroup.user_id == user_id)- )+ """Return `base` or the first free `base N` for this user.++ A group being renamed in place passes its own id so its current name+ doesn't count as taken.+ """+ query = select(AssetGroup.name).where(AssetGroup.user_id == user_id)+ if exclude_group_id is not None:+ query = query.where(AssetGroup.id != exclude_group_id)+ existing_rows = await session.execute(query)taken = {row[0] for row in existing_rows.all()}if base not in taken:return basediff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 64613fa2..28f0657c 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -1,10 +1,13 @@+import hashlibimport logging+import reimport uuidfrom datetime import date, datetime, timedelta, timezonefrom decimal import Decimal, InvalidOperationfrom typing import Optional-from sqlalchemy import delete, exists, or_, select, update+from sqlalchemy import delete, exists, func, or_, select, update+from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload@@ -15,12 +18,16 @@ from app.models.asset_value import AssetValuefrom app.models.bank_connection import BankConnectionfrom app.models.account import Accountfrom app.models.category import Category+from app.models.institution import Institution+from app.models.goal import Goal+from app.models.collection import collection_asset_groupsfrom app.models.credit_card_bill import CreditCardBillfrom app.models.payee import Payee, PayeeMappingfrom app.models.transaction import Transactionfrom app.models.user import Userfrom app.providers import get_providerfrom app.providers.base import (+ AccountData,HoldingData,ProviderNotConfiguredError,ProviderRateLimited,@@ -34,7 +41,10 @@ from app.services.account_service import (_simplefin_to_internal_balance,sync_opening_balance_for_connected_account,)-from app.services.asset_group_service import ensure_group_for_connection+from app.services.asset_group_service import (+ _unique_default_name,+ ensure_group_for_connection,+)from app.services.credit_card_service import apply_effective_datefrom app.services.rule_engine import merge_notesfrom app.services.rule_service import apply_rules_to_transaction, preview_rules_for_transaction@@ -51,10 +61,146 @@ def _clean_logo_url(value: object) -> Optional[str]:"""Normalize a provider-supplied logo to a non-empty string or None.Guards the DB column against anything a provider hands back that isn't a- usable URL (None, empty string, or a non-string), so a misbehaving- integration can never write junk into ``bank_connections.logo_url``.+ usable URL (None, empty string, a non-string, or one longer than the+ column — truncating would store a broken URL, so it's dropped), so a+ misbehaving integration can never write junk into a ``logo_url`` column+ or abort a sync with a DataError."""- return value if isinstance(value, str) and value.strip() else None+ if isinstance(value, str) and value.strip() and len(value) <= 500:+ return value+ return None+++def _clean_institution_name(value: object) -> Optional[str]:+ """Same guard as _clean_logo_url, for the 255-char institution columns."""+ return value[:255] if isinstance(value, str) and value.strip() else None+++def _wallet_external_id(connection_external_id: str, account_key: Optional[str]) -> str:+ """The per-account wallet key, squeezed into the 255-char column.++ Truncation alone could collide two accounts; over-long composites keep a+ deterministic digest suffix instead.+ """+ if not account_key:+ return connection_external_id+ key = f"{connection_external_id}::{account_key}"+ if len(key) <= 255:+ return key+ digest = hashlib.sha256(key.encode("utf-8")).hexdigest()+ return f"{key[:214]}::{digest[:39]}"+++def _is_auto_wallet_name(name: str, institution_name: str) -> bool:+ """True while a wallet still carries its creation-time auto-name — the+ institution label, possibly with _unique_default_name's " N" suffix."""+ if name == institution_name:+ return True+ return bool(re.fullmatch(re.escape(institution_name) + r" \d+", name))+++async def _resolve_institution(+ session: AsyncSession,+ connection_id: uuid.UUID,+ cache: dict[str, Institution],+ acc_data: AccountData,+) -> Optional[Institution]:+ """Get-or-create the Institution row an account's provider hint names.++ Matched by the provider's stable org id when it sends one, so a bank+ renamed on the provider side updates its row in place instead of minting+ a new one (review on #654); name identity is the fallback for servers+ that only send a name. Providers without per-account hints+ (Pluggy/Enable — one institution per connection) return None, and+ serialization falls back to the connection's own fields.+ """+ name = _clean_institution_name(acc_data.institution_name)+ if not name:+ return None+ ext = _clean_institution_name(acc_data.institution_external_id)+ key = f"id:{ext}" if ext else f"name:{name}"+ if key in cache:+ return cache[key]++ inst: Optional[Institution] = None+ if ext:+ inst = (+ await session.execute(+ select(Institution).where(+ Institution.connection_id == connection_id,+ Institution.external_id == ext,+ )+ )+ ).scalar_one_or_none()+ if inst is None:+ # Adopt a row created before the server sent org ids, so the+ # accounts pointing at it don't get orphaned onto a new row.+ inst = (+ await session.execute(+ select(Institution).where(+ Institution.connection_id == connection_id,+ Institution.external_id.is_(None),+ Institution.name == name,+ )+ )+ ).scalar_one_or_none()+ if inst is not None:+ inst.external_id = ext+ else:+ # Name-only hint. Match any row with this name — id-keyed rows+ # included, so a payload that intermittently drops org ids doesn't+ # spawn duplicates. NULLS FIRST keeps the pick deterministic.+ inst = (+ await session.execute(+ select(Institution)+ .where(+ Institution.connection_id == connection_id,+ Institution.name == name,+ )+ .order_by(Institution.external_id.asc().nulls_first())+ .limit(1)+ )+ ).scalar_one_or_none()++ if inst is None:+ inst = Institution(+ connection_id=connection_id,+ external_id=ext,+ name=name,+ logo_url=_clean_logo_url(acc_data.institution_logo_url),+ )+ try:+ # Savepoint: a concurrent sync (scheduled + manual) can insert+ # the same identity between our SELECT and this flush. The+ # partial unique index rejects the loser — reuse the winner's+ # row instead of failing the whole sync.+ async with session.begin_nested():+ session.add(inst)+ await session.flush()+ except IntegrityError:+ inst = (+ await session.execute(+ select(Institution)+ .where(+ Institution.connection_id == connection_id,+ Institution.external_id == ext+ if ext+ else Institution.name == name,+ )+ .limit(1)+ )+ ).scalar_one()+ else:+ if inst.name != name:+ inst.name = name # provider-side rename+ # The logo is favicon-derived from the org's website, never user-set,+ # so it follows the provider too — a rename that moves domains would+ # otherwise keep the old bank's icon forever.+ new_logo = _clean_logo_url(acc_data.institution_logo_url)+ if new_logo is not None and inst.logo_url != new_logo:+ inst.logo_url = new_logo+ cache[key] = inst+ return instPLUGGY_CATEGORY_MAP = {"Eating out": "Alimentação",@@ -128,19 +274,245 @@ async def _sync_holdings(source = connection.providertoday = date.today()- # Find-or-create the wallet that will own this connection's holdings.- # Name defaults to the institution; users can rename freely without+ # Find-or-create the wallet(s) that own this connection's holdings. A+ # holding carrying its owning account (SimpleFIN — issue #345) gets one+ # wallet per investment account, named after it; the rest share the+ # connection-named wallet. Users can rename wallets freely without# breaking future syncs (matching is by external_id).- group: Optional[AssetGroup] = None- if holdings:- group = await ensure_group_for_connection(- session,- user_id=user_id,- connection_id=connection.id,- source=source,- external_id=connection.external_id,- default_name=connection.institution_name,+ groups_by_key: dict[Optional[str], AssetGroup] = {}+ holding_ids = {h.external_id for h in holdings if h.external_id}+ # Snapshots before any bucket runs, so payload order can't change them.+ # Once per-account wallets exist under the current connection key, the+ # plain-keyed wallet is the live connection-default, not a legacy row+ # awaiting its first split — adopting it would hijack it. A keyed+ # bucket applies the stricter test: any split wallet in scope (old+ # prefixes included) means past the legacy era, so a genuinely new+ # account must mint even right after a reconnect rotated the prefix —+ # only the keyless bucket may still adopt the stale default then.+ has_split_wallets = bool(+ await session.scalar(+ select(+ exists().where(+ AssetGroup.user_id == user_id,+ AssetGroup.workspace_id == connection.workspace_id,+ AssetGroup.source == source,+ AssetGroup.external_id.startswith(+ f"{connection.external_id}::", autoescape=True+ ),+ )+ )+ )+ )+ has_any_split_wallets = has_split_wallets or bool(+ await session.scalar(+ select(+ exists().where(+ AssetGroup.user_id == user_id,+ AssetGroup.workspace_id == connection.workspace_id,+ AssetGroup.source == source,+ or_(+ AssetGroup.connection_id == connection.id,+ AssetGroup.connection_id.is_(None),+ ),+ AssetGroup.external_id.contains("::"),+ )+ ))+ )++ async def _holds_synced_asset(group_id: uuid.UUID) -> bool:+ """Does this wallet already hold an asset this payload re-syncs?"""+ if not holding_ids:+ return False+ return bool(+ await session.scalar(+ select(+ exists().where(+ Asset.group_id == group_id,+ Asset.external_id.in_(holding_ids),+ )+ )+ )+ )++ async def _wallet_for(holding: HoldingData) -> AssetGroup:+ key = holding.account_external_id+ if key not in groups_by_key:+ # The owning account's institution backs the wallet's+ # "Synced from …" subtitle (issue #345).+ institution_id = (+ await session.scalar(+ select(Account.institution_id).where(+ Account.connection_id == connection.id,+ Account.external_id == key,+ )+ )+ if key+ else None+ )+ wallet_key = _wallet_external_id(connection.external_id, key)+ default_name = (+ _clean_institution_name(holding.account_name)+ or connection.institution_name+ )+ # The first claim on a wallet key adopts the wallet these+ # holdings lived in before — the legacy connection-keyed one, or+ # one left on a stale key by a reconnect (plain or per-account:+ # a "…::{account}" suffix match is this very account's wallet+ # under an older connection key) — instead of minting a new+ # row, so an existing user's rename/icon/color/position+ # survive. Only an untouched auto-name is refreshed. Guards, in+ # order: never adopt when a wallet already owns the key+ # (re-keying a twin next to it would trip the unique+ # (user, source, external_id) index and fail every sync); never+ # adopt a wallet another bucket of this run claimed; never+ # reach into another workspace; a plain candidate only counts+ # before the first split — afterwards it is the live+ # connection-default wallet, not a legacy awaiting adoption; a+ # stale-keyed candidate must be provably this bank's — still+ # linked to this connection, or an orphan holding assets this+ # payload re-syncs (a deleted sibling connection's orphan is+ # neither); ambiguity means minting, not guessing.+ existing = await session.scalar(+ select(AssetGroup.id).where(+ AssetGroup.user_id == user_id,+ AssetGroup.source == source,+ AssetGroup.external_id == wallet_key,+ )+ )+ legacy: Optional[AssetGroup] = None+ if existing is None:+ claimed = {g.id for g in groups_by_key.values()}+ key_shape = ~AssetGroup.external_id.contains("::")+ if key:+ key_shape = or_(+ key_shape,+ AssetGroup.external_id.endswith(+ f"::{key}", autoescape=True+ ),+ )+ candidates = [+ g+ for g in (+ await session.execute(+ select(AssetGroup).where(+ AssetGroup.user_id == user_id,+ AssetGroup.workspace_id == connection.workspace_id,+ AssetGroup.source == source,+ or_(+ AssetGroup.connection_id == connection.id,+ AssetGroup.connection_id.is_(None),+ ),+ AssetGroup.external_id.isnot(None),+ # Wallets keyed under the live prefix belong+ # to their own accounts, never to this one.+ ~AssetGroup.external_id.startswith(+ f"{connection.external_id}::",+ autoescape=True,+ ),+ key_shape,+ )+ )+ ).scalars().all()+ if g.id not in claimed+ ]+ # A stale key parses as exactly "{old prefix}::{key}"; a+ # leftover "::" in the remainder means the tail straddles+ # another account's key (ids may themselves contain "::").+ tail = f"::{key}" if key else None+ suffixed = [+ g+ for g in candidates+ if tail+ and g.external_id+ and g.external_id.endswith(tail)+ and g.external_id[: -len(tail)]+ and "::" not in g.external_id[: -len(tail)]+ ]+ plain = [+ g+ for g in candidates+ if g.external_id and "::" not in g.external_id+ ]+ pool = suffixed or (+ []+ if (has_any_split_wallets if key else has_split_wallets)+ else plain+ )+ exact = [+ g for g in pool if g.external_id == connection.external_id+ ]+ if exact:+ legacy = exact[0]+ else:+ ours = [g for g in pool if g.connection_id == connection.id]+ if not ours:+ ours = [+ g for g in pool if await _holds_synced_asset(g.id)+ ]+ if len(ours) == 1:+ legacy = ours[0]+ if legacy is not None:+ # A concurrent sync can win the key between the guard above+ # and this flush; fall through to the mint path, which+ # re-selects the winner's row.+ try:+ async with session.begin_nested():+ legacy.external_id = wallet_key+ legacy.connection_id = connection.id+ if _is_auto_wallet_name(+ legacy.name, connection.institution_name+ ):+ legacy.name = await _unique_default_name(+ session,+ user_id,+ default_name[:95],+ exclude_group_id=legacy.id,+ )+ if institution_id is not None:+ legacy.institution_id = institution_id+ await session.flush()+ except IntegrityError:+ await session.refresh(legacy)+ else:+ groups_by_key[key] = legacy+ return legacy+ groups_by_key[key] = await ensure_group_for_connection(+ session,+ user_id=user_id,+ connection_id=connection.id,+ source=source,+ external_id=wallet_key,+ default_name=default_name,+ institution_id=institution_id,+ workspace_id=connection.workspace_id,+ )+ return groups_by_key[key]++ # Wallets this sync owns: this connection's, plus orphans a prior+ # disconnect left behind (connection_id went NULL via SET NULL) — their+ # re-adopted assets must still split into per-account wallets instead of+ # staying stranded. An asset sitting in one may be re-attributed below;+ # a user's custom wallet (source "manual") and other workspaces' wallets+ # are never touched.+ sync_owned_rows = await session.execute(+ select(AssetGroup.id, AssetGroup.external_id).where(+ AssetGroup.user_id == user_id,+ AssetGroup.workspace_id == connection.workspace_id,+ AssetGroup.source == source,+ or_(+ AssetGroup.connection_id == connection.id,+ AssetGroup.connection_id.is_(None),+ ),+ )+ )+ sync_owned = sync_owned_rows.all()+ sync_owned_group_ids = {row[0] for row in sync_owned}+ # Per-account wallets, by their "…::…" keys. A holding that lost its+ # account hint must not drain one of these into the default bucket — a+ # single degraded payload would empty them and the reap would delete+ # the user's customization with them.+ split_group_ids = {row[0] for row in sync_owned if row[1] and "::" in row[1]}# Also pull orphans (connection_id IS NULL) with the same source —# those are assets archived by a prior disconnect. Re-matching on@@ -184,12 +556,24 @@ async def _sync_holdings(asset = await _upsert_asset_from_holding(session, existing, holding, user_id, connection.id, source,+ workspace_id=connection.workspace_id,)- # Attach to the connection's wallet. We only set group_id when- # it's currently null so a user who moved this holding to a- # custom wallet ("US Stocks") doesn't get overridden back on- # every sync.- if group is not None and asset.group_id is None:+ # Attach to its institution's wallet. NOTE this deliberately moves+ # holdings between sync-owned wallets, not just out of a null group+ # like it used to: re-attribution corrects the sync's own earlier+ # bucketing (one-wallet-per-connection → per-account). A wallet the+ # user made themselves ("US Stocks", source "manual") is never+ # touched.+ group = await _wallet_for(holding)+ hint_lost = (+ holding.account_external_id is None+ and asset.group_id in split_group_ids+ )+ if (+ not hint_lost+ and (asset.group_id is None or asset.group_id in sync_owned_group_ids)+ and asset.group_id != group.id+ ):asset.group_id = group.id# Seed a historical value at purchase_date so users get a real# evolution curve from day one — not just today's snapshot.@@ -209,6 +593,35 @@ async def _sync_holdings(if ext_id not in seen and not asset.is_archived:asset.is_archived = True+ # Sync owns its wallets: drop any it emptied by re-attribution above+ # (e.g. the single connection-named wallet that predates per-institution+ # ones). Wallets still holding assets — or used this run — are kept, and+ # so is anything a goal tracks or a collection contains: deleting those+ # would SET NULL the goal's target and CASCADE the membership away,+ # silently breaking things the user built on the wallet.+ if holdings:+ await session.flush()+ used_ids = {g.id for g in groups_by_key.values()}+ for gid in sync_owned_group_ids - used_ids:+ has_assets = await session.scalar(+ select(func.count()).select_from(Asset).where(Asset.group_id == gid)+ )+ if has_assets:+ continue+ referenced = await session.scalar(+ select(+ exists().where(Goal.asset_group_id == gid)+ | exists()+ .select_from(collection_asset_groups)+ .where(collection_asset_groups.c.asset_group_id == gid)+ )+ )+ if referenced:+ continue+ emptied = await session.get(AssetGroup, gid)+ if emptied is not None:+ await session.delete(emptied)+async def _upsert_asset_from_holding(session: AsyncSession,@@ -217,6 +630,7 @@ async def _upsert_asset_from_holding(user_id: uuid.UUID,connection_id: uuid.UUID,source: str,+ workspace_id: Optional[uuid.UUID] = None,) -> Asset:"""Create or update an Asset from a HoldingData payload.@@ -259,6 +673,12 @@ async def _upsert_asset_from_holding(# (e.g. unlink + reconnect). This avoids overriding user-archived assets.if asset.is_archived and previous_connection_id != connection_id:asset.is_archived = False+ # Re-adopted across workspaces (bank deleted in one, re-added in the+ # other): the asset follows its connection; its old wallet stays behind+ # in the old workspace, so placement is redone by the caller.+ if workspace_id is not None and asset.workspace_id != workspace_id:+ asset.workspace_id = workspace_id+ asset.group_id = None# Sparse fields — merge, don't clobber. Pluggy sometimes returns# these on first sync and null on later ones (e.g. amountOriginal@@ -581,8 +1001,12 @@ async def handle_oauth_callback(use_provider_cats = await admin_service.use_provider_categories(session)+ institution_cache: dict[str, Institution] = {}for acc_data in connection_data.accounts:is_cc = acc_data.type == "credit_card"+ institution = await _resolve_institution(+ session, connection.id, institution_cache, acc_data+ )account = Account(user_id=user_id,workspace_id=workspace_id,@@ -599,6 +1023,7 @@ async def handle_oauth_callback(minimum_payment=acc_data.minimum_payment if is_cc else None,card_brand=acc_data.card_brand if is_cc else None,card_level=acc_data.card_level if is_cc else None,+ institution_id=institution.id if institution else None,)session.add(account)await session.flush()@@ -1214,6 +1639,7 @@ async def sync_connection(new_tx_ids: list[uuid.UUID] = []merged_count = 0accounts_data = await provider.get_accounts(credentials)+ institution_cache: dict[str, Institution] = {}for acc_data in accounts_data:result = await session.execute(select(Account).where(@@ -1223,12 +1649,21 @@ async def sync_connection()account = result.scalar_one_or_none()+ institution = await _resolve_institution(+ session, connection.id, institution_cache, acc_data+ )+# Honor user intent: a closed connected account stays closed and is# not touched by sync. The row is left alone (no balance/name# rewrite, no new transactions) but the connection link is kept so# the next sync still finds it here instead of creating a duplicate- # active account (issue #90).+ # active account (issue #90). Its institution pointer still follows+ # the provider, though — otherwise a renamed org's abandoned row+ # would stay pinned forever and keep a single-bank link presenting+ # as multi-institution.if account and account.is_closed:+ if institution is not None and account.institution_id != institution.id:+ account.institution_id = institution.idcontinueif account:@@ -1247,6 +1682,9 @@ async def sync_connection(# that intermittently omits it can't blank out a known mask.if acc_data.masked_number is not None:account.masked_number = acc_data.masked_number+ # Backfills existing accounts on next sync (issue #345).+ if institution is not None:+ account.institution_id = institution.idif acc_data.type == "credit_card":# Preserve existing CC metadata when the provider doesn't# expose it. Pluggy's creditData fields (limit, close/due@@ -1284,6 +1722,7 @@ async def sync_connection(minimum_payment=acc_data.minimum_payment if is_cc else None,card_brand=acc_data.card_brand if is_cc else None,card_level=acc_data.card_level if is_cc else None,+ institution_id=institution.id if institution else None,)session.add(account)await session.flush()@@ -1561,6 +2000,24 @@ async def sync_connection(if _sync_assets_enabled(conn_settings):await _sync_holdings(session, user_id, connection, credentials)+ # Reap institution rows referenced by nothing. Id-carrying servers+ # never orphan a row (renames update in place), but a name-only+ # server that renames its bank mints a fresh row and repoints the+ # accounts — the abandoned row would otherwise keep a single-bank+ # link presenting as multi-institution forever. Requiring zero+ # account AND zero wallet references means a wallet's "Synced from"+ # label can never be taken away. Runs after the holdings sync so a+ # wallet repointed away from the old row frees it this sync, not next.+ orphaned_institutions = await session.execute(+ select(Institution).where(+ Institution.connection_id == connection.id,+ ~exists().where(Account.institution_id == Institution.id),+ ~exists().where(AssetGroup.institution_id == Institution.id),+ )+ )+ for orphan in orphaned_institutions.scalars().all():+ await session.delete(orphan)+connection.last_sync_at = datetime.now(timezone.utc)connection.status = "active"await session.commit()diff --git a/backend/mcp_server/tools/accounts.py b/backend/mcp_server/tools/accounts.pyindex 43281b73..61ea3eda 100644--- a/backend/mcp_server/tools/accounts.py+++ b/backend/mcp_server/tools/accounts.py@@ -44,7 +44,7 @@ async def list_accounts("balance": num(r.get("balance")),"balance_primary": num(r.get("balance_primary")),"is_closed": bool(r.get("is_closed", False)),- "institution": r.get("institution"),+ "institution": r.get("institution_name"),})return {"items": items, "total": len(items)}diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.pyindex ecc42064..25b3e904 100644--- a/backend/tests/test_account_service.py+++ b/backend/tests/test_account_service.py@@ -1180,3 +1180,207 @@ async def test_update_simplefin_type_change_not_crossing_card_keeps_balance(assert updated is not Noneassert updated.type == "savings"assert updated.balance == Decimal("1500.00")+++# ----- per-account institution resolution (issue #345) ------------------------+++def _mem_connection(**overrides):+ from app.models.bank_connection import BankConnection++ defaults = dict(+ provider="simplefin",+ external_id="CON-1",+ institution_name="First Bank",+ logo_url="https://logos.example/first.png",+ )+ defaults.update(overrides)+ return BankConnection(**defaults)+++def _mem_institution(name="Second Brokerage", logo_url="https://logos.example/second.png"):+ from app.models.institution import Institution++ return Institution(name=name, logo_url=logo_url)+++def _mem_multi_connection(**overrides):+ """A connection spanning two institutions (multi-institution link)."""+ return _mem_connection(+ institutions=[_mem_institution("First Bank", None), _mem_institution()],+ **overrides,+ )+++def test_institution_falls_back_to_connection_when_account_has_none():+ """Pluggy/Enable accounts have no institution row — connection wins."""+ from app.services.account_service import _institution++ acc = Account(name="Checking", type="checking")+ name, logo = _institution(acc, _mem_connection())+ assert name == "First Bank"+ assert logo == "https://logos.example/first.png"+++def test_institution_prefers_the_accounts_own_on_multi_links():+ """On a link spanning several institutions, each account shows its own."""+ from app.services.account_service import _institution++ acc = Account(name="Brokerage", type="investment")+ acc.institution = _mem_institution()+ name, logo = _institution(acc, _mem_multi_connection())+ assert name == "Second Brokerage"+ assert logo == "https://logos.example/second.png"+++def test_institution_never_mixes_name_and_logo_on_multi_links():+ """On a multi-institution link, an account whose institution has no logo+ must not borrow the connection's — that would pair one bank's name with+ another bank's icon."""+ from app.services.account_service import _institution++ acc = Account(name="Brokerage", type="investment")+ acc.institution = _mem_institution(logo_url=None)+ name, logo = _institution(acc, _mem_multi_connection())+ assert name == "Second Brokerage"+ assert logo is None+++def test_institution_single_link_falls_back_to_connection_logo():+ """On a single-institution link the connection's logo is the same bank's,+ so it fills in when the institution row has none (review on #654)."""+ from app.services.account_service import _institution++ acc = Account(name="Checking", type="checking")+ acc.institution = _mem_institution("First Bank", logo_url=None)+ conn = _mem_connection(institutions=[acc.institution])+ name, logo = _institution(acc, conn)+ assert name == "First Bank"+ assert logo == "https://logos.example/first.png"+++def test_institution_rename_wins_on_single_links_but_not_multi():+ """Renaming a single-bank link relabels its accounts (review on #654);+ renaming a multi-institution link labels the link, not the banks."""+ from app.services.account_service import _institution++ single = _mem_connection(display_name="My Bank")+ with_own = Account(name="Checking", type="checking")+ with_own.institution = _mem_institution("First Bank")+ single.institutions = [with_own.institution]+ assert _institution(with_own, single)[0] == "My Bank"++ multi = _mem_multi_connection(display_name="My Bank Link")+ at_second = Account(name="Brokerage", type="investment")+ at_second.institution = multi.institutions[1]+ assert _institution(at_second, multi)[0] == "Second Brokerage"++ hint_less = Account(name="Other", type="checking")+ assert _institution(hint_less, multi)[0] == "My Bank Link"+++def test_institution_manual_account_has_none():+ from app.services.account_service import _institution++ assert _institution(Account(name="Wallet", type="checking"), None) == (None, None)+++def _hint(name, logo=None, ext=None):+ from app.providers.base import AccountData++ return AccountData(+ external_id="x", name="A", type="checking",+ balance=Decimal("0"), currency="USD",+ institution_external_id=ext, institution_name=name, institution_logo_url=logo,+ )+++async def test_resolve_institution_matches_by_org_id_across_renames(+ session: AsyncSession, test_user,+):+ """A bank renamed on the provider side updates its row in place — same id,+ new name — instead of minting a new row (review on #654)."""+ from app.services.connection_service import _resolve_institution++ conn_id = await _make_provider_connection(session, test_user.id, "simplefin")++ first = await _resolve_institution(+ session, conn_id, {}, _hint("Chase Bank", "https://logos.example/old.png", ext="CON-1")+ )+ assert first is not None+ renamed = await _resolve_institution(+ session, conn_id, {}, _hint("Chase", "https://logos.example/new.png", ext="CON-1")+ )+ assert renamed is not None+ assert renamed.id == first.id+ assert renamed.name == "Chase"+ # The favicon-derived logo follows the provider too — a rename that+ # moves domains must not keep the old bank's icon.+ assert renamed.logo_url == "https://logos.example/new.png"+++async def test_resolve_institution_adopts_legacy_name_row(+ session: AsyncSession, test_user,+):+ """A row created before the server sent org ids is adopted by the first+ id-carrying hint with the same name, keeping its accounts attached."""+ from app.services.connection_service import _resolve_institution++ conn_id = await _make_provider_connection(session, test_user.id, "simplefin")++ legacy = await _resolve_institution(session, conn_id, {}, _hint("Chase Bank"))+ assert legacy is not None and legacy.external_id is None+ adopted = await _resolve_institution(session, conn_id, {}, _hint("Chase Bank", ext="CON-1"))+ assert adopted is not None+ assert adopted.id == legacy.id+ assert adopted.external_id == "CON-1"+++async def test_resolve_institution_same_name_different_orgs_stay_distinct(+ session: AsyncSession, test_user,+):+ """Two logins at the same bank (same display name, different org ids)+ must not collapse into one row."""+ from app.services.connection_service import _resolve_institution++ conn_id = await _make_provider_connection(session, test_user.id, "simplefin")++ one = await _resolve_institution(session, conn_id, {}, _hint("Fidelity", ext="CON-1"))+ two = await _resolve_institution(session, conn_id, {}, _hint("Fidelity", ext="CON-2"))+ assert one is not None and two is not None+ assert one.id != two.id+++async def test_resolve_institution_upserts_and_reuses(session: AsyncSession, test_user):+ """One row per identity; first sighting wins the logo, later sightings+ backfill a missing one; no hint → no row."""+ from app.services.connection_service import _resolve_institution++ conn_id = await _make_provider_connection(session, test_user.id, "simplefin")++ cache = {}+ first = await _resolve_institution(session, conn_id, cache, _hint("Chase Bank"))+ assert first is not None and first.logo_url is None+ again = await _resolve_institution(+ session, conn_id, {}, _hint("Chase Bank", "https://logos.example/chase.png")+ )+ assert again is not None+ assert again.id == first.id # reused across cache misses+ assert again.logo_url == "https://logos.example/chase.png" # backfilled+ assert await _resolve_institution(session, conn_id, cache, _hint(None)) is None+ assert await _resolve_institution(session, conn_id, cache, _hint(" ")) is None+++def test_clean_logo_url_drops_overlong_urls():+ """A URL longer than the column is dropped, not truncated — a truncated+ URL is a broken URL (review on #654)."""+ from app.services.connection_service import _clean_logo_url++ assert _clean_logo_url("https://ok.example/logo.png") == "https://ok.example/logo.png"+ assert _clean_logo_url("https://long.example/" + "a" * 500) is None+ assert _clean_logo_url(" ") is None+ assert _clean_logo_url(None) is Nonediff --git a/backend/tests/test_accounts_api.py b/backend/tests/test_accounts_api.pyindex dcba6f9c..beb7d702 100644--- a/backend/tests/test_accounts_api.py+++ b/backend/tests/test_accounts_api.py@@ -102,6 +102,33 @@ async def test_update_bank_connected_account_rejected(assert "bank-connected" in response.json()["detail"].lower()+async def test_update_response_resolves_institution_like_get(+ client: AsyncClient, auth_headers, session, test_account: Account, test_connection+):+ """PATCH must serialize with the connection the way GET does: on a+ single-institution link a connection rename outranks the institution+ row's name (review round 5 on #654)."""+ from app.models.institution import Institution++ inst = Institution(+ connection_id=test_connection.id, external_id="org-1", name="First Bank",+ )+ session.add(inst)+ await session.flush()+ test_account.institution_id = inst.id+ test_connection.display_name = "My Bank"+ await session.commit()++ response = await client.patch(+ f"/api/accounts/{test_account.id}",+ headers=auth_headers,+ json={"display_name": "Everyday Checking"},+ )+ assert response.status_code == 200+ assert response.json()["institution_name"] == "My Bank"++@pytest.mark.asyncioasync def test_delete_manual_account(client: AsyncClient, auth_headers):# Create a manual accountdiff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.pyindex db3687d5..06bbe162 100644--- a/backend/tests/test_connection_service.py+++ b/backend/tests/test_connection_service.py@@ -2542,3 +2542,1760 @@ async def test_sync_leaves_simplefin_checking_balance_unchanged(await session.refresh(account)assert account.balance == Decimal("1234.56")+++# ---------------------------------------------------------------------------+# _sync_holdings — per-account wallets (issue #345)+# ---------------------------------------------------------------------------+++async def test_sync_holdings_splits_wallets_per_account(+ session: AsyncSession, test_user, test_workspace,+):+ """Holdings split into one wallet per owning account, backed by the+ account's institution. The legacy connection-keyed wallet is ADOPTED by+ the first account — re-keyed, its untouched auto-name refreshed — so an+ existing user's wallet row survives the upgrade; a wallet the user made+ themselves is never touched."""+ from app.models.asset_group import AssetGroup+ from app.models.institution import Institution+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "First Bank")++ inst = Institution(connection_id=conn.id, name="Second Brokerage")+ session.add(inst)+ await session.flush()+ account = Account(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, external_id="acc-1", name="Employer 401(k)",+ type="investment", balance=Decimal("0"), currency="USD",+ institution_id=inst.id,+ )+ session.add(account)++ # Legacy wallet from the one-wallet-per-connection era, holding h-1.+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="First Bank", source="test",+ connection_id=conn.id, external_id=conn.external_id,+ )+ # A wallet the user made themselves — sync must never touch it.+ custom = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="US Stocks", source="manual",+ )+ session.add_all([legacy, custom])+ await session.flush()++ asset_legacy = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=legacy.id,+ )+ asset_custom = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, source="test", external_id="h-2",+ name="Bonds", type="investment", currency="USD",+ valuation_method="manual", group_id=custom.id,+ )+ session.add_all([asset_legacy, asset_custom])+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="Employer 401(k)",+ ),+ HoldingData(+ external_id="h-2", name="Bonds", currency="USD",+ current_value=Decimal("5"),+ account_external_id="acc-1", account_name="Employer 401(k)",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ groups = (+ await session.execute(select(AssetGroup).where(AssetGroup.user_id == test_user.id))+ ).scalars().all()+ by_name = {g.name: g for g in groups}++ # The legacy wallet was adopted as the per-account wallet: same row,+ # re-keyed, auto-name ("First Bank" == institution label, so untouched+ # by the user) refreshed to the account's, institution backfilled.+ wallet = by_name["Employer 401(k)"]+ assert wallet.id == legacy.id+ assert wallet.external_id == f"{conn.external_id}::acc-1"+ assert wallet.institution_id == inst.id+ assert "First Bank" not in by_name++ await session.refresh(asset_legacy)+ assert asset_legacy.group_id == wallet.id++ # The user's own wallet keeps its asset, even though h-2 was synced.+ await session.refresh(asset_custom)+ assert asset_custom.group_id == custom.id+ assert "US Stocks" in by_name+++# ---------------------------------------------------------------------------+# sync_connection — institution wiring (issue #345)+# ---------------------------------------------------------------------------+++def _institution_provider(institution_name: str) -> AsyncMock:+ mock = AsyncMock()+ mock.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock.get_accounts = AsyncMock(return_value=[+ AccountData(+ external_id="acc-1", name="Checking", type="checking",+ balance=Decimal("0"), currency="USD",+ institution_external_id="CON-1", institution_name=institution_name,+ ),+ ])+ mock.get_transactions = AsyncMock(return_value=[])+ mock.get_holdings = AsyncMock(return_value=[])+ mock.get_bills = AsyncMock(return_value=[])+ return mock+++async def test_sync_wires_account_institutions_and_reaps_orphans(+ session: AsyncSession, test_user, test_workspace,+):+ """The account loop backfills institution_id on pre-existing accounts, a+ provider-side rename updates the row in place, rows nothing references+ are reaped, wallet-referenced rows survive, and the connections API+ exposes the link's institutions (review on #654)."""+ from app.models.asset_group import AssetGroup+ from app.models.institution import Institution+ from app.schemas.bank_connection import BankConnectionRead++ conn = await _make_connection(session, test_user.id, "Sync Bank")+ conn_id = conn.id++ # Pre-existing account with no institution yet — must get backfilled.+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="Checking",+ type="checking", balance=Decimal("0"), currency="USD",+ )+ session.add(account)+ account_id = account.id+ # An abandoned identity-drift row: no account or wallet points at it.+ stray = Institution(connection_id=conn_id, name="Old Name Bank")+ # A row only a wallet references — the reap must never touch it.+ kept = Institution(connection_id=conn_id, name="Departed Brokerage")+ session.add_all([stray, kept])+ await session.flush()+ stray_id, kept_id = stray.id, kept.id+ session.add(AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Old 401(k)", source="test", connection_id=conn_id,+ external_id="ext::gone", institution_id=kept_id,+ ))+ await session.commit()++ def _patched(mock):+ return (+ patch("app.services.connection_service.get_provider", return_value=mock),+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock),+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock),+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock),+ )++ p1, p2, p3, p4 = _patched(_institution_provider("Chase"))+ with p1, p2, p3, p4:+ await sync_connection(session, conn_id, test_workspace.id, test_user.id)++ from app.models.institution import Institution as Inst+ inst = (+ await session.execute(select(Inst).where(Inst.external_id == "CON-1"))+ ).scalar_one()+ assert inst.name == "Chase"+ refreshed = await session.get(Account, account_id)+ assert refreshed is not None and refreshed.institution_id == inst.id+ assert await session.get(Inst, stray_id) is None # reaped: nothing references it+ assert await session.get(Inst, kept_id) is not None # wallet keeps its label++ # Provider-side rename: same row, new name, no new rows.+ p1, p2, p3, p4 = _patched(_institution_provider("Chase Bank"))+ with p1, p2, p3, p4:+ await sync_connection(session, conn_id, test_workspace.id, test_user.id)+ renamed = await session.get(Inst, inst.id)+ assert renamed is not None and renamed.name == "Chase Bank"++ conn_row = (+ await session.execute(select(BankConnection).where(BankConnection.id == conn_id))+ ).scalar_one()+ read = BankConnectionRead.model_validate(conn_row)+ assert {i.name for i in read.institutions} == {"Chase Bank", "Departed Brokerage"}+++async def test_sync_holdings_readopts_orphaned_wallet_after_reconnect(+ session: AsyncSession, test_user, test_workspace,+):+ """Disconnect leaves the legacy wallet with connection_id NULL (SET NULL)+ and reconnects can mint a NEW connection external_id. The lone stale+ plain-keyed wallet is adopted anyway — customization kept, assets in+ place — instead of being emptied and deleted (review round 4 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Recon Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ # The pre-disconnect wallet: connection link severed, external_id intact.+ orphan_wallet = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Recon Bank", source="test",+ connection_id=None, external_id="old-ext",+ )+ session.add(orphan_wallet)+ await session.flush()+ orphan_wallet_id = orphan_wallet.id+ stranded = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=None, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=orphan_wallet_id,+ )+ session.add(stranded)+ await session.commit()+ stranded_id = stranded.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})+ await session.commit()++ moved = await session.get(Asset, stranded_id)+ assert moved is not None+ # The stale wallet was adopted as the per-account wallet: same row,+ # re-keyed and re-linked; "Recon Bank" was the untouched auto-name, so+ # it's refreshed to the account's.+ assert moved.group_id == orphan_wallet_id+ wallet = await session.get(AssetGroup, orphan_wallet_id)+ assert wallet is not None+ assert wallet.external_id == f"{conn.external_id}::acc-1"+ assert wallet.connection_id == conn_id+ assert wallet.name == "IRA"+++async def test_sync_holdings_keeps_emptied_wallet_a_goal_tracks(+ session: AsyncSession, test_user, test_workspace,+):+ """Deleting an emptied sync-owned wallet would SET NULL a goal's target+ and CASCADE away collection membership — so referenced wallets survive+ (self-review on #654)."""+ from app.models.asset_group import AssetGroup+ from app.models.goal import Goal+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Goal Bank")++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, external_id="acc-1", name="401(k)",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ # Keyed like a per-account wallet of a since-removed account, so the+ # legacy-adoption path (which only considers plain-keyed wallets) doesn't+ # claim it — this test exercises the goal guard on the emptied-wallet+ # delete, not adoption.+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Goal Bank", source="test",+ connection_id=conn.id, external_id="gone::acc-9",+ )+ session.add(legacy)+ await session.flush()+ legacy_id = legacy.id+ asset = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, source="test", external_id="h-1",+ name="Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=legacy_id,+ )+ goal = Goal(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Retire", target_amount=Decimal("1000000"),+ asset_group_id=legacy_id,+ )+ session.add_all([asset, goal])+ await session.commit()+ goal_id = goal.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Fund", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="401(k)",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})+ await session.commit()++ # Asset moved to the per-account wallet, but the goal's wallet survives+ # empty rather than vanishing out from under the goal.+ assert (await session.get(AssetGroup, legacy_id)) is not None+ refreshed_goal = await session.get(Goal, goal_id)+ assert refreshed_goal is not None+ assert refreshed_goal.asset_group_id == legacy_id+++async def test_sync_holdings_adoption_preserves_wallet_customization(+ session: AsyncSession, test_user, test_workspace,+):+ """The maintainer's repro on #654: an existing user's wallet — renamed,+ custom icon/color/position — must survive the first per-account sync as+ the same row with all customization intact, not come back as a default+ wallet. A custom name is never overwritten by adoption."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Fidelity")++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, external_id="acc-1", name="Rollover IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ customized = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My Retirement", icon="piggy-bank", color="#FF00AA", position=7,+ source="test", connection_id=conn.id, external_id=conn.external_id,+ )+ session.add(customized)+ await session.flush()+ wallet_id = customized.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, source="test", external_id="h-1",+ name="Index Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=wallet_id,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Index Fund", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="Rollover IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallet = await session.get(AssetGroup, wallet_id)+ assert wallet is not None # same row, not a replacement+ assert wallet.external_id == f"{conn.external_id}::acc-1" # re-keyed+ assert wallet.name == "My Retirement" # custom name untouched+ assert wallet.icon == "piggy-bank"+ assert wallet.color == "#FF00AA"+ assert wallet.position == 7+ # No second wallet minted for the account.+ all_synced = (+ await session.execute(select(AssetGroup).where(+ AssetGroup.user_id == test_user.id, AssetGroup.source == "test"))+ ).scalars().all()+ assert [g.id for g in all_synced] == [wallet_id]+++def test_wallet_external_id_fits_the_column_deterministically():+ """Over-long composites keep a deterministic digest suffix instead of a+ collision-prone truncation (review round 4 on #654)."""+ from app.services.connection_service import _wallet_external_id++ assert _wallet_external_id("EXT", "acc-1") == "EXT::acc-1"+ assert _wallet_external_id("EXT", None) == "EXT"+ long_a = _wallet_external_id("E" * 250, "a" * 250)+ long_b = _wallet_external_id("E" * 250, "b" * 250)+ assert len(long_a) <= 255 and len(long_b) <= 255+ assert long_a != long_b # truncation alone would collide these+ assert long_a == _wallet_external_id("E" * 250, "a" * 250) # deterministic+++async def test_sync_holdings_mixed_hints_stay_stable_across_syncs(+ session: AsyncSession, test_user, test_workspace,+):+ """A payload mixing account-attributed and unattributed holdings must+ reach a steady state: the per-account wallet and the connection-default+ wallet coexist, and a second sync neither re-keys, duplicates, nor+ crashes on the unique (user, source, external_id) index+ (review round 4 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Mixed Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Mixed Bank", source="test",+ connection_id=conn_id, external_id=conn.external_id,+ )+ session.add(legacy)+ await session.commit()+ legacy_id = legacy.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ # Spec-nonconforming account without an id → no account hint.+ HoldingData(+ external_id="h-2", name="Mystery Fund", currency="USD",+ current_value=Decimal("5"),+ ),+ ]++ for _ in range(2): # the second pass is the regression+ with patch(+ "app.services.connection_service.get_provider", return_value=mock_provider+ ):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallets = (+ await session.execute(select(AssetGroup).where(+ AssetGroup.user_id == test_user.id, AssetGroup.source == "test"))+ ).scalars().all()+ by_key = {w.external_id: w for w in wallets}+ # Steady state: the adopted per-account wallet plus one connection-default+ # wallet for the unattributed holding — no churn, no duplicates.+ assert len(wallets) == 2+ assert set(by_key) == {f"{conn.external_id}::acc-1", conn.external_id}+ assert by_key[f"{conn.external_id}::acc-1"].id == legacy_id # adopted once+++async def test_sync_holdings_adoption_refreshes_suffixed_auto_names(+ session: AsyncSession, test_user, test_workspace,+):+ """A wallet auto-named "Mixed Bank 2" by _unique_default_name is still an+ untouched auto-name — adoption refreshes it to the account's name, and+ the refresh itself dedupes against existing wallet names+ (review round 4 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Suffix Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="Employer 401(k)",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ # The name a second same-institution connection's wallet gets at creation.+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Suffix Bank 2", source="test",+ connection_id=conn_id, external_id=conn.external_id,+ )+ # A manual wallet already using the account's name — the refresh must+ # dedupe, not duplicate.+ session.add_all([legacy, AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Employer 401(k)", source="manual",+ )])+ await session.commit()+ legacy_id = legacy.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="Employer 401(k)",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallet = await session.get(AssetGroup, legacy_id)+ assert wallet is not None+ assert wallet.name == "Employer 401(k) 2" # refreshed AND deduped+++async def test_sync_holdings_unattributed_first_keeps_default_wallet_key(+ session: AsyncSession, test_user, test_workspace,+):+ """When the unattributed holding claims the connection-default wallet+ first, a later per-account bucket must not adopt (and re-key) that+ just-claimed wallet — provider-controlled payload order must not cause+ churn (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Order Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Order Bank", source="test",+ connection_id=conn_id, external_id=conn.external_id,+ )+ session.add(legacy)+ await session.commit()+ legacy_id = legacy.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ # Unattributed FIRST: the connection-default bucket claims the+ # legacy wallet before the per-account bucket goes looking.+ HoldingData(+ external_id="h-2", name="Mystery Fund", currency="USD",+ current_value=Decimal("5"),+ ),+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]++ for _ in range(2):+ with patch(+ "app.services.connection_service.get_provider", return_value=mock_provider+ ):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallets = (+ await session.execute(select(AssetGroup).where(+ AssetGroup.user_id == test_user.id, AssetGroup.source == "test"))+ ).scalars().all()+ by_key = {w.external_id: w for w in wallets}+ assert len(wallets) == 2+ assert set(by_key) == {conn.external_id, f"{conn.external_id}::acc-1"}+ # The claimed default wallet kept its plain key; the per-account wallet+ # is a separate row.+ assert by_key[conn.external_id].id == legacy_id+ assert by_key[f"{conn.external_id}::acc-1"].id != legacy_id+++async def test_sync_holdings_never_adopts_another_connections_orphan(+ session: AsyncSession, test_user, test_workspace,+):+ """A deleted sibling connection's orphaned wallet (connection_id NULL via+ SET NULL, same provider) is not this bank's: it holds none of the assets+ this payload syncs, so a new connection mints its own wallet instead of+ hijacking the orphan and mingling two banks' assets+ (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "New Bank")++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, external_id="acc-1", name="Brokerage",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ orphan = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Old Bank", source="test",+ connection_id=None, external_id="old-bank-ext",+ )+ session.add(orphan)+ await session.flush()+ orphan_id = orphan.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=None, source="test", external_id="old-h-1",+ name="Old Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=orphan_id, is_archived=True,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="Brokerage",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ untouched = await session.get(AssetGroup, orphan_id)+ assert untouched is not None+ assert untouched.external_id == "old-bank-ext"+ assert untouched.connection_id is None+ assert untouched.name == "Old Bank"+ minted = await session.scalar(+ select(AssetGroup).where(+ AssetGroup.external_id == f"{conn.external_id}::acc-1")+ )+ assert minted is not None+ assert minted.id != orphan_id+++async def test_sync_holdings_adopts_own_stale_wallet_over_foreign_orphan(+ session: AsyncSession, test_user, test_workspace,+):+ """A reconnect-in-place leaves the bank's wallet linked to the connection+ but on a stale key. It is adopted even when an unrelated orphan coexists —+ the old ambiguity rule would have minted a wallet and reaped the+ customized one (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Recon Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ stale = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My Retirement", source="test",+ connection_id=conn_id, external_id="pre-reconnect-ext",+ )+ foreign = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Old Bank", source="test",+ connection_id=None, external_id="old-bank-ext",+ )+ session.add_all([stale, foreign])+ await session.flush()+ stale_id, foreign_id = stale.id, foreign.id+ # The orphan still holds its old bank's archived asset.+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=None, source="test", external_id="old-h-1",+ name="Old Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=foreign_id, is_archived=True,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ adopted = await session.get(AssetGroup, stale_id)+ assert adopted is not None+ assert adopted.external_id == f"{conn.external_id}::acc-1"+ assert adopted.name == "My Retirement" # customization kept+ untouched = await session.get(AssetGroup, foreign_id)+ assert untouched is not None+ assert untouched.external_id == "old-bank-ext"+++async def test_sync_holdings_prefers_exact_key_match_over_stale_candidate(+ session: AsyncSession, test_user, test_workspace,+):+ """With the current-keyed legacy wallet AND a stale-keyed wallet both on+ the connection, the exact match wins — without the preference, two+ same-connection candidates would read as ambiguous and mint+ (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Exact Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Exact Bank", source="test",+ connection_id=conn_id, external_id=conn.external_id,+ )+ stale = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Leftover", source="test",+ connection_id=conn_id, external_id="stale-ext",+ )+ session.add_all([legacy, stale])+ await session.flush()+ legacy_id, stale_id = legacy.id, stale.id+ # An asset outside this payload keeps the stale wallet from the reap —+ # the point here is which candidate adoption picks, not the reap.+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="other-h",+ name="Other Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=stale_id,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ adopted = await session.get(AssetGroup, legacy_id)+ assert adopted is not None+ assert adopted.external_id == f"{conn.external_id}::acc-1"+ untouched = await session.get(AssetGroup, stale_id)+ assert untouched is not None+ assert untouched.external_id == "stale-ext"+++async def test_sync_holdings_keyless_reconnect_adopts_stale_wallet(+ session: AsyncSession, test_user, test_workspace,+):+ """Providers whose holdings carry no account hint (Pluggy) get the same+ adoption on reconnect: the customized wallet left on the old item id is+ re-keyed in place instead of being emptied into a fresh default wallet+ and reaped (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Keyless Bank")+ conn_id = conn.id++ wallet = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My Crypto", icon="bitcoin", source="test",+ connection_id=conn_id, external_id="old-item-id",+ )+ session.add(wallet)+ await session.flush()+ wallet_id = wallet.id+ asset = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-1",+ name="Bitcoin", type="investment", currency="USD",+ valuation_method="manual", group_id=wallet_id,+ )+ session.add(asset)+ await session.commit()+ asset_id = asset.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Bitcoin", currency="USD",+ current_value=Decimal("10"),+ ),+ ]+ for _ in range(2):+ with patch(+ "app.services.connection_service.get_provider", return_value=mock_provider+ ):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ adopted = await session.get(AssetGroup, wallet_id)+ assert adopted is not None+ assert adopted.external_id == conn.external_id # re-keyed to the new id+ assert adopted.connection_id == conn_id+ assert adopted.name == "My Crypto"+ assert adopted.icon == "bitcoin"+ kept = await session.get(Asset, asset_id)+ assert kept is not None+ assert kept.group_id == wallet_id+++async def test_sync_holdings_adoption_keeps_name_matching_account(+ session: AsyncSession, test_user, test_workspace,+):+ """When the account is named after the institution, the refreshed+ auto-name equals the wallet's current one — it must not count itself as+ taken and become "Vanguard 2" (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Vanguard")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="Vanguard",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ legacy = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Vanguard", source="test",+ connection_id=conn_id, external_id=conn.external_id,+ )+ session.add(legacy)+ await session.commit()+ legacy_id = legacy.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="Vanguard",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallet = await session.get(AssetGroup, legacy_id)+ assert wallet is not None+ assert wallet.name == "Vanguard"+++async def test_sync_holdings_reaps_emptied_unreferenced_wallet(+ session: AsyncSession, test_user, test_workspace,+):+ """The positive half of the reap: a sync-owned wallet emptied by+ re-attribution, tracked by no goal and in no collection, is deleted+ (review round 5 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Reap Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ # A per-account wallet of a since-removed account ("::"-keyed, so the+ # adoption path never claims it).+ old_wallet = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Closed Account", source="test",+ connection_id=conn_id, external_id=f"{conn.external_id}::acc-gone",+ )+ session.add(old_wallet)+ await session.flush()+ old_wallet_id = old_wallet.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=old_wallet_id,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ # The holding moved to a different account, emptying the old wallet.+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ assert await session.get(AssetGroup, old_wallet_id) is None+++async def test_sync_holdings_readopts_split_wallet_after_reconnect(+ session: AsyncSession, test_user, test_workspace,+):+ """The keys this PR itself writes must survive a delete/re-add cycle: an+ orphaned per-account wallet on an old connection prefix is matched by its+ "::{account}" suffix and re-keyed in place — not excluded, re-minted, and+ reaped (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Rotate Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ orphan = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My IRA", source="test",+ connection_id=None, external_id="old-conn-ext::acc-1",+ )+ session.add(orphan)+ await session.flush()+ orphan_id = orphan.id+ stranded = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=None, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=orphan_id, is_archived=True,+ )+ session.add(stranded)+ await session.commit()+ stranded_id = stranded.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallet = await session.get(AssetGroup, orphan_id)+ assert wallet is not None+ assert wallet.external_id == f"{conn.external_id}::acc-1"+ assert wallet.connection_id == conn_id+ assert wallet.name == "My IRA" # customization kept+ moved = await session.get(Asset, stranded_id)+ assert moved is not None+ assert moved.group_id == orphan_id+ assert moved.is_archived is False+++async def test_sync_holdings_rekeys_split_wallet_after_inplace_reconnect(+ session: AsyncSession, test_user, test_workspace,+):+ """A reconnect-in-place rotates connection.external_id but keeps the+ wallet linked; the suffix match re-keys it under the new prefix+ (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Inplace Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="401(k)",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ stale = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My 401k", icon="target", source="test",+ connection_id=conn_id, external_id="pre-rotation-ext::acc-1",+ )+ session.add(stale)+ await session.commit()+ stale_id = stale.id++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="401(k)",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ wallet = await session.get(AssetGroup, stale_id)+ assert wallet is not None+ assert wallet.external_id == f"{conn.external_id}::acc-1"+ assert wallet.name == "My 401k"+ assert wallet.icon == "target"+++async def test_sync_holdings_hint_loss_does_not_drain_split_wallets(+ session: AsyncSession, test_user, test_workspace,+):+ """One payload with the account ids missing must not empty the+ per-account wallets into the default bucket (the reap would then delete+ them); when the hints return, everything is back to steady state+ (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Hint Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ wallet = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My IRA", source="test",+ connection_id=conn_id, external_id=f"{conn.external_id}::acc-1",+ )+ session.add(wallet)+ await session.flush()+ wallet_id = wallet.id+ asset = Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=wallet_id,+ )+ session.add(asset)+ await session.commit()+ asset_id = asset.id++ degraded = AsyncMock()+ degraded.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=degraded):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ survivor = await session.get(AssetGroup, wallet_id)+ assert survivor is not None+ assert survivor.external_id == f"{conn.external_id}::acc-1"+ assert survivor.name == "My IRA"+ held = await session.get(Asset, asset_id)+ assert held is not None+ assert held.group_id == wallet_id # not drained into the default bucket++ healthy = AsyncMock()+ healthy.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("11"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=healthy):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ # Steady state restored: the per-account wallet still owns the asset and+ # the transient default wallet was reaped once emptied of purpose.+ held = await session.get(Asset, asset_id)+ assert held is not None+ assert held.group_id == wallet_id+ wallets = (+ await session.execute(select(AssetGroup).where(+ AssetGroup.user_id == test_user.id, AssetGroup.source == "test"))+ ).scalars().all()+ assert {w.external_id for w in wallets} == {f"{conn.external_id}::acc-1"}+++async def test_sync_holdings_new_account_first_keeps_default_wallet(+ session: AsyncSession, test_user, test_workspace,+):+ """Once per-account wallets exist, the plain-keyed wallet is the live+ connection-default — a new account's bucket running first must mint its+ own wallet, not adopt and re-key the default (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Grow Bank")+ conn_id = conn.id++ for ext, name in (("acc-1", "IRA"), ("acc-2", "Brokerage")):+ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id=ext, name=name,+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ split = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="IRA", source="test",+ connection_id=conn_id, external_id=f"{conn.external_id}::acc-1",+ )+ default = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Misc investments", source="test",+ connection_id=conn_id, external_id=conn.external_id,+ )+ session.add_all([split, default])+ await session.flush()+ split_id, default_id = split.id, default.id+ session.add_all([+ Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=split_id,+ ),+ Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-2",+ name="Mystery Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=default_id,+ ),+ ])+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ # The NEW account's holding arrives first.+ HoldingData(+ external_id="h-3", name="Tesla", currency="USD",+ current_value=Decimal("20"),+ account_external_id="acc-2", account_name="Brokerage",+ ),+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ HoldingData(+ external_id="h-2", name="Mystery Fund", currency="USD",+ current_value=Decimal("5"),+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ kept = await session.get(AssetGroup, default_id)+ assert kept is not None+ assert kept.external_id == conn.external_id # not hijacked by acc-2+ assert kept.name == "Misc investments"+ minted = await session.scalar(+ select(AssetGroup).where(+ AssetGroup.external_id == f"{conn.external_id}::acc-2")+ )+ assert minted is not None+ assert minted.id not in {split_id, default_id}+++async def test_sync_holdings_never_touches_another_workspaces_wallets(+ session: AsyncSession, test_user, test_workspace,+):+ """A sync stays inside its connection's workspace: another workspace's+ orphan wallet is not adopted, drained, or reaped even when its assets+ overlap the payload (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.models.workspace import Workspace, WorkspaceMember+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Scoped Bank")++ other_ws = Workspace(+ id=uuid.uuid4(), name="Elsewhere", kind="personal",+ created_by_user_id=test_user.id, default_currency="USD", locale="en-US",+ )+ session.add(other_ws)+ await session.flush()+ session.add(WorkspaceMember(+ id=uuid.uuid4(), workspace_id=other_ws.id,+ user_id=test_user.id, role="owner",+ ))+ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn.id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ foreign = AssetGroup(+ user_id=test_user.id, workspace_id=other_ws.id,+ name="Other Workspace Wallet", source="test",+ connection_id=None, external_id="old-ext",+ )+ session.add(foreign)+ await session.flush()+ foreign_id = foreign.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=other_ws.id,+ connection_id=None, source="test", external_id="h-1",+ name="Apple", type="investment", currency="USD",+ valuation_method="manual", group_id=foreign_id, is_archived=True,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ untouched = await session.get(AssetGroup, foreign_id)+ assert untouched is not None+ assert untouched.external_id == "old-ext"+ assert untouched.connection_id is None+ assert untouched.workspace_id == other_ws.id+ minted = await session.scalar(+ select(AssetGroup).where(+ AssetGroup.external_id == f"{conn.external_id}::acc-1")+ )+ assert minted is not None+ assert minted.workspace_id == test_workspace.id+ # The asset follows its connection into this workspace (leaving the+ # other workspace's wallet behind); it never straddles the two.+ moved = await session.scalar(select(Asset).where(Asset.external_id == "h-1"))+ assert moved is not None+ assert moved.workspace_id == test_workspace.id+ assert moved.group_id == minted.id+ assert moved.is_archived is False+++async def test_wallet_key_uniqueness_is_enforced_in_the_test_schema(+ session: AsyncSession, test_user, test_workspace,+):+ """The model mirrors migration 034's partial unique index so adoption+ guards are testable: duplicate keys raise, NULL keys don't+ (review round 6 on #654)."""+ from sqlalchemy.exc import IntegrityError++ from app.models.asset_group import AssetGroup++ user_id, ws_id = test_user.id, test_workspace.id+ session.add(AssetGroup(+ user_id=user_id, workspace_id=ws_id,+ name="First", source="test", external_id="dup-key",+ ))+ await session.commit()++ session.add(AssetGroup(+ user_id=user_id, workspace_id=ws_id,+ name="Second", source="test", external_id="dup-key",+ ))+ with pytest.raises(IntegrityError):+ await session.flush()+ await session.rollback()++ # The index is partial: NULL keys never collide.+ session.add_all([+ AssetGroup(+ user_id=user_id, workspace_id=ws_id,+ name="Manual A", source="test",+ ),+ AssetGroup(+ user_id=user_id, workspace_id=ws_id,+ name="Manual B", source="test",+ ),+ ])+ await session.commit()+++async def test_ensure_group_recovers_when_losing_the_mint_race(+ session: AsyncSession, test_user, test_workspace, monkeypatch,+):+ """When a concurrent sync mints the same wallet key between the lookup+ and the flush, the loser's IntegrityError is contained and the winner's+ row is returned (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.asset_group_service import ensure_group_for_connection++ conn = await _make_connection(session, test_user.id, "Race Bank")+ winner = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Winner", source="test",+ connection_id=conn.id, external_id="race-key",+ )+ session.add(winner)+ await session.commit()+ winner_id = winner.id++ real_execute = session.execute+ state = {"missed": False}++ class _Miss:+ def scalar_one_or_none(self):+ return None++ async def racing_execute(stmt, *args, **kwargs):+ # The first lookup misses — the winner's row lands "between" the+ # select and the flush, as a concurrent sync's commit would.+ if not state["missed"]:+ state["missed"] = True+ return _Miss()+ return await real_execute(stmt, *args, **kwargs)++ monkeypatch.setattr(session, "execute", racing_execute)+ group = await ensure_group_for_connection(+ session,+ user_id=test_user.id,+ connection_id=conn.id,+ source="test",+ external_id="race-key",+ default_name="Race Bank",+ )++ assert group.id == winner_id+++async def test_sync_holdings_survives_losing_the_adoption_rekey_race(+ session: AsyncSession, test_user, test_workspace, monkeypatch,+):+ """If a concurrent sync claims the wallet key while this one is+ adopting, the re-key's IntegrityError is contained: the candidate is+ left as it was and the winner's wallet is used+ (review round 6 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Adopt Race Bank")+ conn_id = conn.id+ other = await _make_connection(session, test_user.id, "Other Bank")++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ wallet_key = f"{conn.external_id}::acc-1"+ # The concurrent sync's wallet already owns the target key, but hangs+ # off a different connection so it is not an adoption candidate.+ twin = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Twin", source="test",+ connection_id=other.id, external_id=wallet_key,+ )+ # This sync's own stale candidate, picked via the suffix tier.+ stale = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My Stale", source="test",+ connection_id=conn_id, external_id="old-conn-ext::acc-1",+ )+ session.add_all([twin, stale])+ await session.flush()+ twin_id, stale_id = twin.id, stale.id+ # An asset outside the payload keeps the loser's wallet from the reap —+ # the point here is the contained IntegrityError, not the reap.+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="other-h",+ name="Other Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=stale_id,+ ))+ await session.commit()++ real_scalar = session.scalar+ state = {"missed": False}++ async def racing_scalar(stmt, *args, **kwargs):+ # Blind only the existence guard (its statement carries the exact+ # wallet key), simulating the winner committing after the check.+ params = stmt.compile().params if hasattr(stmt, "compile") else {}+ if not state["missed"] and wallet_key in params.values():+ state["missed"] = True+ return None+ return await real_scalar(stmt, *args, **kwargs)++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ monkeypatch.setattr(session, "scalar", racing_scalar)+ with patch(+ "app.services.connection_service.get_provider", return_value=mock_provider+ ):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ # The loser backed off: its candidate is untouched, the winner's wallet+ # owns the key (re-linked to this connection by the mint path).+ kept = await session.get(AssetGroup, stale_id)+ assert kept is not None+ assert kept.external_id == "old-conn-ext::acc-1"+ assert kept.name == "My Stale"+ winner = await session.get(AssetGroup, twin_id)+ assert winner is not None+ assert winner.external_id == wallet_key+ moved = await session.scalar(select(Asset).where(Asset.external_id == "h-1"))+ assert moved is not None+ assert moved.group_id == twin_id+++async def test_sync_holdings_keyless_bucket_adopts_default_after_rotation(+ session: AsyncSession, test_user, test_workspace,+):+ """After a reconnect rotates the connection key, the keyless bucket must+ still adopt the customized stale default wallet — pinned against+ recomputing the split snapshot per bucket, which would see the split+ wallet re-keyed earlier in the same run and mint instead+ (review round 7 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Rotated Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ split = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My IRA", source="test",+ connection_id=conn_id, external_id="old-ext::acc-1",+ )+ default = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My Misc", source="test",+ connection_id=conn_id, external_id="old-ext",+ )+ session.add_all([split, default])+ await session.flush()+ split_id, default_id = split.id, default.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-2",+ name="Mystery Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=default_id,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ # The keyed bucket runs first and re-keys the split wallet under+ # the new prefix — the pre-run snapshot must not see that.+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ HoldingData(+ external_id="h-2", name="Mystery Fund", currency="USD",+ current_value=Decimal("5"),+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ rekeyed = await session.get(AssetGroup, split_id)+ assert rekeyed is not None+ assert rekeyed.external_id == f"{conn.external_id}::acc-1"+ adopted = await session.get(AssetGroup, default_id)+ assert adopted is not None+ assert adopted.external_id == conn.external_id+ assert adopted.name == "My Misc"+ held = await session.scalar(select(Asset).where(Asset.external_id == "h-2"))+ assert held is not None+ assert held.group_id == default_id+++async def test_sync_holdings_new_account_after_rotation_mints_its_own_wallet(+ session: AsyncSession, test_user, test_workspace,+):+ """A genuinely new account appearing in the first post-rotation sync+ must mint — old-prefix split wallets prove the legacy era is over, so+ the stale default belongs to the keyless bucket, not the new account+ (review round 7 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Grown Bank")+ conn_id = conn.id++ for ext, name in (("acc-1", "IRA"), ("acc-2", "Brokerage")):+ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id=ext, name=name,+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ split = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="My IRA", source="test",+ connection_id=conn_id, external_id="old-ext::acc-1",+ )+ default = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Misc investments", source="test",+ connection_id=conn_id, external_id="old-ext",+ )+ session.add_all([split, default])+ await session.flush()+ split_id, default_id = split.id, default.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-2",+ name="Mystery Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=default_id,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ # The brand-new account's holding arrives first.+ HoldingData(+ external_id="h-3", name="Tesla", currency="USD",+ current_value=Decimal("20"),+ account_external_id="acc-2", account_name="Brokerage",+ ),+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ HoldingData(+ external_id="h-2", name="Mystery Fund", currency="USD",+ current_value=Decimal("5"),+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ kept = await session.get(AssetGroup, default_id)+ assert kept is not None+ assert kept.external_id == conn.external_id # adopted by the keyless bucket+ assert kept.name == "Misc investments"+ minted = await session.scalar(+ select(AssetGroup).where(+ AssetGroup.external_id == f"{conn.external_id}::acc-2")+ )+ assert minted is not None+ assert minted.id not in {split_id, default_id}+++async def test_sync_holdings_two_stale_generations_mean_minting(+ session: AsyncSession, test_user, test_workspace,+):+ """Two stale per-account wallets for the same account (two rotations)+ are ambiguous — mint rather than guess; neither is re-keyed+ (review round 7 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Twice Bank")+ conn_id = conn.id++ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id="acc-1", name="IRA",+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ gen1 = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Gen One", source="test",+ connection_id=conn_id, external_id="gen1-ext::acc-1",+ )+ gen2 = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Gen Two", source="test",+ connection_id=conn_id, external_id="gen2-ext::acc-1",+ )+ session.add_all([gen1, gen2])+ await session.flush()+ gen1_id, gen2_id = gen1.id, gen2.id+ for i, gid in enumerate((gen1_id, gen2_id)):+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id=f"keep-{i}",+ name="Keeper", type="investment", currency="USD",+ valuation_method="manual", group_id=gid,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ HoldingData(+ external_id="h-1", name="Apple", currency="USD",+ current_value=Decimal("10"),+ account_external_id="acc-1", account_name="IRA",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ for gid, ext in ((gen1_id, "gen1-ext::acc-1"), (gen2_id, "gen2-ext::acc-1")):+ wallet = await session.get(AssetGroup, gid)+ assert wallet is not None+ assert wallet.external_id == ext+ minted = await session.scalar(+ select(AssetGroup).where(+ AssetGroup.external_id == f"{conn.external_id}::acc-1")+ )+ assert minted is not None+ assert minted.id not in {gen1_id, gen2_id}+++async def test_sync_holdings_separator_in_account_id_cannot_steal_sibling_wallet(+ session: AsyncSession, test_user, test_workspace,+):+ """An account id ending in another account's id (ids may contain "::")+ must not suffix-match the sibling's live wallet — live-prefix wallets+ are never candidates, and a stale key must parse as exactly one+ "{prefix}::{key}" (review round 7 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.services.connection_service import _sync_holdings++ conn = await _make_connection(session, test_user.id, "Colon Bank")+ conn_id = conn.id++ for ext, name in (("a::b", "Joint"), ("b", "Solo")):+ session.add(Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, external_id=ext, name=name,+ type="investment", balance=Decimal("0"), currency="USD",+ ))+ joint = AssetGroup(+ user_id=test_user.id, workspace_id=test_workspace.id,+ name="Our Joint Account", source="test",+ connection_id=conn_id, external_id=f"{conn.external_id}::a::b",+ )+ session.add(joint)+ await session.flush()+ joint_id = joint.id+ session.add(Asset(+ user_id=test_user.id, workspace_id=test_workspace.id,+ connection_id=conn_id, source="test", external_id="h-joint",+ name="Joint Fund", type="investment", currency="USD",+ valuation_method="manual", group_id=joint_id,+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings.return_value = [+ # The new account whose id is the "::"-tail of its sibling's runs+ # first — the hostile ordering.+ HoldingData(+ external_id="h-solo", name="Solo Fund", currency="USD",+ current_value=Decimal("10"),+ account_external_id="b", account_name="Solo",+ ),+ HoldingData(+ external_id="h-joint", name="Joint Fund", currency="USD",+ current_value=Decimal("20"),+ account_external_id="a::b", account_name="Joint",+ ),+ ]+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "fake"})+ await session.commit()++ untouched = await session.get(AssetGroup, joint_id)+ assert untouched is not None+ assert untouched.external_id == f"{conn.external_id}::a::b"+ assert untouched.name == "Our Joint Account"+ solo = await session.scalar(+ select(AssetGroup).where(AssetGroup.external_id == f"{conn.external_id}::b")+ )+ assert solo is not None+ assert solo.id != joint_id+ held = await session.scalar(select(Asset).where(Asset.external_id == "h-joint"))+ assert held is not None+ assert held.group_id == joint_id+++async def test_ensure_group_relocates_wallet_when_connection_moves_workspaces(+ session: AsyncSession, test_user, test_workspace,+):+ """The wallet key is unique per (user, source) across workspaces, so a+ key match from another workspace means the bank moved — the wallet+ follows its connection instead of feeding data into a workspace the+ connection doesn't live in (review round 7 on #654)."""+ from app.models.asset_group import AssetGroup+ from app.models.workspace import Workspace, WorkspaceMember+ from app.services.asset_group_service import ensure_group_for_connection++ conn = await _make_connection(session, test_user.id, "Mover Bank")+ other_ws = Workspace(+ id=uuid.uuid4(), name="Old Home", kind="personal",+ created_by_user_id=test_user.id, default_currency="USD", locale="en-US",+ )+ session.add(other_ws)+ await session.flush()+ session.add(WorkspaceMember(+ id=uuid.uuid4(), workspace_id=other_ws.id,+ user_id=test_user.id, role="owner",+ ))+ stranded = AssetGroup(+ user_id=test_user.id, workspace_id=other_ws.id,+ name="Moved Wallet", source="test",+ connection_id=None, external_id="shared-key",+ )+ session.add(stranded)+ await session.commit()+ stranded_id = stranded.id++ group = await ensure_group_for_connection(+ session,+ user_id=test_user.id,+ connection_id=conn.id,+ source="test",+ external_id="shared-key",+ default_name="Mover Bank",+ workspace_id=test_workspace.id,+ )++ assert group.id == stranded_id+ assert group.connection_id == conn.id+ assert group.workspace_id == test_workspace.id+ assert group.name == "Moved Wallet"diff --git a/backend/tests/test_providers_simplefin.py b/backend/tests/test_providers_simplefin.pyindex 2837c90b..6dd00b41 100644--- a/backend/tests/test_providers_simplefin.py+++ b/backend/tests/test_providers_simplefin.py@@ -518,3 +518,128 @@ def test_flow_type_is_token():def test_get_oauth_url_raises_for_token_flow():with pytest.raises(NotImplementedError):SimpleFinProvider().get_oauth_url("https://x", "state")+++# ----- multi-institution payloads (issue #345) --------------------------------+++def test_parse_accounts_maps_each_account_to_its_own_institution():+ """connections[] entries are matched to accounts by conn_id, so a Setup+ Token spanning several institutions labels each account with its own."""+ payload = {+ "connections": [+ {"conn_id": "CON-1", "name": "First Bank", "org_url": "https://first.example"},+ {"conn_id": "CON-2", "name": "Second Brokerage", "org_url": "https://second.example"},+ ],+ "accounts": [+ {"id": "a1", "name": "Checking", "currency": "USD", "balance": "10", "conn_id": "CON-1"},+ {"id": "a2", "name": "IRA", "currency": "USD", "balance": "20", "conn_id": "CON-2"},+ {"id": "a3", "name": "Orphan", "currency": "USD", "balance": "30"},+ ],+ }++ institution_name, accounts = SimpleFinProvider._parse_accounts(payload)++ # Connection-level name keeps the previous first-entry behavior.+ assert institution_name == "First Bank"+ by_id = {a.external_id: a for a in accounts}+ assert by_id["a1"].institution_name == "First Bank"+ assert by_id["a1"].institution_external_id == "CON-1"+ assert "first.example" in (by_id["a1"].institution_logo_url or "")+ assert by_id["a2"].institution_name == "Second Brokerage"+ assert by_id["a2"].institution_external_id == "CON-2"+ assert "second.example" in (by_id["a2"].institution_logo_url or "")+ # No conn_id → no per-account institution; serialize falls back to the connection.+ assert by_id["a3"].institution_name is None+ assert by_id["a3"].institution_external_id is None+ assert by_id["a3"].institution_logo_url is None+++def test_parse_accounts_connection_without_name_or_url_is_harmless():+ """A nameless connections[] entry is skipped; a named one without a URL+ yields a name but no logo."""+ payload = {+ "connections": [+ {"conn_id": "CON-1"},+ {"conn_id": "CON-2", "name": "Bare Bank"},+ ],+ "accounts": [+ {"id": "a1", "name": "A", "currency": "USD", "balance": "1", "conn_id": "CON-1"},+ {"id": "a2", "name": "B", "currency": "USD", "balance": "2", "conn_id": "CON-2"},+ ],+ }++ _, accounts = SimpleFinProvider._parse_accounts(payload)+ by_id = {a.external_id: a for a in accounts}+ assert by_id["a1"].institution_name is None+ assert by_id["a2"].institution_name == "Bare Bank"+ assert by_id["a2"].institution_logo_url is None+++def test_parse_accounts_falls_back_to_account_org_object():+ """Spec-style servers attach an ``org`` object per account instead of a+ top-level connections[]; the feature still works there (review on #654)."""+ payload = {+ "accounts": [+ {+ "id": "a1", "name": "Checking", "currency": "USD", "balance": "10",+ "org": {"name": "Org Bank", "domain": "orgbank.example", "id": "ORG-1"},+ },+ {+ "id": "a2", "name": "Savings", "currency": "USD", "balance": "20",+ "org": {"domain": "nameless.example"},+ },+ ],+ }++ _, accounts = SimpleFinProvider._parse_accounts(payload)+ by_id = {a.external_id: a for a in accounts}+ assert by_id["a1"].institution_name == "Org Bank"+ assert by_id["a1"].institution_external_id == "ORG-1"+ assert "orgbank.example" in (by_id["a1"].institution_logo_url or "")+ # A nameless org still identifies the bank by domain.+ assert by_id["a2"].institution_name == "nameless.example"+ assert by_id["a2"].institution_external_id == "nameless.example"+ assert "nameless.example" in (by_id["a2"].institution_logo_url or "")+++async def test_get_holdings_carries_the_owning_account():+ """Each holding is stamped with its owning account so the sync can build+ one wallet per investment account (issue #345)."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "accounts": [+ {+ "id": "acc-1",+ "name": "Employer 401(k)",+ "currency": "USD",+ "holdings": [+ {"id": "h-1", "description": "Apple", "symbol": "AAPL",+ "market_value": "10.00", "shares": "1"},+ ],+ },+ {+ "id": "acc-2",+ "name": "Rollover IRA",+ "currency": "USD",+ "holdings": [+ {"id": "h-2", "description": "Bonds", "symbol": "BND",+ "market_value": "5.00", "shares": "1"},+ ],+ },+ ],+ },+ )++ creds = {"access_url": "https://u:[email protected]/simplefin"}+ with _patched_client(handler):+ holdings = await SimpleFinProvider().get_holdings(creds)+ by_id = {h.external_id: h for h in holdings}+ assert by_id["h-1"].account_external_id == "acc-1"+ assert by_id["h-1"].account_name == "Employer 401(k)"+ assert by_id["h-2"].account_external_id == "acc-2"+ assert by_id["h-2"].account_name == "Rollover IRA"diff --git a/backend/tests/test_sync_holdings.py b/backend/tests/test_sync_holdings.pyindex 5679aa54..f55135c2 100644--- a/backend/tests/test_sync_holdings.py+++ b/backend/tests/test_sync_holdings.py@@ -1,10 +1,13 @@"""Cover the Asset lifecycle through `_sync_holdings`.The sync contract is a bit subtle: provider data drives creation *and*-closure of Assets, but user-set fields (sell_date, group_id) are load--bearing and must never be overwritten. These tests pin the full matrix:-new/existing × active/withdrawn, same-day vs next-day re-syncs,-historical seeding idempotency, and sparse-field merging.+closure of Assets, but user-set fields are load-bearing — sell_date is+never overwritten, and group_id is rewritten only between wallets the+sync itself owns (per-account re-attribution, issue #345); a wallet the+user chose is never touched (see test_connection_service.py for the+re-attribution matrix). These tests pin the rest: new/existing ×+active/withdrawn, same-day vs next-day re-syncs, historical seeding+idempotency, and sparse-field merging."""from __future__ import annotationsdiff --git a/frontend/src/lib/connection-utils.test.ts b/frontend/src/lib/connection-utils.test.tsnew file mode 100644index 00000000..080a8c83--- /dev/null+++ b/frontend/src/lib/connection-utils.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest'+import { getConnectionName } from './connection-utils'++const t = (key: string, opts?: Record<string, unknown>) =>+ `${key}:${opts?.provider}:${opts?.count}`++describe('getConnectionName', () => {+ it('a user rename always wins', () => {+ expect(+ getConnectionName(+ {+ provider: 'simplefin',+ institution_name: 'First Bank',+ display_name: 'My Banks',+ institutions: [{ name: 'First Bank' }, { name: 'Second Brokerage' }],+ },+ t,+ ),+ ).toBe('My Banks')+ })++ it('labels a multi-institution link by its provider, not one bank', () => {+ expect(+ getConnectionName(+ {+ provider: 'simplefin',+ institution_name: 'First Bank',+ institutions: [{ name: 'First Bank' }, { name: 'Second Brokerage' }],+ },+ t,+ ),+ ).toBe('accounts.multiInstitutionLink:SimpleFIN:2')+ })++ it('falls back to the raw provider key when unmapped', () => {+ expect(+ getConnectionName(+ {+ provider: 'newprovider',+ institution_name: 'X',+ institutions: [{ name: 'A' }, { name: 'B' }],+ },+ t,+ ),+ ).toBe('accounts.multiInstitutionLink:newprovider:2')+ })++ it('a single-institution link shows that institution', () => {+ expect(+ getConnectionName(+ { provider: 'simplefin', institution_name: 'Old Label', institutions: [{ name: 'First Bank' }] },+ t,+ ),+ ).toBe('First Bank')+ })++ it('no institutions falls back to the connection label (Pluggy/Enable)', () => {+ expect(+ getConnectionName({ provider: 'pluggy', institution_name: 'Nubank', institutions: [] }, t),+ ).toBe('Nubank')+ expect(getConnectionName({ institution_name: 'Nubank' }, t)).toBe('Nubank')+ })+})diff --git a/frontend/src/lib/connection-utils.ts b/frontend/src/lib/connection-utils.tsindex 4a96e793..5d806b6f 100644--- a/frontend/src/lib/connection-utils.ts+++ b/frontend/src/lib/connection-utils.ts@@ -1,3 +1,26 @@-export function getConnectionName(connection: { institution_name: string; display_name?: string | null }): string {- return connection.display_name ?? connection.institution_name+// Provider proper names — product names, not translated.+const PROVIDER_LABELS: Record<string, string> = {+ simplefin: 'SimpleFIN',+ pluggy: 'Pluggy',+ enable_banking: 'Enable Banking',+}++export function getConnectionName(+ connection: {+ provider?: string+ institution_name: string+ display_name?: string | null+ institutions?: { name: string }[]+ },+ t: (key: string, opts?: Record<string, unknown>) => string,+): string {+ if (connection.display_name) return connection.display_name+ const insts = connection.institutions ?? []+ // A link spanning several institutions (SimpleFIN — issue #345) is labeled+ // by the provider it runs through, not by one arbitrary bank out of many.+ if (insts.length > 1) {+ const provider = PROVIDER_LABELS[connection.provider ?? ''] ?? connection.provider ?? ''+ return t('accounts.multiInstitutionLink', { provider, count: insts.length })+ }+ return insts[0]?.name ?? connection.institution_name}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 287a866c..b154eae4 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Gib den Betrag, den du dieser Karte aktuell schuldest, als positiven Wert ein. Lasse das Feld auf 0, wenn du keine Schulden hast.","balanceDate": "Saldodatum","lastSync": "Letzte Synchr.",+ "multiInstitutionLink_one": "{{provider}} · {{count}} Institut",+ "multiInstitutionLink_other": "{{provider}} · {{count}} Institute","sync": "Synchronisieren","disconnect": "Trennen","addManual": "Konto hinzufügen",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 0d9c698e..2c9515a4 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -565,6 +565,7 @@"balanceCreditCardHint": "Enter how much you currently owe on this card as a positive number. Leave at 0 if you have no debt.","balanceDate": "Balance date","lastSync": "Last sync",+ "multiInstitutionLink": "{{provider}} · {{count}} institutions","sync": "Sync","disconnect": "Disconnect","addManual": "Add Account",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex e34f7f9c..d9d1c0e2 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Introduce cuánto debes actualmente en esta tarjeta como un número positivo. Déjalo en 0 si no tienes deuda.","balanceDate": "Fecha de saldo","lastSync": "Última sincronización",+ "multiInstitutionLink_one": "{{provider}} · {{count}} institución",+ "multiInstitutionLink_other": "{{provider}} · {{count}} instituciones","sync": "Sincronizar","disconnect": "Desconectar","addManual": "Agregar cuenta",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 349a66c7..c31bbdcc 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Saisissez le montant que vous devez actuellement sur cette carte, sous forme de nombre positif. Laissez à 0 si vous n'avez pas de dette.","balanceDate": "Date du solde","lastSync": "Dernière synchronisation",+ "multiInstitutionLink_one": "{{provider}} · {{count}} établissement",+ "multiInstitutionLink_other": "{{provider}} · {{count}} établissements","sync": "Synchroniser","disconnect": "Déconnecter","addManual": "Ajouter un compte",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 130cf029..660187e8 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Inserisci quanto devi attualmente su questa carta come numero positivo. Lascia 0 se non hai debiti.","balanceDate": "Data del saldo","lastSync": "Ultima sincronizzazione",+ "multiInstitutionLink_one": "{{provider}} · {{count}} istituto",+ "multiInstitutionLink_other": "{{provider}} · {{count}} istituti","sync": "Sincronizza","disconnect": "Disconnetti","addManual": "Aggiungi conto",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex a1586802..106bb3cf 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Voer in een positief getal in hoeveel u momenteel op deze kaart verschuldigd bent. Laat op 0 staan als u geen schulden heeft.","balanceDate": "Saldodatum","lastSync": "Laatste synchronisatie",+ "multiInstitutionLink_one": "{{provider}} · {{count}} instelling",+ "multiInstitutionLink_other": "{{provider}} · {{count}} instellingen","sync": "Synchroniseren","disconnect": "Verbreek de verbinding","addManual": "Account toevoegen",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex d3217edf..97e7db50 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -598,6 +598,10 @@"balanceCreditCardHint": "Wpisz, ile aktualnie jesteś winien na tej karcie, jako liczbę dodatnią. Zostaw 0, jeśli nie masz zadłużenia.","balanceDate": "Data salda","lastSync": "Ostatnia synchronizacja",+ "multiInstitutionLink_one": "{{provider}} · {{count}} instytucja",+ "multiInstitutionLink_few": "{{provider}} · {{count}} instytucje",+ "multiInstitutionLink_many": "{{provider}} · {{count}} instytucji",+ "multiInstitutionLink_other": "{{provider}} · {{count}} instytucji","sync": "Synchronizuj","disconnect": "Odłącz","addManual": "Dodaj konto",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 5564ca1a..b069eb33 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Informe quanto você deve atualmente neste cartão como um valor positivo. Deixe em 0 se não houver dívida.","balanceDate": "Data do saldo","lastSync": "Última sincronização",+ "multiInstitutionLink_one": "{{provider}} · {{count}} instituição",+ "multiInstitutionLink_other": "{{provider}} · {{count}} instituições","sync": "Sincronizar","disconnect": "Desconectar","addManual": "Adicionar Conta",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 3ec00066..9063055f 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -565,6 +565,8 @@"balanceCreditCardHint": "Indica quanto deves atualmente neste cartão como um valor positivo. Deixa em 0 se não houver dívida.","balanceDate": "Data do saldo","lastSync": "Última sincronização",+ "multiInstitutionLink_one": "{{provider}} · {{count}} instituição",+ "multiInstitutionLink_other": "{{provider}} · {{count}} instituições","sync": "Sincronizar","disconnect": "Desconectar","addManual": "Adicionar Conta",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 5c3bb8a9..cab43ee2 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -571,6 +571,10 @@"balanceCreditCardHint": "Введите положительное число — сколько вы должны по этой карте. Оставьте 0, если долга нет.","balanceDate": "Дата баланса","lastSync": "Последняя синхронизация",+ "multiInstitutionLink_one": "{{provider}} · {{count}} учреждение",+ "multiInstitutionLink_few": "{{provider}} · {{count}} учреждения",+ "multiInstitutionLink_many": "{{provider}} · {{count}} учреждений",+ "multiInstitutionLink_other": "{{provider}} · {{count}} учреждения","sync": "Синхронизировать","disconnect": "Отключить","addManual": "Добавить счёт",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex d3936d76..a6e5d5de 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -571,6 +571,10 @@"balanceCreditCardHint": "Введіть додатне число — скільки ви винні за цією карткою. Залиште 0, якщо боргу немає.","balanceDate": "Дата балансу","lastSync": "Остання синхронізація",+ "multiInstitutionLink_one": "{{provider}} · {{count}} установа",+ "multiInstitutionLink_few": "{{provider}} · {{count}} установи",+ "multiInstitutionLink_many": "{{provider}} · {{count}} установ",+ "multiInstitutionLink_other": "{{provider}} · {{count}} установи","sync": "Синхронізувати","disconnect": "Відключити","addManual": "Додати рахунок",diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex e0276a70..2a283c2a 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -319,10 +319,14 @@ export default function AccountsPage() {{/* Connection header */}<div className="flex items-center justify-between px-5 py-3.5 border-b border-border"><div className="flex items-center gap-3">- <ConnectionLogo logoUrl={conn.logo_url} />+ {/* One bank's favicon would misrepresent a multi-+ institution link — fall back to the generic icon. */}+ <ConnectionLogo+ logoUrl={(conn.institutions?.length ?? 0) > 1 ? null : conn.logo_url}+ /><div><div className="flex items-center gap-2">- <p className="text-sm font-semibold text-foreground">{getConnectionName(conn)}</p>+ <p className="text-sm font-semibold text-foreground">{getConnectionName(conn, t)}</p><Badgevariant={conn.status === 'active' ? 'default' : 'secondary'}className={@@ -525,7 +529,7 @@ export default function AccountsPage() {<DialogTitle>{t('accounts.confirmDisconnectTitle')}</DialogTitle></DialogHeader><p className="text-sm text-muted-foreground">- {t('accounts.confirmDisconnectDesc', { institution: disconnectingConnection ? getConnectionName(disconnectingConnection) : '' })}+ {t('accounts.confirmDisconnectDesc', { institution: disconnectingConnection ? getConnectionName(disconnectingConnection, t) : '' })}</p><DialogFooter><Button variant="outline" onClick={() => setDisconnectingConnection(null)}>diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 18fa4c68..cc819180 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -117,6 +117,11 @@ export interface CategoryGroup {categories: Category[]}+export interface ConnectionInstitution {+ name: string+ logo_url: string | null+}+export interface BankConnection {id: stringuser_id: string@@ -129,6 +134,9 @@ export interface BankConnection {settings: ConnectionSettings | nulllast_sync_at: string | nullcreated_at: string+ // Institutions this link spans (issue #345). Empty for one-institution+ // providers — institution_name covers those.+ institutions: ConnectionInstitution[]}export interface ConnectionSettings {