resolver: an organisation name shared by several records no longer creates another one

When an alias matched more than one organisation, the lookup gave up and the loader created a new record,
which made the name match three next time. A reparse of rtr.medientransparenz (2026-11-20) turned this into
41 duplicate organisations and 3,600 duplicate money flows. pick_org now chooses the exact name, then the same
kind, then the oldest record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
simonandClaude Opus 5.5 committed 2026-11-20 10:35:01 +01:00
1 parent 9f0e2fc115
commit 8e16c01634
2 files changed
+27 -1

No files matched your search

+16 -1
View File
@@ -30,6 +30,13 @@ OFFICE_FILLER = re.compile(r"\b(der republik osterreich|der bundesrepublik oster
r"\(osterreich\)") r"\(osterreich\)")
def pick_org(candidates: list[dict], label: str, kind: str | None) -> int:
"""Tie-break between organisations sharing an alias: the exact name first, then the same kind, then the oldest."""
exact = normalize(label)
return min(candidates, key=lambda o: (normalize(o["name"] or "") != exact, bool(kind) and o["kind"] != kind,
o["id"]))["id"]
def name_parts(name: str) -> tuple[str, str]: def name_parts(name: str) -> tuple[str, str]:
"""'Mag. Chiara-Sophia Glawogger' -> ('chiara', 'glawogger'): first given name and surname, normalised.""" """'Mag. Chiara-Sophia Glawogger' -> ('chiara', 'glawogger'): first given name and surname, normalised."""
tokens = normalize(strip_titles(name)).replace(",", " ").split() tokens = normalize(strip_titles(name)).replace(",", " ").split()
@@ -293,16 +300,24 @@ class Resolver:
row = self.conn.execute("SELECT id FROM organization WHERE slug = %s", (ref.slug,)).fetchone() row = self.conn.execute("SELECT id FROM organization WHERE slug = %s", (ref.slug,)).fetchone()
if row: if row:
return row["id"] return row["id"]
ambiguous: set[int] = set()
for label in (ref.short_name, ref.name): for label in (ref.short_name, ref.name):
if not label: if not label:
continue continue
for norm in {normalize(label), normalize_org_name(label)} - {""}: for norm in sorted({normalize(label), normalize_org_name(label)} - {""}):
rows = self.conn.execute( rows = self.conn.execute(
"SELECT DISTINCT entity_id FROM alias WHERE entity_type = 'organization' AND alias_norm = %s", "SELECT DISTINCT entity_id FROM alias WHERE entity_type = 'organization' AND alias_norm = %s",
(norm,), (norm,),
).fetchall() ).fetchall()
if len(rows) == 1: if len(rows) == 1:
return rows[0]["entity_id"] return rows[0]["entity_id"]
ambiguous.update(r["entity_id"] for r in rows)
if ambiguous:
# Several organisations share the name ("Tiroler Tageszeitung" / "Tiroler Tageszeitung GmbH"). Creating
# another one would only add a third; pick one deterministically instead.
candidates = self.conn.execute("SELECT id, name, kind FROM organization WHERE id = ANY(%s)",
(sorted(ambiguous),)).fetchall()
return pick_org(candidates, ref.name or ref.short_name or "", ref.kind)
return None return None
def _org_create(self, ref: OrgRef) -> int: def _org_create(self, ref: OrgRef) -> int:
+11
View File
@@ -127,3 +127,14 @@ def test_office_portfolios_for_colloquial_labels():
economy = office_key("Bundesminister für Wirtschaft, Energie und Tourismus") economy = office_key("Bundesminister für Wirtschaft, Energie und Tourismus")
climate = office_key("Federal Minister for Climate Action, Environment, Energy, Mobility, Innovation and Technology") climate = office_key("Federal Minister for Climate Action, Environment, Energy, Mobility, Innovation and Technology")
assert lead_portfolio(economy) == "wirtschaft" and lead_portfolio(economy) not in portfolios(climate) assert lead_portfolio(economy) == "wirtschaft" and lead_portfolio(economy) not in portfolios(climate)
def test_ambiguous_organisation_names_resolve_to_one_existing_record():
from politrack.core.resolve import pick_org
twins = [{"id": 1292, "name": "Tiroler Tageszeitung GmbH", "kind": "company"},
{"id": 10562, "name": "Tiroler Tageszeitung", "kind": "media"},
{"id": 37042, "name": "Tiroler Tageszeitung", "kind": "media"}]
assert pick_org(twins, "Tiroler Tageszeitung", "media") == 10562 # exact name, then the oldest
assert pick_org(twins, "Tiroler Tageszeitung GmbH", None) == 1292
assert pick_org([{"id": 5, "name": "A GmbH", "kind": "company"}, {"id": 3, "name": "A AG", "kind": "public_body"}],
"A", "public_body") == 3