feat(search): add exact company aliases
Embed a versioned local alias overlay and rank exact aliases before legal-name matches and word prefixes. Normalize Unicode consistently, deduplicate by company identity before limiting, and update bilingual search guidance and tests. Refs #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -6,7 +6,7 @@ Source officielle : <https://github.com/JerBouma/FinanceDatabase/tree/93b872f0e4
|
||||
|
||||
Le fichier est complet, mais ne représente pas 47 735 sociétés identifiables distinctes : 2 423 lignes n'ont ni ISIN ni FIGI et 2 184 identités ont plusieurs lignes déjà classées primaires par l'amont. Le port expose **43 126 identités** (`isin:` en priorité, sinon `figi:`). Pour une identité répétée, il retient le meilleur `listing_score` amont ; une égalité entre primaires est départagée par symbole dans un ordre stable, uniquement pour choisir un représentant déterministe. Les lignes sans identité restent dans le snapshot mais sont exclues de la recherche et de la résolution. Aucune identité artificielle n'est inventée. Les valeurs exactes NVDA, AAPL, 9888.HK, 002594.SZ et 0285.HK sont vérifiées, avec BYD Company et BYD Electronic distincts.
|
||||
|
||||
Le manifeste précise provenance, champs, décompte, SHA-256 du parquet amont et du CSV, empreintes des sources Python utilisées et politique de résolution. Le chargement embarqué vérifie son empreinte avant utilisation. La recherche locale porte sur le nom (casse et espaces normalisés), avec ordre nom/identité stable et limite après déduplication ; aucun appel fournisseur n'est nécessaire. Le DTO de recherche ne projette que `company_id`, `name`, `exchange`, `country`, `mic`.
|
||||
Le manifeste précise provenance, champs, décompte, SHA-256 du parquet amont et du CSV, empreintes des sources Python utilisées et politique de résolution. Le chargement embarqué vérifie son empreinte avant utilisation. La recherche locale classe les alias exacts en premier, les noms légaux exacts ensuite, puis les préfixes de mots du nom légal. Les alias ne sont jamais recherchés par sous-chaîne ou préfixe. La déduplication par `company_id` précède la limite (maximum 20), et les collisions d’alias retournent tous les candidats dans cette limite, sans choix arbitraire d’identité. À rang égal, le tri utilise le nom légal normalisé puis `company_id`. Aucun appel fournisseur n’est nécessaire. Le DTO de recherche ne projette que `company_id`, `name`, `exchange`, `country`, `mic`.
|
||||
|
||||
## Reproduire ou mettre à jour explicitement
|
||||
|
||||
@ -28,3 +28,14 @@ cmp backend/internal/companycatalog/data/equities_primary.csv "$TMPDIR/company-c
|
||||
```
|
||||
|
||||
Le sélectionneur utilise uniquement les fichiers locaux et refuse les connexions Python pendant la sélection. Les sources et le parquet sont vérifiés avant export. Pour changer de commit, revoir explicitement les empreintes attendues (`company-catalog-upstream.json`), les versions Python, constantes, effectifs, identités cibles et tests ; puis régénérer et faire valider par QA. Il n'existe aucun rafraîchissement automatique. Ne pas lancer cet outil pendant les tests ou au démarrage de l'application.
|
||||
|
||||
|
||||
## Alias internes versionnés — ticket 24
|
||||
|
||||
`data/aliases.v1.json` est un overlay local séparé du CSV et de son manifeste de provenance. Il est embarqué avec le binaire, chargé uniquement par le catalogue par défaut et n’est ni enrichi depuis le réseau ni persistant en DB. L’exporteur FinanceDatabase ne le remplace pas. Le schéma version 1 contient des entrées `{alias, company_ids}` : plusieurs IDs par alias sont permis, avec regroupement des variantes normalisées et suppression des doublons. Tous les IDs doivent exister dans le snapshot ; une référence obsolète ou un fichier invalide fait échouer le chargement complet, sans application partielle.
|
||||
|
||||
Les deux associations initiales sont vérifiées dans le CSV réel : IBM → `isin:US4592001014` / International Business Machines Corporation ; Intel → `isin:US4581401001` / Intel Corporation. Elles ne changent ni les noms affichés, ni les IDs, ni les symboles internes, ni le DTO public. Les alias eux-mêmes restent internes.
|
||||
|
||||
La normalisation commune aux requêtes, alias et noms légaux applique la casse minuscule, la décomposition Unicode NFKD, le retrait des accents combinants et la réduction des espaces. Les points d’abréviation et apostrophes sont retirés (`I.B.M.` → `ibm`), les autres ponctuations séparent les mots (`Intel-Corporation` → `intel corporation`). Les symboles mathématiques/monétaires restent littéraux : `ES=F` ne doit pas devenir une requête générique « es f ». La chaîne originale d’affichage est conservée. Un préfixe légal commence à une frontière de mot ; il ne cherche pas à l’intérieur d’un mot et ne réordonne pas les mots.
|
||||
|
||||
Pour maintenir les alias, modifier uniquement l’overlay et ses tests après vérification des identités locales. Après mise à jour du snapshot, valider toutes les références d’alias avant livraison. Les chargements de petits CSV de test via `NewFinanceDatabaseCatalogFromSnapshot` n’appliquent pas automatiquement l’overlay de production : ils ne contiennent pas nécessairement ses identités cibles.
|
||||
|
||||
146
backend/internal/companycatalog/aliases_ticket24_test.go
Normal file
146
backend/internal/companycatalog/aliases_ticket24_test.go
Normal file
@ -0,0 +1,146 @@
|
||||
package companycatalog
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket24RealSnapshotFindsIBMAndIntelFirst(t *testing.T) {
|
||||
catalog, err := Default()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct{ query, id, name, symbol string }{
|
||||
{"IBM", "isin:US4592001014", "International Business Machines Corporation", "IBM"},
|
||||
{"Intel", "isin:US4581401001", "Intel Corporation", "INTC"},
|
||||
{" ÍNTÈL. ", "isin:US4581401001", "Intel Corporation", "INTC"},
|
||||
{"I.B.M.", "isin:US4592001014", "International Business Machines Corporation", "IBM"},
|
||||
} {
|
||||
t.Run(tc.query, func(t *testing.T) {
|
||||
canonical, err := catalog.ResolveCompany(tc.id)
|
||||
if err != nil || canonical.Name != tc.name || canonical.YahooSymbol != tc.symbol {
|
||||
t.Fatalf("local identity mismatch %+v %v", canonical, err)
|
||||
}
|
||||
got, err := catalog.SearchCompanies(tc.query, 1)
|
||||
if err != nil || len(got) != 1 || got[0].CompanyID != tc.id || got[0].Name != tc.name {
|
||||
t.Fatalf("query=%q got=%+v err=%v", tc.query, got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestTicket24LegalWordPrefixKeepsUsefulSearchWithoutInteriorSubstring(t *testing.T) {
|
||||
c := &Catalog{companies: []Company{{CompanyID: "isin:1", Name: "International Business Machines Corporation"}, {CompanyID: "isin:2", Name: "Intel Corporation"}, {CompanyID: "isin:3", Name: "Société Générale"}}}
|
||||
for _, tc := range []struct{ q, id string }{
|
||||
{"Business Mach", "isin:1"}, {"international-business machines", "isin:1"},
|
||||
{"INTEL CORPORATION.", "isin:2"}, {"societe ge\u0301ne\u0301rale", "isin:3"},
|
||||
} {
|
||||
got, err := c.SearchCompanies(tc.q, 20)
|
||||
if err != nil || len(got) != 1 || got[0].CompanyID != tc.id {
|
||||
t.Fatalf("query=%q got=%+v err=%v", tc.q, got, err)
|
||||
}
|
||||
}
|
||||
got, err := c.SearchCompanies("ternational", 20)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("interior substring returned %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket24AliasesAreExactOnly(t *testing.T) {
|
||||
catalog, err := Default()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, query := range []string{"IB", "BM", "some IBM company"} {
|
||||
got, err := catalog.SearchCompanies(query, 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, company := range got {
|
||||
if company.CompanyID == "isin:US4592001014" {
|
||||
t.Fatalf("non-exact alias %q matched IBM", query)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A legal prefix still works independently of aliases.
|
||||
isolated := &Catalog{companies: []Company{{CompanyID: "isin:ibm", Name: "International Business Machines Corporation"}}}
|
||||
got, err := isolated.SearchCompanies("Internation", 20)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("legal prefix lost %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket24SameTierOrderingUsesNormalizedLegalNameThenIdentity(t *testing.T) {
|
||||
c := &Catalog{companies: []Company{{CompanyID: "isin:z", Name: "Élite Corporation"}, {CompanyID: "isin:b", Name: "Elite Corporation"}, {CompanyID: "isin:a", Name: "Élite Corporation"}, {CompanyID: "isin:x", Name: "Alpha Elite Services"}}}
|
||||
got, err := c.SearchCompanies("Elite", 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids := []string{}
|
||||
for _, company := range got {
|
||||
ids = append(ids, company.CompanyID)
|
||||
}
|
||||
if !reflect.DeepEqual(ids, []string{"isin:x", "isin:a", "isin:b", "isin:z"}) {
|
||||
t.Fatalf("unstable normalized order: %v", ids)
|
||||
}
|
||||
if strings.Contains(normalizeName("Société"), "é") {
|
||||
t.Fatal("accents not normalized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket24AliasCollisionPriorityAndDeduplicationBeforeLimit(t *testing.T) {
|
||||
companies := []Company{{CompanyID: "isin:z", Name: "Zeta Holdings"}, {CompanyID: "isin:a", Name: "Alias First Holdings"}, {CompanyID: "isin:legal", Name: "Alpha"}, {CompanyID: "isin:prefix", Name: "Alpha Ventures"}}
|
||||
c := &Catalog{byID: map[string]Company{}}
|
||||
for _, company := range companies {
|
||||
c.byID[company.CompanyID] = company
|
||||
c.companies = append(c.companies, company, company)
|
||||
}
|
||||
data := []byte(`{"version":1,"aliases":[{"alias":"Alpha","company_ids":["isin:z","isin:a","isin:a"]},{"alias":" ÁLPHA! ","company_ids":["isin:z"]}]}`)
|
||||
if err := c.loadAliases(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
limit int
|
||||
want []string
|
||||
}{{1, []string{"isin:a"}}, {2, []string{"isin:a", "isin:z"}}, {3, []string{"isin:a", "isin:z", "isin:legal"}}, {20, []string{"isin:a", "isin:z", "isin:legal", "isin:prefix"}}} {
|
||||
for repeat := 0; repeat < 3; repeat++ {
|
||||
got, err := c.SearchCompanies("alpha", tc.limit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids := []string{}
|
||||
for _, company := range got {
|
||||
ids = append(ids, company.CompanyID)
|
||||
}
|
||||
if !reflect.DeepEqual(ids, tc.want) {
|
||||
t.Fatalf("limit=%d ids=%v want=%v", tc.limit, ids, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Prefix matching applies to legal names, never to the alias dictionary.
|
||||
got, err := c.SearchCompanies("Alph", 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0].CompanyID != "isin:legal" || got[1].CompanyID != "isin:prefix" {
|
||||
t.Fatalf("alias prefix leaked: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket24RejectsInvalidAliasFilesWithoutPartialApplication(t *testing.T) {
|
||||
c := &Catalog{byID: map[string]Company{"isin:1": {CompanyID: "isin:1", Name: "Legal Name"}}}
|
||||
for _, data := range []string{
|
||||
`{"version":2,"aliases":[]}`,
|
||||
`{"version":1,"aliases":[{"alias":"Known","company_ids":["isin:1"]},{"alias":"Unknown","company_ids":["isin:missing"]}]}`,
|
||||
`{"version":1,"aliases":[{"alias":"...","company_ids":["isin:1"]}]}`,
|
||||
`{"version":1,"aliases":[{"alias":"Empty","company_ids":[]}]}`,
|
||||
} {
|
||||
if err := c.loadAliases([]byte(data)); err == nil {
|
||||
t.Fatalf("accepted invalid alias file")
|
||||
}
|
||||
}
|
||||
got, err := c.SearchCompanies("Known", 20)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatal("partially applied invalid alias file")
|
||||
}
|
||||
}
|
||||
@ -28,6 +28,7 @@ type CompanyCatalog interface {
|
||||
var ErrUnknownCompany = errors.New("unknown company")
|
||||
|
||||
type Catalog struct {
|
||||
aliases map[string]map[string]bool
|
||||
companies []Company
|
||||
byID map[string]Company
|
||||
}
|
||||
@ -40,6 +41,9 @@ var embeddedManifest []byte
|
||||
|
||||
//go:embed data/FINANCEDATABASE_LICENSE
|
||||
var embeddedLicense []byte
|
||||
|
||||
//go:embed data/aliases.v1.json
|
||||
var embeddedAliases []byte
|
||||
var defaultOnce sync.Once
|
||||
var defaultCatalog *Catalog
|
||||
var defaultError error
|
||||
@ -58,6 +62,12 @@ func Default() (*Catalog, error) {
|
||||
return
|
||||
}
|
||||
defaultCatalog, defaultError = readCatalog(bytes.NewReader(embeddedSnapshot))
|
||||
if defaultError == nil {
|
||||
defaultError = defaultCatalog.loadAliases(embeddedAliases)
|
||||
}
|
||||
if defaultError != nil {
|
||||
defaultCatalog = nil
|
||||
}
|
||||
})
|
||||
return defaultCatalog, defaultError
|
||||
}
|
||||
@ -140,26 +150,6 @@ func readCatalog(input io.Reader) (*Catalog, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Name search folds case/spacing only: punctuation from a derivative ticker
|
||||
// (for example ES=F) must not become unrelated fragments of company names.
|
||||
func normalizeName(s string) string { return strings.Join(strings.Fields(strings.ToLower(s)), " ") }
|
||||
|
||||
func (c *Catalog) SearchCompanies(query string, limit int) ([]Company, error) {
|
||||
query = normalizeName(query)
|
||||
if query == "" || limit < 1 || limit > 20 {
|
||||
return nil, errors.New("invalid company search")
|
||||
}
|
||||
out := make([]Company, 0, limit)
|
||||
for _, company := range c.companies {
|
||||
if strings.Contains(normalizeName(company.Name), query) {
|
||||
out = append(out, company)
|
||||
if len(out) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (c *Catalog) ResolveCompany(id string) (Company, error) {
|
||||
if company, ok := c.byID[id]; ok {
|
||||
return company, nil
|
||||
|
||||
13
backend/internal/companycatalog/data/aliases.v1.json
Normal file
13
backend/internal/companycatalog/data/aliases.v1.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"aliases": [
|
||||
{
|
||||
"alias": "IBM",
|
||||
"company_ids": ["isin:US4592001014"]
|
||||
},
|
||||
{
|
||||
"alias": "Intel",
|
||||
"company_ids": ["isin:US4581401001"]
|
||||
}
|
||||
]
|
||||
}
|
||||
124
backend/internal/companycatalog/search.go
Normal file
124
backend/internal/companycatalog/search.go
Normal file
@ -0,0 +1,124 @@
|
||||
package companycatalog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// Normalization is shared by aliases, legal names and queries. Periods in
|
||||
// initials and apostrophes are ignored; other punctuation separates words.
|
||||
// Diacritics fold away; original display names and opaque IDs never change.
|
||||
func normalizeName(value string) string {
|
||||
var out strings.Builder
|
||||
for _, r := range norm.NFKD.String(strings.ToLower(value)) {
|
||||
switch {
|
||||
case unicode.Is(unicode.Mn, r):
|
||||
continue
|
||||
case unicode.IsLetter(r) || unicode.IsNumber(r) || unicode.IsSymbol(r):
|
||||
out.WriteRune(r)
|
||||
case r == '.' || r == '\'' || r == '’':
|
||||
continue
|
||||
default:
|
||||
out.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
return strings.Join(strings.Fields(out.String()), " ")
|
||||
}
|
||||
|
||||
// loadAliases validates the whole overlay before publishing it. Alias targets
|
||||
// must resolve in this snapshot; stale IDs never cause partial alias updates.
|
||||
func (c *Catalog) loadAliases(data []byte) error {
|
||||
var file struct {
|
||||
Version int `json:"version"`
|
||||
Aliases []struct {
|
||||
Alias string `json:"alias"`
|
||||
CompanyIDs []string `json:"company_ids"`
|
||||
} `json:"aliases"`
|
||||
}
|
||||
if json.Unmarshal(data, &file) != nil || file.Version != 1 {
|
||||
return errors.New("invalid company alias file")
|
||||
}
|
||||
aliases := map[string]map[string]bool{}
|
||||
for _, entry := range file.Aliases {
|
||||
key := normalizeName(entry.Alias)
|
||||
if key == "" || len(entry.CompanyIDs) == 0 {
|
||||
return errors.New("invalid company alias entry")
|
||||
}
|
||||
if aliases[key] == nil {
|
||||
aliases[key] = map[string]bool{}
|
||||
}
|
||||
for _, id := range entry.CompanyIDs {
|
||||
if _, ok := c.byID[id]; !ok {
|
||||
return errors.New("unresolved company alias target")
|
||||
}
|
||||
aliases[key][id] = true
|
||||
}
|
||||
}
|
||||
c.aliases = aliases
|
||||
return nil
|
||||
}
|
||||
|
||||
func legalWordPrefix(name, query string) bool {
|
||||
return strings.HasPrefix(name, query) || strings.Contains(name, " "+query)
|
||||
}
|
||||
|
||||
func (c *Catalog) SearchCompanies(query string, limit int) ([]Company, error) {
|
||||
if strings.TrimSpace(query) == "" || limit < 1 || limit > 20 {
|
||||
return nil, errors.New("invalid company search")
|
||||
}
|
||||
query = normalizeName(query)
|
||||
if query == "" {
|
||||
return []Company{}, nil
|
||||
}
|
||||
type match struct {
|
||||
company Company
|
||||
tier int
|
||||
name string
|
||||
}
|
||||
matches := map[string]match{}
|
||||
add := func(company Company, tier int) {
|
||||
normalized := normalizeName(company.Name)
|
||||
old, exists := matches[company.CompanyID]
|
||||
if !exists || tier < old.tier || (tier == old.tier && normalized < old.name) {
|
||||
matches[company.CompanyID] = match{company, tier, normalized}
|
||||
}
|
||||
}
|
||||
for id := range c.aliases[query] {
|
||||
add(c.byID[id], 0)
|
||||
}
|
||||
for _, company := range c.companies {
|
||||
name := normalizeName(company.Name)
|
||||
if name == query {
|
||||
add(company, 1)
|
||||
} else if legalWordPrefix(name, query) {
|
||||
add(company, 2)
|
||||
}
|
||||
}
|
||||
ranked := make([]match, 0, len(matches))
|
||||
for _, candidate := range matches {
|
||||
ranked = append(ranked, candidate)
|
||||
}
|
||||
sort.Slice(ranked, func(i, j int) bool {
|
||||
a, b := ranked[i], ranked[j]
|
||||
if a.tier != b.tier {
|
||||
return a.tier < b.tier
|
||||
}
|
||||
if a.name != b.name {
|
||||
return a.name < b.name
|
||||
}
|
||||
return a.company.CompanyID < b.company.CompanyID
|
||||
})
|
||||
if len(ranked) > limit {
|
||||
ranked = ranked[:limit]
|
||||
}
|
||||
out := make([]Company, 0, len(ranked))
|
||||
for _, candidate := range ranked {
|
||||
out = append(out, candidate.company)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Reference in New Issue
Block a user