diff --git a/docs/datasources.md b/docs/datasources.md index cb0626d..9e4bb53 100644 --- a/docs/datasources.md +++ b/docs/datasources.md @@ -6,7 +6,7 @@ são instanciados no `lifespan` (startup) a partir de env vars e injetados no | Datasource | Backend | Lib | Modelo | Usado por | |-----------|---------|-----|--------|-----------| -| `PostgresDatasource` | PostgreSQL `govbrnews` | `asyncpg` (pool) | **async** | themes, agencies, news (internal), `agencyAnalytics`, `articlesTimeline`, entidades (`entityCoverage`, `trendingEntities`) | +| `PostgresDatasource` | PostgreSQL `govbrnews` | `asyncpg` (pool) | **async** | themes, agencies, news (internal), `agencyAnalytics`, `articlesTimeline`, entidades (`entity`, `entityCoverage`, `trendingEntities`, `relatedEntities`, `entityNetwork`, `entityGraphStats`) | | `TypesenseDatasource` | Typesense | `typesense` | **sync** | articles, search, facets | | `TypesenseAdminDatasource` | Typesense | `typesense` | **sync** | writes (indexação, internal) | | `FirestoreDatasource` | Firestore | `firebase-admin` | **sync** (wrapped) | clippings, subscriptions, marketplace, users | @@ -17,6 +17,16 @@ são instanciados no `lifespan` (startup) a partir de env vars e injetados no `async` onde a lib é síncrona. Datasource ausente no startup vira `app.state. = None` (warning), e o resolver dependente falha em runtime. +!!! warning "Grafo de entidades depende da migração 032 do data-platform" + `entity`, `relatedEntities` e `entityNetwork` fazem LEFT JOIN em + `entity_stats` e leem `entity_edges.unique_content_count`; + `relatedEntities` e `entityGraphStats` leem `entity_graph_meta`. As três + estruturas vêm da migração 032 do data-platform: sem ela essas queries + falham (tabela/coluna inexistente). Com a migração aplicada mas antes da + primeira execução da DAG do grafo, os campos novos (`articleCount`, + `uniqueContentCount`, `uniqueContentWeight`, `lift`) ficam nulos e + `entityGraphStats` é `null`. + ## Injeção por request `get_context(request)` lê os datasources de `request.app.state` (populados pelo diff --git a/docs/exemplos.md b/docs/exemplos.md index f6eaad1..b02c008 100644 --- a/docs/exemplos.md +++ b/docs/exemplos.md @@ -114,6 +114,35 @@ forma mais rápida de explorar a API. `days` é limitado a 366. Os outros painéis usam facets do Typesense e refletem o atraso de indexação dele. +=== "Entidades" + + ```graphql + query Entidade($id: String!) { + entity(id: $id) { canonicalName type articleCount uniqueContentCount } + # vizinhos com associação acima do acaso (lift), sem co-menções únicas + relatedEntities(id: $id, limit: 12, orderBy: LIFT, minWeight: 2) { + canonicalId canonicalName weight uniqueContentWeight lift + } + # rede centrada: a entidade + 30 vizinhos mais fortes, com todas as arestas dela + entityNetwork(id: $id, egoCentered: true, maxNodes: 30, limit: 50) { + nodes { entityId canonicalName articleCount } + edges { src dst weight uniqueContentWeight } + } + # semana de 01/10 a 07/10 inteira: dateTo é exclusivo + entityCoverage(entityId: $id, dateFrom: "2026-10-01", dateTo: "2026-10-08", granularity: DAY) { + period agencyKey articleCount uniqueContentCount + } + entityGraphStats { totalArticles totalUniqueContent computedAt } + } + ``` + + !!! note "Contagens de artigos × de conteúdo" + `articleCount`/`weight` contam artigos; uma nota republicada por N + órgãos conta N vezes. `uniqueContentCount`/`uniqueContentWeight` contam + conteúdos distintos (`content_hash`). No `entityCoverage`, cada + conteúdo é creditado só ao primeiro órgão que o publicou no intervalo, + então `uniqueContentCount` pode ser somado entre órgãos e períodos. + ## Queries e mutations autenticadas Exigem `Authorization: Bearer `. @@ -285,3 +314,14 @@ mutation Features($id: String!, $f: JSON!) { upsertFeatures(uniqueId: $id, featu - **`cloneMarketplaceListing` retorna `Clipping!`** (precisa de selection set, ex.: `{ id name }`) — era `Boolean!` antes de um gap-fix pré-rollout. - **`clippings`** (não `myClippings`) é a query de listagem do usuário. + - **`entityCoverage` usa dias UTC com `dateTo` exclusivo.** Para incluir o + dia D inteiro, mande `dateTo = D + 1`. `period` vem como + `"AAAA-MM-DD 00:00:00+00"` (início do período em UTC). + - **`entityNetwork` sem `egoCentered` é a rede legada** (CTE recursiva, corte + de arestas pelo peso global): as arestas entre vizinhos podem expulsar as + da própria entidade. Para uma rede centrada, use `egoCentered: true`. + - **`relatedEntities` inclui co-menções únicas por padrão** (`minWeight: 1`, + a lista de sempre); `minWeight: 2` corta esse ruído. Já `entityNetwork` + com `egoCentered: true` usa sempre weight ≥ 2. + - **`ArticleSummary.agencyName` carrega a key** da agência (igual a + `agencyKey`), não o nome. diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index 21850b8..b8f27c4 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -26,9 +26,23 @@ type AgencyPeriodMetrics { Fração (0 a 1) dos artigos COM rótulo de sentimento que são negativos. Null se nenhum tem. """ pctNegative: Float + + """ + Média do Flesch pela fórmula inglesa (legado; escala distorcida para português). + """ avgReadabilityFlesch: Float avgWordCount: Float topThemes: [ThemeStats!]! + + """ + Média do Flesch adaptado ao português (Martins et al., 1996) dos artigos que o têm. Null quando nenhum tem. + """ + avgReadabilityFleschPtbr: Float + + """ + Nº de artigos do grupo com Flesch pt-BR calculado (base de avgReadabilityFleschPtbr). + """ + readabilityFleschPtbrCount: Int } """Agency statistics with article count""" @@ -123,7 +137,16 @@ type ArticleFeatures { uniqueSessions: Int trendingScore: Float wordCount: Int + + """ + Índice de Flesch pela fórmula inglesa (legado; escala distorcida para português). + """ readabilityFlesch: Float + + """ + Índice de Flesch adaptado ao português (Martins et al., 1996): 0–100, maior = mais fácil. Null até o artigo ser recalculado. + """ + readabilityFleschPtbr: Float } input ArticleFilter { @@ -149,9 +172,19 @@ enum ArticleSort { type ArticleSummary { uniqueId: String! title: String! + + """ + Key da agência (o mesmo valor de agencyKey, apesar do nome). Mantido por compatibilidade. + """ agencyName: String publishedAt: String trendingScore: Float + + """Link do artigo no portal de origem.""" + url: String + + """Key da agência (ex.: 'saude').""" + agencyKey: String } type ArticlesResult { @@ -292,6 +325,11 @@ type EntityCoveragePoint { articleCount: Int! totalMentions: Int! avgSentimentScore: Float + + """ + Conteúdos distintos (content_hash) creditados a esta agência: cada conteúdo conta só para a primeira agência que o publicou no intervalo consultado, então o campo soma entre agências e períodos sem contar republicações. articleCount conta artigos. + """ + uniqueContentCount: Int! } type EntityFacet { @@ -301,6 +339,15 @@ type EntityFacet { label: String } +""" +Totais do grafo de entidades (entity_graph_meta), recalculados pela DAG do grafo; N do lift de `relatedEntities`. +""" +type EntityGraphStats { + totalArticles: Int! + totalUniqueContent: Int! + computedAt: DateTime +} + enum EntityKind { ORG PER @@ -320,6 +367,11 @@ type EntityNetworkEdge { dst: String! weight: Int! kind: String! + + """ + Co-menções com conteúdo distinto: republicações (mesmo content_hash) contam uma vez. `weight` conta artigos. Null antes do cálculo do grafo. + """ + uniqueContentWeight: Int } type EntityNetworkNode { @@ -327,6 +379,16 @@ type EntityNetworkNode { canonicalName: String type: String wikidataId: String + + """ + Artigos que mencionam a entidade (entity_stats). Null sem estatística calculada. + """ + articleCount: Int + + """ + Conteúdos distintos que mencionam a entidade: republicações (mesmo content_hash) contam uma vez (entity_stats). Null sem estatística calculada. + """ + uniqueContentCount: Int } type EntityNode { @@ -338,6 +400,16 @@ type EntityNode { wikidataUrl: String description: String agencyKey: String + + """ + Artigos que mencionam a entidade (entity_stats). Null sem estatística calculada. + """ + articleCount: Int + + """ + Conteúdos distintos que mencionam a entidade: republicações (mesmo content_hash) contam uma vez (entity_stats). Null sem estatística calculada. + """ + uniqueContentCount: Int } type EntitySearchResult { @@ -713,14 +785,19 @@ type Query { entity(id: String!): EntityNode """ - Entidades relacionadas a `id` (entity_id) por co-menção (Fase 6c). Lê a rede de co-menção materializada (`entity_edges`, 1-hop), retorna os vizinhos hidratados do entity_registry, ordenados por `weight` (nº de artigos em co-menção) desc, até `limit`. Retorna [] sem Postgres ou sem vizinhos. PÚBLICO. + Entidades relacionadas a `id` (entity_id) por co-menção (Fase 6c). Lê a rede de co-menção materializada (`entity_edges`, 1-hop), retorna os vizinhos hidratados do entity_registry com weight >= `minWeight` (default 1 = todos; 2 descarta co-menções únicas), ordenados por `orderBy` (default WEIGHT = nº de artigos em co-menção) desc, até `limit`. Retorna [] sem Postgres ou sem vizinhos. PÚBLICO. + """ + relatedEntities(id: String!, limit: Int! = 12, orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 1): [RelatedEntity!]! + + """ + Totais do grafo de entidades (entity_graph_meta): artigos e conteúdos distintos considerados e quando foram calculados. Null sem Postgres ou antes da primeira execução da DAG do grafo. PÚBLICO. """ - relatedEntities(id: String!, limit: Int! = 12): [RelatedEntity!]! + entityGraphStats: EntityGraphStats """ - Ego-network (nós + arestas) ao redor de `id` (entity_id) para a visualização de rede (Fase 6c). Travessia não-direcionada na rede de co-menção (`entity_edges`) via CTE recursiva até `depth` saltos (CLAMPado a no máx 2; profundidades maiores ficam para o Neo4j futuro). `limit` limita o nº de arestas (cap de tamanho do grafo). Retorna {nodes:[], edges:[]} sem Postgres. PÚBLICO. + Ego-network (nós + arestas) ao redor de `id` (entity_id) para a visualização de rede (Fase 6c). Modo legado (default): travessia não-direcionada na rede de co-menção (`entity_edges`) via CTE recursiva até `depth` saltos (CLAMPado a no máx 2; profundidades maiores ficam para o Neo4j futuro); `limit` limita o nº de arestas (cap de tamanho do grafo). `egoCentered: true`: a entidade + seus `maxNodes` (1–100) vizinhos mais fortes (weight >= 2), com TODAS as arestas da entidade; `limit` (1–500) corta só as arestas entre vizinhos (`includeNeighborEdges`); `depth` é ignorado. Retorna {nodes:[], edges:[]} sem Postgres. PÚBLICO. """ - entityNetwork(id: String!, depth: Int! = 1, limit: Int! = 50): EntityNetwork! + entityNetwork(id: String!, depth: Int! = 1, limit: Int! = 50, egoCentered: Boolean! = false, maxNodes: Int! = 30, includeNeighborEdges: Boolean! = true): EntityNetwork! """ Contagem de artigos por code de tema (nivel `level`) nos ultimos `days` dias. `label` e None (o portal mapeia pela config). PUBLICO. @@ -737,7 +814,9 @@ type Query { """ estimateRecorteCount(themes: [String!]!, agencies: [String!]!, keywords: [String!]!, sinceHours: Int! = 24): Int! - """Série temporal de cobertura de uma entidade por agência""" + """ + Série temporal de cobertura de uma entidade por agência. `dateFrom`/`dateTo` (AAAA-MM-DD, opcionais) em dias UTC; dateFrom inclusivo, dateTo exclusivo: para incluir o dia D inteiro, passe dateTo = D + 1. `period` é o início do período em UTC ("AAAA-MM-DD 00:00:00+00"). + """ entityCoverage(entityId: String!, dateFrom: String = null, dateTo: String = null, granularity: Granularity! = MONTH): [EntityCoveragePoint!]! """Busca fuzzy de entidades por nome ou alias""" @@ -782,6 +861,35 @@ type RelatedEntity { wikidataId: String weight: Int! kind: String! + + """ + Artigos que mencionam o vizinho (entity_stats). Null sem estatística calculada. + """ + articleCount: Int + + """ + Conteúdos distintos que mencionam o vizinho: republicações (mesmo content_hash) contam uma vez (entity_stats). Null sem estatística calculada. + """ + uniqueContentCount: Int + + """ + Co-menções com conteúdo distinto: republicações (mesmo content_hash) contam uma vez. `weight` conta artigos. Null antes do cálculo do grafo. + """ + uniqueContentWeight: Int + + """ + weight · N / (artigos da entidade · artigos do vizinho), com N = entityGraphStats.totalArticles. > 1: co-menção acima do esperado ao acaso. Null quando falta estatística de uma das pontas ou o total do grafo. + """ + lift: Float +} + +""" +Ordenação de `relatedEntities`. WEIGHT: artigos em co-menção (legado). UNIQUE_CONTENT: co-menções com conteúdo distinto (desconta republicações). LIFT: co-menção observada / esperada pela frequência das duas entidades (destaca associações específicas em vez de entidades genéricas). Valores nulos vão para o fim; desempate por weight. +""" +enum RelatedEntityOrder { + WEIGHT + UNIQUE_CONTENT + LIFT } type Release { diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 0fd27f5..d3ae440 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -37,9 +37,23 @@ type AgencyPeriodMetrics { Fração (0 a 1) dos artigos COM rótulo de sentimento que são negativos. Null se nenhum tem. """ pctNegative: Float + + """ + Média do Flesch pela fórmula inglesa (legado; escala distorcida para português). + """ avgReadabilityFlesch: Float avgWordCount: Float topThemes: [ThemeStats!]! + + """ + Média do Flesch adaptado ao português (Martins et al., 1996) dos artigos que o têm. Null quando nenhum tem. + """ + avgReadabilityFleschPtbr: Float + + """ + Nº de artigos do grupo com Flesch pt-BR calculado (base de avgReadabilityFleschPtbr). + """ + readabilityFleschPtbrCount: Int } """Agency statistics with article count""" @@ -134,7 +148,16 @@ type ArticleFeatures { uniqueSessions: Int trendingScore: Float wordCount: Int + + """ + Índice de Flesch pela fórmula inglesa (legado; escala distorcida para português). + """ readabilityFlesch: Float + + """ + Índice de Flesch adaptado ao português (Martins et al., 1996): 0–100, maior = mais fácil. Null até o artigo ser recalculado. + """ + readabilityFleschPtbr: Float } input ArticleFilter { @@ -160,9 +183,19 @@ enum ArticleSort { type ArticleSummary { uniqueId: String! title: String! + + """ + Key da agência (o mesmo valor de agencyKey, apesar do nome). Mantido por compatibilidade. + """ agencyName: String publishedAt: String trendingScore: Float + + """Link do artigo no portal de origem.""" + url: String + + """Key da agência (ex.: 'saude').""" + agencyKey: String } type ArticlesResult { @@ -303,6 +336,11 @@ type EntityCoveragePoint { articleCount: Int! totalMentions: Int! avgSentimentScore: Float + + """ + Conteúdos distintos (content_hash) creditados a esta agência: cada conteúdo conta só para a primeira agência que o publicou no intervalo consultado, então o campo soma entre agências e períodos sem contar republicações. articleCount conta artigos. + """ + uniqueContentCount: Int! } type EntityFacet { @@ -312,6 +350,15 @@ type EntityFacet { label: String } +""" +Totais do grafo de entidades (entity_graph_meta), recalculados pela DAG do grafo; N do lift de `relatedEntities`. +""" +type EntityGraphStats { + totalArticles: Int! + totalUniqueContent: Int! + computedAt: DateTime +} + enum EntityKind { ORG PER @@ -331,6 +378,11 @@ type EntityNetworkEdge { dst: String! weight: Int! kind: String! + + """ + Co-menções com conteúdo distinto: republicações (mesmo content_hash) contam uma vez. `weight` conta artigos. Null antes do cálculo do grafo. + """ + uniqueContentWeight: Int } type EntityNetworkNode { @@ -338,6 +390,16 @@ type EntityNetworkNode { canonicalName: String type: String wikidataId: String + + """ + Artigos que mencionam a entidade (entity_stats). Null sem estatística calculada. + """ + articleCount: Int + + """ + Conteúdos distintos que mencionam a entidade: republicações (mesmo content_hash) contam uma vez (entity_stats). Null sem estatística calculada. + """ + uniqueContentCount: Int } type EntityNode { @@ -349,6 +411,16 @@ type EntityNode { wikidataUrl: String description: String agencyKey: String + + """ + Artigos que mencionam a entidade (entity_stats). Null sem estatística calculada. + """ + articleCount: Int + + """ + Conteúdos distintos que mencionam a entidade: republicações (mesmo content_hash) contam uma vez (entity_stats). Null sem estatística calculada. + """ + uniqueContentCount: Int } type EntitySearchResult { @@ -724,14 +796,19 @@ type Query { entity(id: String!): EntityNode """ - Entidades relacionadas a `id` (entity_id) por co-menção (Fase 6c). Lê a rede de co-menção materializada (`entity_edges`, 1-hop), retorna os vizinhos hidratados do entity_registry, ordenados por `weight` (nº de artigos em co-menção) desc, até `limit`. Retorna [] sem Postgres ou sem vizinhos. PÚBLICO. + Entidades relacionadas a `id` (entity_id) por co-menção (Fase 6c). Lê a rede de co-menção materializada (`entity_edges`, 1-hop), retorna os vizinhos hidratados do entity_registry com weight >= `minWeight` (default 1 = todos; 2 descarta co-menções únicas), ordenados por `orderBy` (default WEIGHT = nº de artigos em co-menção) desc, até `limit`. Retorna [] sem Postgres ou sem vizinhos. PÚBLICO. + """ + relatedEntities(id: String!, limit: Int! = 12, orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 1): [RelatedEntity!]! + + """ + Totais do grafo de entidades (entity_graph_meta): artigos e conteúdos distintos considerados e quando foram calculados. Null sem Postgres ou antes da primeira execução da DAG do grafo. PÚBLICO. """ - relatedEntities(id: String!, limit: Int! = 12): [RelatedEntity!]! + entityGraphStats: EntityGraphStats """ - Ego-network (nós + arestas) ao redor de `id` (entity_id) para a visualização de rede (Fase 6c). Travessia não-direcionada na rede de co-menção (`entity_edges`) via CTE recursiva até `depth` saltos (CLAMPado a no máx 2; profundidades maiores ficam para o Neo4j futuro). `limit` limita o nº de arestas (cap de tamanho do grafo). Retorna {nodes:[], edges:[]} sem Postgres. PÚBLICO. + Ego-network (nós + arestas) ao redor de `id` (entity_id) para a visualização de rede (Fase 6c). Modo legado (default): travessia não-direcionada na rede de co-menção (`entity_edges`) via CTE recursiva até `depth` saltos (CLAMPado a no máx 2; profundidades maiores ficam para o Neo4j futuro); `limit` limita o nº de arestas (cap de tamanho do grafo). `egoCentered: true`: a entidade + seus `maxNodes` (1–100) vizinhos mais fortes (weight >= 2), com TODAS as arestas da entidade; `limit` (1–500) corta só as arestas entre vizinhos (`includeNeighborEdges`); `depth` é ignorado. Retorna {nodes:[], edges:[]} sem Postgres. PÚBLICO. """ - entityNetwork(id: String!, depth: Int! = 1, limit: Int! = 50): EntityNetwork! + entityNetwork(id: String!, depth: Int! = 1, limit: Int! = 50, egoCentered: Boolean! = false, maxNodes: Int! = 30, includeNeighborEdges: Boolean! = true): EntityNetwork! """ Contagem de artigos por code de tema (nivel `level`) nos ultimos `days` dias. `label` e None (o portal mapeia pela config). PUBLICO. @@ -748,7 +825,9 @@ type Query { """ estimateRecorteCount(themes: [String!]!, agencies: [String!]!, keywords: [String!]!, sinceHours: Int! = 24): Int! - """Série temporal de cobertura de uma entidade por agência""" + """ + Série temporal de cobertura de uma entidade por agência. `dateFrom`/`dateTo` (AAAA-MM-DD, opcionais) em dias UTC; dateFrom inclusivo, dateTo exclusivo: para incluir o dia D inteiro, passe dateTo = D + 1. `period` é o início do período em UTC ("AAAA-MM-DD 00:00:00+00"). + """ entityCoverage(entityId: String!, dateFrom: String = null, dateTo: String = null, granularity: Granularity! = MONTH): [EntityCoveragePoint!]! """Busca fuzzy de entidades por nome ou alias""" @@ -793,6 +872,35 @@ type RelatedEntity { wikidataId: String weight: Int! kind: String! + + """ + Artigos que mencionam o vizinho (entity_stats). Null sem estatística calculada. + """ + articleCount: Int + + """ + Conteúdos distintos que mencionam o vizinho: republicações (mesmo content_hash) contam uma vez (entity_stats). Null sem estatística calculada. + """ + uniqueContentCount: Int + + """ + Co-menções com conteúdo distinto: republicações (mesmo content_hash) contam uma vez. `weight` conta artigos. Null antes do cálculo do grafo. + """ + uniqueContentWeight: Int + + """ + weight · N / (artigos da entidade · artigos do vizinho), com N = entityGraphStats.totalArticles. > 1: co-menção acima do esperado ao acaso. Null quando falta estatística de uma das pontas ou o total do grafo. + """ + lift: Float +} + +""" +Ordenação de `relatedEntities`. WEIGHT: artigos em co-menção (legado). UNIQUE_CONTENT: co-menções com conteúdo distinto (desconta republicações). LIFT: co-menção observada / esperada pela frequência das duas entidades (destaca associações específicas em vez de entidades genéricas). Valores nulos vão para o fim; desempate por weight. +""" +enum RelatedEntityOrder { + WEIGHT + UNIQUE_CONTENT + LIFT } type Release { diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 597d8ed..db4f9ab 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -71,6 +71,10 @@ class EntityRegistryRecord: wikidata_url: Optional[str] = None description: Optional[str] = None agency_key: Optional[str] = None + # GQL-1: `entity_stats` (migração 032); None sem estatística calculada. + # Só `_ENTITY_REGISTRY_SQL` (entity(id)) junta; o batch deixa None. + article_count: Optional[int] = None + unique_content_count: Optional[int] = None @dataclass @@ -87,26 +91,50 @@ class RelatedEntityRecord: wikidata_id: Optional[str] = None weight: int = 0 kind: str = "co_mention" + # GQL-1 (migração 032): stats do vizinho, co-menções com conteúdo distinto e + # lift da aresta. None quando falta estatística (ver `_RELATED_ENTITIES_SQL`). + article_count: Optional[int] = None + unique_content_count: Optional[int] = None + unique_content_weight: Optional[int] = None + lift: Optional[float] = None + + +@dataclass +class EntityGraphStatsRecord: + """Totais do grafo de entidades (`entity_graph_meta`, linha única id=1).""" + + total_articles: int + total_unique_content: int + computed_at: Optional[datetime] = None @dataclass class EntityNetworkNodeRecord: - """Nó da ego-network de uma entidade (Fase 6c).""" + """Nó da ego-network de uma entidade (Fase 6c). + + `article_count`/`unique_content_count` vêm de `entity_stats` (migração 032 + do data-platform); None quando a entidade ainda não tem estatística.""" entity_id: str canonical_name: Optional[str] = None type: Optional[str] = None wikidata_id: Optional[str] = None + article_count: Optional[int] = None + unique_content_count: Optional[int] = None @dataclass class EntityNetworkEdgeRecord: - """Aresta da ego-network (Fase 6c). `src`/`dst` são entity_ids.""" + """Aresta da ego-network (Fase 6c). `src`/`dst` são entity_ids. + + `unique_content_weight` = co-menções com conteúdo distinto + (`entity_edges.unique_content_count`, migração 032); None antes do cálculo.""" src: str dst: str weight: int = 0 kind: str = "co_mention" + unique_content_weight: Optional[int] = None @dataclass @@ -157,10 +185,13 @@ class TypesenseDocRecord(NewsRecord): # (asyncpg devolve como str → json.loads). `description`/`wikidata_*` podem ser # nulos quando a entidade não foi linkada ao Wikidata. _ENTITY_REGISTRY_SQL = """ -SELECT entity_id, canonical_name, type, aliases, - wikidata_id, wikidata_url, description, agency_key -FROM entity_registry -WHERE entity_id = $1 +SELECT r.entity_id, r.canonical_name, r.type, r.aliases, + r.wikidata_id, r.wikidata_url, r.description, r.agency_key, + s.article_count AS article_count, + s.unique_content_count AS unique_content_count +FROM entity_registry r +LEFT JOIN entity_stats s ON s.entity_id = r.entity_id +WHERE r.entity_id = $1 """ _ENTITY_REGISTRY_BATCH_SQL = """ @@ -174,25 +205,76 @@ class TypesenseDocRecord(NewsRecord): # `entity_edges` onde a entidade aparece em qualquer ponta (src_id OU dst_id), # pega a "outra ponta" e junta com `entity_registry` para hidratar # nome/tipo/wikidata. `entity_id` SEMPRE como `$1` parametrizado (sem -# interpolação — risco de injection). Ordenado por weight desc; LIMIT em $2. -# A ordem canônica src_id < dst_id em entity_edges garante 1 linha por par. +# interpolação — risco de injection). LIMIT em $2. A ordem canônica +# src_id < dst_id em entity_edges garante 1 linha por par. +# +# GQL-1: `$4` = peso mínimo da aresta; `$3` = ordenação (whitelist no +# datasource): 'weight' (legado), 'unique_content' (co-menções com conteúdo +# distinto) ou 'lift' = weight·N / (cnt_ego·cnt_vizinho), com N = +# entity_graph_meta.total_articles e cnt = entity_stats.article_count — NULL se +# qualquer termo faltar ou for 0 (NULLIF). Nulos vão para o fim e o desempate é +# sempre weight desc, other_id asc (com 'weight', a ordem legada). _RELATED_ENTITIES_SQL = """ -SELECT - CASE WHEN e.src_id = $1 THEN e.dst_id ELSE e.src_id END AS other_id, - e.weight AS weight, - e.kind AS kind, - r.canonical_name AS canonical_name, - r.type AS type, - r.wikidata_id AS wikidata_id -FROM entity_edges e -JOIN entity_registry r - ON r.entity_id = CASE WHEN e.src_id = $1 THEN e.dst_id ELSE e.src_id END -WHERE e.kind = 'co_mention' - AND ($1 IN (e.src_id, e.dst_id)) -ORDER BY e.weight DESC, other_id ASC +WITH neighbors AS ( + SELECT + CASE WHEN e.src_id = $1 THEN e.dst_id ELSE e.src_id END AS other_id, + e.weight AS weight, + e.kind AS kind, + e.unique_content_count AS unique_content_weight + FROM entity_edges e + WHERE e.kind = 'co_mention' + AND ($1 IN (e.src_id, e.dst_id)) + AND e.weight >= $4 +), +scored AS ( + SELECT + nb.other_id, + nb.weight, + nb.kind, + nb.unique_content_weight, + r.canonical_name AS canonical_name, + r.type AS type, + r.wikidata_id AS wikidata_id, + so.article_count AS article_count, + so.unique_content_count AS unique_content_count, + nb.weight::float8 * NULLIF(m.total_articles, 0) + / (NULLIF(se.article_count, 0)::float8 * NULLIF(so.article_count, 0)) AS lift + FROM neighbors nb + JOIN entity_registry r ON r.entity_id = nb.other_id + LEFT JOIN entity_stats so ON so.entity_id = nb.other_id + LEFT JOIN entity_stats se ON se.entity_id = $1 + LEFT JOIN entity_graph_meta m ON m.id = 1 +) +SELECT other_id, weight, kind, unique_content_weight, canonical_name, type, + wikidata_id, article_count, unique_content_count, lift +FROM scored +ORDER BY + CASE $3::text + WHEN 'lift' THEN lift + WHEN 'unique_content' THEN unique_content_weight::float8 + ELSE weight::float8 + END DESC NULLS LAST, + weight DESC, other_id ASC LIMIT $2 """ +# Totais do grafo (linha única id=1), recalculados pela DAG junto com +# entity_stats (migração 032). N do lift. +_ENTITY_GRAPH_STATS_SQL = """ +SELECT total_articles, total_unique_content, computed_at +FROM entity_graph_meta +WHERE id = 1 +""" + +# Ordenações aceitas por `get_related_entities` ($3 de `_RELATED_ENTITIES_SQL`). +_RELATED_ENTITY_ORDERS = frozenset({"weight", "unique_content", "lift"}) + +# Limites da ego-network centrada (GQL-1). Peso 1 = uma única co-menção (ruído). +_EGO_MIN_WEIGHT = 2 +_EGO_DEFAULT_MAX_NODES = 30 +_EGO_MAX_NODES = 100 +_EGO_MAX_NEIGHBOR_EDGES = 500 + # Fase 6c — ego-network multi-hop (depth<=2) via CTE recursiva em `entity_edges`. # Parte de `$1` (parametrizado), expande pelas arestas de co-menção até `$2` # saltos (clampado a 2 no datasource), coletando o conjunto de entity_ids @@ -216,9 +298,12 @@ class TypesenseDocRecord(NewsRecord): r.entity_id AS entity_id, r.canonical_name AS canonical_name, r.type AS type, - r.wikidata_id AS wikidata_id + r.wikidata_id AS wikidata_id, + s.article_count AS article_count, + s.unique_content_count AS unique_content_count FROM (SELECT DISTINCT entity_id FROM reachable) ni JOIN entity_registry r ON r.entity_id = ni.entity_id +LEFT JOIN entity_stats s ON s.entity_id = r.entity_id """ _ENTITY_NETWORK_EDGES_SQL = """ @@ -237,7 +322,8 @@ class TypesenseDocRecord(NewsRecord): node_ids AS ( SELECT DISTINCT entity_id FROM reachable ) -SELECT e.src_id AS src, e.dst_id AS dst, e.weight AS weight, e.kind AS kind +SELECT e.src_id AS src, e.dst_id AS dst, e.weight AS weight, e.kind AS kind, + e.unique_content_count AS unique_content_weight FROM entity_edges e WHERE e.kind = 'co_mention' AND e.src_id IN (SELECT entity_id FROM node_ids) @@ -246,6 +332,75 @@ class TypesenseDocRecord(NewsRecord): LIMIT $3 """ +# GQL-1 — ego-network centrada no foco (`egoCentered`). A rede legada acima +# corta as arestas pelo peso global, e as arestas fortes ENTRE vizinhos expulsam +# as do próprio foco. Aqui os vizinhos são as top `$2` arestas do foco `$1` com +# weight >= `$3` (ordem determinística weight desc, id asc), e TODAS essas +# arestas do foco entram; só as arestas entre vizinhos (`$4` liga/desliga) são +# cortadas em `$5`. Nós e arestas são duas queries com o MESMO CTE `neighbors` +# (mesma ordem + LIMIT ⇒ mesmo conjunto); o datasource ainda poda órfãos caso o +# grafo mude entre elas. Foco primeiro (weight NULL), vizinhos por peso. +_ENTITY_NETWORK_EGO_NODES_SQL = """ +WITH neighbors AS ( + SELECT + CASE WHEN e.src_id = $1 THEN e.dst_id ELSE e.src_id END AS other_id, + e.weight AS weight + FROM entity_edges e + WHERE e.kind = 'co_mention' + AND $1 IN (e.src_id, e.dst_id) + AND e.weight >= $3 + ORDER BY e.weight DESC, other_id ASC + LIMIT $2 +), +node_ids AS ( + SELECT $1::varchar AS entity_id, NULL::int AS weight + UNION ALL + SELECT other_id, weight FROM neighbors +) +SELECT + r.entity_id AS entity_id, + r.canonical_name AS canonical_name, + r.type AS type, + r.wikidata_id AS wikidata_id, + s.article_count AS article_count, + s.unique_content_count AS unique_content_count +FROM node_ids ni +JOIN entity_registry r ON r.entity_id = ni.entity_id +LEFT JOIN entity_stats s ON s.entity_id = r.entity_id +ORDER BY ni.weight DESC NULLS FIRST, r.entity_id ASC +""" + +_ENTITY_NETWORK_EGO_EDGES_SQL = """ +WITH neighbors AS ( + SELECT + CASE WHEN e.src_id = $1 THEN e.dst_id ELSE e.src_id END AS other_id, + e.src_id, e.dst_id, e.weight, e.kind, e.unique_content_count + FROM entity_edges e + WHERE e.kind = 'co_mention' + AND $1 IN (e.src_id, e.dst_id) + AND e.weight >= $3 + ORDER BY e.weight DESC, other_id ASC + LIMIT $2 +), +neighbor_edges AS ( + SELECT e.src_id, e.dst_id, e.weight, e.kind, e.unique_content_count + FROM entity_edges e + WHERE $4::boolean + AND e.kind = 'co_mention' + AND e.weight >= $3 + AND e.src_id IN (SELECT other_id FROM neighbors) + AND e.dst_id IN (SELECT other_id FROM neighbors) + ORDER BY e.weight DESC, e.src_id ASC, e.dst_id ASC + LIMIT $5 +) +SELECT src_id AS src, dst_id AS dst, weight, kind, unique_content_count AS unique_content_weight +FROM neighbors +UNION ALL +SELECT src_id AS src, dst_id AS dst, weight, kind, unique_content_count AS unique_content_weight +FROM neighbor_edges +ORDER BY weight DESC, src ASC, dst ASC +""" + _NEWS_BASE_SQL = """ SELECT n.*, t1.code as theme_l1_code, t1.label as theme_l1_label, @@ -329,6 +484,9 @@ class TypesenseDocRecord(NewsRecord): # legado. O LATERAL `s` resolve os dois com COALESCE (aninhado primeiro). # `pct_positive`/`pct_negative` = fração dos artigos COM rótulo; NULL quando # nenhum artigo do grupo tem rótulo (nulo ≠ zero). +# Legibilidade: `readability_flesch` é a fórmula inglesa (legado); +# `readability_flesch_ptbr` (Martins/1996, GQL-1) vem com a contagem de artigos +# que o têm, para o consumidor medir a cobertura do backfill. _AGENCY_ANALYTICS_SQL = """ SELECT DATE_TRUNC($1, n.published_at)::text AS period, @@ -339,6 +497,8 @@ class TypesenseDocRecord(NewsRecord): AVG(CASE WHEN s.label = 'positive' THEN 1.0 WHEN s.label IS NOT NULL THEN 0.0 END) AS pct_positive, AVG(CASE WHEN s.label = 'negative' THEN 1.0 WHEN s.label IS NOT NULL THEN 0.0 END) AS pct_negative, AVG((nf.features->>'readability_flesch')::float) AS avg_readability_flesch, + AVG((nf.features->>'readability_flesch_ptbr')::float) AS avg_readability_flesch_ptbr, + COUNT(nf.features->>'readability_flesch_ptbr') AS readability_flesch_ptbr_count, AVG((nf.features->>'word_count')::float) AS avg_word_count FROM news n LEFT JOIN news_features nf ON n.unique_id = nf.unique_id @@ -376,6 +536,8 @@ class TypesenseDocRecord(NewsRecord): AVG(CASE WHEN s.label = 'positive' THEN 1.0 WHEN s.label IS NOT NULL THEN 0.0 END) AS pct_positive, AVG(CASE WHEN s.label = 'negative' THEN 1.0 WHEN s.label IS NOT NULL THEN 0.0 END) AS pct_negative, AVG((nf.features->>'readability_flesch')::float) AS avg_readability_flesch, + AVG((nf.features->>'readability_flesch_ptbr')::float) AS avg_readability_flesch_ptbr, + COUNT(nf.features->>'readability_flesch_ptbr') AS readability_flesch_ptbr_count, AVG((nf.features->>'word_count')::float) AS avg_word_count FROM news n LEFT JOIN news_features nf ON n.unique_id = nf.unique_id @@ -397,6 +559,8 @@ class TypesenseDocRecord(NewsRecord): da.pct_positive, da.pct_negative, da.avg_readability_flesch, + da.avg_readability_flesch_ptbr, + COALESCE(da.readability_flesch_ptbr_count, 0) AS readability_flesch_ptbr_count, da.avg_word_count FROM date_series ds CROSS JOIN agency_names an @@ -436,25 +600,59 @@ class TypesenseDocRecord(NewsRecord): ORDER BY d.day """ +# Chave de "mesmo conteúdo" para o dedup de republicações no entityCoverage +# (`n` = news, `ne` = news_entities). Hoje é o hash exato do conteúdo, que quase +# não pega republicações entre órgãos (raramente idênticas byte a byte); uma +# chave de quase-duplicata está em avaliação. Trocar a expressão aqui não muda a +# API (`uniqueContentCount`), mas `entity_stats.unique_content_count` e +# `entity_edges.unique_content_count` vêm da DAG do grafo no data-platform com a +# mesma definição — mantenha as duas pontas alinhadas. +_CONTENT_DEDUP_KEY_SQL = "COALESCE(n.content_hash, ne.unique_id)" + # Série temporal de cobertura de uma entidade por agência e período. # `$1` = granularidade (day/week/month), `$2` = entity_id, `$3` = date_from # (NULL = sem limite inferior), `$4` = date_to (NULL = sem limite superior). +# Dias UTC: `$3` inclusivo e `$4` EXCLUSIVO (meia-noite UTC de cada data, sem +# depender do TimeZone da sessão). `period` é truncado em UTC e formatado como o +# `timestamptz::text` de uma sessão UTC ("2026-08-27 00:00:00+00"), formato que +# os consumidores já parseiam. +# `unique_content_count` credita cada conteúdo (`_CONTENT_DEDUP_KEY_SQL`) só à +# PRIMEIRA agência que o publicou dentro do intervalo (ROW_NUMBER por +# published_at, unique_id): republicações não contam de novo e o campo soma +# entre agências e períodos. `article_count` continua contando artigos. +# Uma linha por artigo: PK (unique_id, entity_id) em news_entities e joins 1:1 +# com news/news_features, então COUNT(*) = COUNT(DISTINCT unique_id) — e, sem +# DISTINCT, o agregado pode ser por hash (o sort após a janela era o gargalo). # Score de sentimento aninhado com fallback plano (ver `_AGENCY_ANALYTICS_SQL`). -_ENTITY_COVERAGE_SQL = """ +_ENTITY_COVERAGE_SQL = f""" +WITH mentions AS ( + SELECT + to_char(DATE_TRUNC($1, ne.published_at AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS"+00"') AS period, + ne.count, + n.agency_key, + n.agency_name, + COALESCE(nf.features->'sentiment'->>'score', nf.features->>'sentiment_score')::float AS sentiment_score, + ROW_NUMBER() OVER ( + PARTITION BY {_CONTENT_DEDUP_KEY_SQL} + ORDER BY n.published_at, ne.unique_id + ) = 1 AS is_first + FROM news_entities ne + JOIN news n ON ne.unique_id = n.unique_id + LEFT JOIN news_features nf ON ne.unique_id = nf.unique_id + WHERE ne.entity_id = $2 + AND ($3::date IS NULL OR ne.published_at >= ($3::date)::timestamp AT TIME ZONE 'UTC') + AND ($4::date IS NULL OR ne.published_at < ($4::date)::timestamp AT TIME ZONE 'UTC') +) SELECT - DATE_TRUNC($1, ne.published_at)::text AS period, - n.agency_key, - n.agency_name, - COUNT(DISTINCT ne.unique_id) AS article_count, - SUM(ne.count) AS total_mentions, - AVG(COALESCE(nf.features->'sentiment'->>'score', nf.features->>'sentiment_score')::float) AS avg_sentiment_score -FROM news_entities ne -JOIN news n ON ne.unique_id = n.unique_id -LEFT JOIN news_features nf ON ne.unique_id = nf.unique_id -WHERE ne.entity_id = $2 - AND ($3::timestamptz IS NULL OR ne.published_at >= $3::timestamptz) - AND ($4::timestamptz IS NULL OR ne.published_at <= $4::timestamptz) -GROUP BY period, n.agency_key, n.agency_name + m.period, + m.agency_key, + m.agency_name, + COUNT(*) AS article_count, + COUNT(*) FILTER (WHERE m.is_first) AS unique_content_count, + SUM(m.count) AS total_mentions, + AVG(m.sentiment_score) AS avg_sentiment_score +FROM mentions m +GROUP BY period, m.agency_key, m.agency_name ORDER BY period """ @@ -722,6 +920,16 @@ def _coerce_alias_list(raw: Any) -> list[str]: return out +def _as_optional_int(value: Any) -> Optional[int]: + return None if value is None else int(value) + + +def _as_optional_float(value: Any) -> Optional[float]: + """Decimal/numérico do asyncpg → float (o Float do graphql-core 3.3 rejeita + Decimal); None passa.""" + return None if value is None else float(value) + + def _row_to_entity_registry(row: dict) -> EntityRegistryRecord: return EntityRegistryRecord( entity_id=row["entity_id"], @@ -732,6 +940,8 @@ def _row_to_entity_registry(row: dict) -> EntityRegistryRecord: wikidata_url=row.get("wikidata_url"), description=row.get("description"), agency_key=row.get("agency_key"), + article_count=_as_optional_int(row.get("article_count")), + unique_content_count=_as_optional_int(row.get("unique_content_count")), ) @@ -743,6 +953,10 @@ def _row_to_related_entity(row: dict) -> RelatedEntityRecord: wikidata_id=row.get("wikidata_id"), weight=row.get("weight") or 0, kind=row.get("kind") or "co_mention", + article_count=_as_optional_int(row.get("article_count")), + unique_content_count=_as_optional_int(row.get("unique_content_count")), + unique_content_weight=_as_optional_int(row.get("unique_content_weight")), + lift=_as_optional_float(row.get("lift")), ) @@ -752,6 +966,8 @@ def _row_to_network_node(row: dict) -> EntityNetworkNodeRecord: canonical_name=row.get("canonical_name"), type=row.get("type"), wikidata_id=row.get("wikidata_id"), + article_count=_as_optional_int(row.get("article_count")), + unique_content_count=_as_optional_int(row.get("unique_content_count")), ) @@ -761,6 +977,40 @@ def _row_to_network_edge(row: dict) -> EntityNetworkEdgeRecord: dst=row["dst"], weight=row.get("weight") or 0, kind=row.get("kind") or "co_mention", + unique_content_weight=_as_optional_int(row.get("unique_content_weight")), + ) + + +def _prune_ego_network( + focus_id: str, + nodes: list[EntityNetworkNodeRecord], + edges: list[EntityNetworkEdgeRecord], +) -> EntityNetworkRecord: + """Garante a ego-network sem órfãos: só ficam o foco e os vizinhos ligados a + ele por aresta, e só as arestas entre esses nós. As duas queries escolhem o + mesmo conjunto de vizinhos, mas a DAG pode recalcular `entity_edges` entre + elas. Também deduplica nós por id e arestas por par não-ordenado (mantém a + primeira, de maior peso): src_id < dst_id é convenção, sem CHECK no banco.""" + unique_nodes: dict[str, EntityNetworkNodeRecord] = {} + for n in nodes: + unique_nodes.setdefault(n.entity_id, n) + nodes = list(unique_nodes.values()) + node_ids = set(unique_nodes) + seen_pairs: set[frozenset[str]] = set() + unique_edges = [] + for e in edges: + pair = frozenset((e.src, e.dst)) + if pair not in seen_pairs and e.src in node_ids and e.dst in node_ids: + seen_pairs.add(pair) + unique_edges.append(e) + edges = unique_edges + linked = {focus_id} + for e in edges: + if focus_id in (e.src, e.dst): + linked.add(e.dst if e.src == focus_id else e.src) + return EntityNetworkRecord( + nodes=[n for n in nodes if n.entity_id in linked], + edges=[e for e in edges if e.src in linked and e.dst in linked], ) @@ -931,33 +1181,78 @@ async def get_entities_batch( return result async def get_related_entities( - self, entity_id: str, limit: int = 12 + self, + entity_id: str, + limit: int = 12, + order_by: str = "weight", + min_weight: int = 1, ) -> list[RelatedEntityRecord]: """Vizinhos 1-hop de `entity_id` na rede de co-menção (Fase 6c). Lê `entity_edges` (kind=co_mention) onde a entidade aparece em qualquer ponta, pega a "outra ponta" e junta com `entity_registry` para hidratar - nome/tipo/wikidata. Ordenado por weight desc; até `limit`. `entity_id` + nome/tipo/wikidata, e com `entity_stats`/`entity_graph_meta` para as + estatísticas e o lift (GQL-1). Só arestas com weight >= `min_weight` + (mínimo 1; o default 1 é a lista legada). `order_by`: 'weight' + (default), 'unique_content' ou 'lift' (nulos por último; desempate + weight desc). Até `limit`. `entity_id` sempre parametrizado ($1) — nunca interpolado (anti-injection).""" + if order_by not in _RELATED_ENTITY_ORDERS: + raise ValueError(f"order_by inválido: {order_by!r}") if not entity_id: return [] async with self._pool.acquire() as conn: - rows = await conn.fetch(_RELATED_ENTITIES_SQL, entity_id, limit) + rows = await conn.fetch( + _RELATED_ENTITIES_SQL, + entity_id, + limit, + order_by, + max(1, int(min_weight)), + ) return [_row_to_related_entity(dict(r)) for r in rows] + async def get_entity_graph_stats(self) -> Optional[EntityGraphStatsRecord]: + """Totais do grafo de entidades (`entity_graph_meta`); None sem linha + (DAG ainda não rodou após a migração 032).""" + async with self._pool.acquire() as conn: + row = await conn.fetchrow(_ENTITY_GRAPH_STATS_SQL) + if row is None: + return None + return EntityGraphStatsRecord( + total_articles=int(row["total_articles"]), + total_unique_content=int(row["total_unique_content"]), + computed_at=row["computed_at"], + ) + async def get_entity_network( - self, entity_id: str, depth: int = 1, limit: int = 50 + self, + entity_id: str, + depth: int = 1, + limit: int = 50, + ego_centered: bool = False, + max_nodes: int = _EGO_DEFAULT_MAX_NODES, + include_neighbor_edges: bool = True, ) -> EntityNetworkRecord: """Ego-network (nós + arestas) ao redor de `entity_id` (Fase 6c). - CTE recursiva em `entity_edges` (kind=co_mention), travessia - não-direcionada até `depth` saltos. `depth` é CLAMPado a [0, 2] aqui - (profundidades maiores ficam para o Neo4j numa iteração futura). `limit` - limita o nº de arestas (cap de tamanho do grafo). `entity_id` sempre - parametrizado ($1) — nunca interpolado (anti-injection). Nós e arestas - em duas queries que compartilham a mesma CTE.""" + Modo legado (default): CTE recursiva em `entity_edges` (kind=co_mention), + travessia não-direcionada até `depth` saltos. `depth` é CLAMPado a [0, 2] + aqui (profundidades maiores ficam para o Neo4j numa iteração futura). + `limit` limita o nº de arestas (cap de tamanho do grafo). Nós e arestas + em duas queries que compartilham a mesma CTE. + + `ego_centered=True` (GQL-1): foco + top `max_nodes` (1–100) vizinhos por + peso (>= 2), com todas as arestas do foco; `limit` (1–500) corta só as + arestas entre vizinhos (`include_neighbor_edges`). `depth` é ignorado. + + `entity_id` sempre parametrizado ($1) — nunca interpolado + (anti-injection).""" if not entity_id: return EntityNetworkRecord(nodes=[], edges=[]) + if ego_centered: + return await self._get_ego_network( + entity_id, max_nodes, limit, include_neighbor_edges + ) # Clamp defensivo: depth no máximo 2 (e mínimo 0). safe_depth = max(0, min(int(depth), 2)) async with self._pool.acquire() as conn: @@ -972,6 +1267,33 @@ async def get_entity_network( edges=[_row_to_network_edge(dict(r)) for r in edge_rows], ) + async def _get_ego_network( + self, + entity_id: str, + max_nodes: int, + limit: int, + include_neighbor_edges: bool, + ) -> EntityNetworkRecord: + safe_nodes = max(1, min(int(max_nodes), _EGO_MAX_NODES)) + safe_limit = max(1, min(int(limit), _EGO_MAX_NEIGHBOR_EDGES)) + async with self._pool.acquire() as conn: + node_rows = await conn.fetch( + _ENTITY_NETWORK_EGO_NODES_SQL, entity_id, safe_nodes, _EGO_MIN_WEIGHT + ) + edge_rows = await conn.fetch( + _ENTITY_NETWORK_EGO_EDGES_SQL, + entity_id, + safe_nodes, + _EGO_MIN_WEIGHT, + bool(include_neighbor_edges), + safe_limit, + ) + return _prune_ego_network( + entity_id, + [_row_to_network_node(dict(r)) for r in node_rows], + [_row_to_network_edge(dict(r)) for r in edge_rows], + ) + async def get_news_for_typesense(self, unique_id: str) -> Optional[TypesenseDocRecord]: query = _NEWS_TYPESENSE_SQL + " WHERE n.unique_id = $1" async with self._pool.acquire() as conn: @@ -1103,10 +1425,12 @@ async def entity_coverage( Parâmetros: - `entity_id`: QID Wikidata ou `dgb_` da entidade. - `granularity`: resolução temporal — `day`, `week` ou `month` (padrão). - - `date_from`/`date_to`: filtros de data ISO 8601 (None = sem limite). + - `date_from`/`date_to`: datas ISO `AAAA-MM-DD` em dias UTC (None = sem + limite); `date_from` inclusivo, `date_to` exclusivo. Retorna lista de dicts com chaves: `period`, `agency_key`, `agency_name`, - `article_count`, `total_mentions`, `avg_sentiment_score`. + `article_count`, `unique_content_count`, `total_mentions`, + `avg_sentiment_score`. """ async with self._pool.acquire() as conn: rows = await conn.fetch( diff --git a/src/graphql_api/schema/resolvers/analytics.py b/src/graphql_api/schema/resolvers/analytics.py index 6645244..69a0ed5 100644 --- a/src/graphql_api/schema/resolvers/analytics.py +++ b/src/graphql_api/schema/resolvers/analytics.py @@ -28,6 +28,10 @@ def _as_float(value): return None if value is None else float(value) +def _as_int(value): + return None if value is None else int(value) + + def _extract_facets(response: dict, field_name: str) -> list[dict]: """Extract facet counts for a given field from a Typesense response.""" for fc in response.get("facet_counts", []): @@ -178,6 +182,8 @@ async def agency_analytics( avg_readability_flesch=_as_float(row.get("avg_readability_flesch")), avg_word_count=_as_float(row.get("avg_word_count")), top_themes=[], + avg_readability_flesch_ptbr=_as_float(row.get("avg_readability_flesch_ptbr")), + readability_flesch_ptbr_count=_as_int(row.get("readability_flesch_ptbr_count")), ) for row in rows ] @@ -261,7 +267,7 @@ def _ts_filter(days: int) -> str: "per_page": 5, "filter_by": theme_filter, "sort_by": "trending_score:desc,published_at:desc", - "include_fields": "id,unique_id,title,agency,published_at,trending_score", + "include_fields": "id,unique_id,title,url,agency,published_at,trending_score", }) result.top_articles = [ ArticleSummary( @@ -276,6 +282,8 @@ def _ts_filter(days: int) -> str: else None ), trending_score=h["document"].get("trending_score"), + url=h["document"].get("url"), + agency_key=h["document"].get("agency"), ) for h in art_resp.get("hits", []) ] diff --git a/src/graphql_api/schema/resolvers/entities.py b/src/graphql_api/schema/resolvers/entities.py index bea8f6b..5544b76 100644 --- a/src/graphql_api/schema/resolvers/entities.py +++ b/src/graphql_api/schema/resolvers/entities.py @@ -50,7 +50,14 @@ def _news_record_to_article(record) -> Article: @strawberry.type class EntityQuery: - @strawberry.field(description="Série temporal de cobertura de uma entidade por agência") + @strawberry.field( + description=( + "Série temporal de cobertura de uma entidade por agência. `dateFrom`/`dateTo` " + "(AAAA-MM-DD, opcionais) em dias UTC; dateFrom inclusivo, dateTo exclusivo: para " + "incluir o dia D inteiro, passe dateTo = D + 1. `period` é o início do período em " + "UTC (\"AAAA-MM-DD 00:00:00+00\")." + ) + ) async def entity_coverage( self, info: Info, @@ -69,6 +76,7 @@ async def entity_coverage( article_count=int(row.get("article_count") or 0), total_mentions=int(row.get("total_mentions") or 0), avg_sentiment_score=row.get("avg_sentiment_score"), + unique_content_count=int(row.get("unique_content_count") or 0), ) for row in rows ] diff --git a/src/graphql_api/schema/resolvers/public_content.py b/src/graphql_api/schema/resolvers/public_content.py index bb89a98..f199c4b 100644 --- a/src/graphql_api/schema/resolvers/public_content.py +++ b/src/graphql_api/schema/resolvers/public_content.py @@ -18,6 +18,7 @@ datasource nos testes. """ +import enum from datetime import datetime, timedelta, timezone from typing import Optional @@ -82,6 +83,31 @@ class EntityNode: wikidata_url: Optional[str] = None description: Optional[str] = None agency_key: Optional[str] = None + article_count: Optional[int] = strawberry.field( + default=None, + description="Artigos que mencionam a entidade (entity_stats). Null sem estatística calculada.", + ) + unique_content_count: Optional[int] = strawberry.field( + default=None, + description=( + "Conteúdos distintos que mencionam a entidade: republicações (mesmo content_hash) contam " + "uma vez (entity_stats). Null sem estatística calculada." + ), + ) + + +@strawberry.enum( + description=( + "Ordenação de `relatedEntities`. WEIGHT: artigos em co-menção (legado). UNIQUE_CONTENT: " + "co-menções com conteúdo distinto (desconta republicações). LIFT: co-menção observada / " + "esperada pela frequência das duas entidades (destaca associações específicas em vez de " + "entidades genéricas). Valores nulos vão para o fim; desempate por weight." + ) +) +class RelatedEntityOrder(enum.Enum): + WEIGHT = "weight" + UNIQUE_CONTENT = "unique_content" + LIFT = "lift" @strawberry.type @@ -98,6 +124,44 @@ class RelatedEntity: wikidata_id: Optional[str] = None weight: int = 0 kind: str = "co_mention" + article_count: Optional[int] = strawberry.field( + default=None, + description="Artigos que mencionam o vizinho (entity_stats). Null sem estatística calculada.", + ) + unique_content_count: Optional[int] = strawberry.field( + default=None, + description=( + "Conteúdos distintos que mencionam o vizinho: republicações (mesmo content_hash) contam " + "uma vez (entity_stats). Null sem estatística calculada." + ), + ) + unique_content_weight: Optional[int] = strawberry.field( + default=None, + description=( + "Co-menções com conteúdo distinto: republicações (mesmo content_hash) contam uma vez. " + "`weight` conta artigos. Null antes do cálculo do grafo." + ), + ) + lift: Optional[float] = strawberry.field( + default=None, + description=( + "weight · N / (artigos da entidade · artigos do vizinho), com N = " + "entityGraphStats.totalArticles. > 1: co-menção acima do esperado ao acaso. Null quando " + "falta estatística de uma das pontas ou o total do grafo." + ), + ) + + +@strawberry.type( + description=( + "Totais do grafo de entidades (entity_graph_meta), recalculados pela DAG do grafo; " + "N do lift de `relatedEntities`." + ) +) +class EntityGraphStats: + total_articles: int + total_unique_content: int + computed_at: Optional[datetime] = None @strawberry.type @@ -108,6 +172,17 @@ class EntityNetworkNode: canonical_name: Optional[str] = None type: Optional[str] = None wikidata_id: Optional[str] = None + article_count: Optional[int] = strawberry.field( + default=None, + description="Artigos que mencionam a entidade (entity_stats). Null sem estatística calculada.", + ) + unique_content_count: Optional[int] = strawberry.field( + default=None, + description=( + "Conteúdos distintos que mencionam a entidade: republicações (mesmo content_hash) contam " + "uma vez (entity_stats). Null sem estatística calculada." + ), + ) @strawberry.type @@ -118,6 +193,13 @@ class EntityNetworkEdge: dst: str weight: int = 0 kind: str = "co_mention" + unique_content_weight: Optional[int] = strawberry.field( + default=None, + description=( + "Co-menções com conteúdo distinto: republicações (mesmo content_hash) contam uma vez. " + "`weight` conta artigos. Null antes do cálculo do grafo." + ), + ) @strawberry.type @@ -281,15 +363,18 @@ async def entity(self, info: Info, id: str) -> Optional[EntityNode]: wikidata_url=rec.wikidata_url, description=rec.description, agency_key=rec.agency_key, + article_count=rec.article_count, + unique_content_count=rec.unique_content_count, ) @strawberry.field( description=( "Entidades relacionadas a `id` (entity_id) por co-menção (Fase 6c). " "Lê a rede de co-menção materializada (`entity_edges`, 1-hop), " - "retorna os vizinhos hidratados do entity_registry, ordenados por " - "`weight` (nº de artigos em co-menção) desc, até `limit`. Retorna [] " - "sem Postgres ou sem vizinhos. PÚBLICO." + "retorna os vizinhos hidratados do entity_registry com weight >= " + "`minWeight` (default 1 = todos; 2 descarta co-menções únicas), " + "ordenados por `orderBy` (default WEIGHT = nº de artigos em co-menção) " + "desc, até `limit`. Retorna [] sem Postgres ou sem vizinhos. PÚBLICO." ) ) async def related_entities( @@ -297,12 +382,16 @@ async def related_entities( info: Info, id: str, limit: int = 12, + order_by: RelatedEntityOrder = RelatedEntityOrder.WEIGHT, + min_weight: int = 1, ) -> list[RelatedEntity]: ctx = info.context pg = ctx.postgres_ds if pg is None: return [] - records = await pg.get_related_entities(id, limit=limit) + records = await pg.get_related_entities( + id, limit=limit, order_by=order_by.value, min_weight=min_weight + ) return [ RelatedEntity( canonical_id=rec.entity_id, @@ -311,18 +400,46 @@ async def related_entities( wikidata_id=rec.wikidata_id, weight=rec.weight, kind=rec.kind, + article_count=rec.article_count, + unique_content_count=rec.unique_content_count, + unique_content_weight=rec.unique_content_weight, + lift=rec.lift, ) for rec in records ] + @strawberry.field( + description=( + "Totais do grafo de entidades (entity_graph_meta): artigos e conteúdos " + "distintos considerados e quando foram calculados. Null sem Postgres ou " + "antes da primeira execução da DAG do grafo. PÚBLICO." + ) + ) + async def entity_graph_stats(self, info: Info) -> Optional[EntityGraphStats]: + pg = info.context.postgres_ds + if pg is None: + return None + rec = await pg.get_entity_graph_stats() + if rec is None: + return None + return EntityGraphStats( + total_articles=rec.total_articles, + total_unique_content=rec.total_unique_content, + computed_at=rec.computed_at, + ) + @strawberry.field( description=( "Ego-network (nós + arestas) ao redor de `id` (entity_id) para a " - "visualização de rede (Fase 6c). Travessia não-direcionada na rede " - "de co-menção (`entity_edges`) via CTE recursiva até `depth` saltos " - "(CLAMPado a no máx 2; profundidades maiores ficam para o Neo4j " - "futuro). `limit` limita o nº de arestas (cap de tamanho do grafo). " - "Retorna {nodes:[], edges:[]} sem Postgres. PÚBLICO." + "visualização de rede (Fase 6c). Modo legado (default): travessia " + "não-direcionada na rede de co-menção (`entity_edges`) via CTE " + "recursiva até `depth` saltos (CLAMPado a no máx 2; profundidades " + "maiores ficam para o Neo4j futuro); `limit` limita o nº de arestas " + "(cap de tamanho do grafo). `egoCentered: true`: a entidade + seus " + "`maxNodes` (1–100) vizinhos mais fortes (weight >= 2), com TODAS as " + "arestas da entidade; `limit` (1–500) corta só as arestas entre " + "vizinhos (`includeNeighborEdges`); `depth` é ignorado. Retorna " + "{nodes:[], edges:[]} sem Postgres. PÚBLICO." ) ) async def entity_network( @@ -331,12 +448,22 @@ async def entity_network( id: str, depth: int = 1, limit: int = 50, + ego_centered: bool = False, + max_nodes: int = 30, + include_neighbor_edges: bool = True, ) -> EntityNetwork: ctx = info.context pg = ctx.postgres_ds if pg is None: return EntityNetwork(nodes=[], edges=[]) - net = await pg.get_entity_network(id, depth=depth, limit=limit) + net = await pg.get_entity_network( + id, + depth=depth, + limit=limit, + ego_centered=ego_centered, + max_nodes=max_nodes, + include_neighbor_edges=include_neighbor_edges, + ) return EntityNetwork( nodes=[ EntityNetworkNode( @@ -344,6 +471,8 @@ async def entity_network( canonical_name=n.canonical_name, type=n.type, wikidata_id=n.wikidata_id, + article_count=n.article_count, + unique_content_count=n.unique_content_count, ) for n in net.nodes ], @@ -353,6 +482,7 @@ async def entity_network( dst=e.dst, weight=e.weight, kind=e.kind, + unique_content_weight=e.unique_content_weight, ) for e in net.edges ], diff --git a/src/graphql_api/schema/types/analytics.py b/src/graphql_api/schema/types/analytics.py index f12b931..cb66604 100644 --- a/src/graphql_api/schema/types/analytics.py +++ b/src/graphql_api/schema/types/analytics.py @@ -65,18 +65,35 @@ class AgencyPeriodMetrics: pct_negative: Optional[float] = strawberry.field( description="Fração (0 a 1) dos artigos COM rótulo de sentimento que são negativos. Null se nenhum tem.", ) - avg_readability_flesch: Optional[float] + avg_readability_flesch: Optional[float] = strawberry.field( + description="Média do Flesch pela fórmula inglesa (legado; escala distorcida para português).", + ) avg_word_count: Optional[float] top_themes: list[ThemeStats] + avg_readability_flesch_ptbr: Optional[float] = strawberry.field( + default=None, + description=( + "Média do Flesch adaptado ao português (Martins et al., 1996) dos artigos que o têm. " + "Null quando nenhum tem." + ), + ) + readability_flesch_ptbr_count: Optional[int] = strawberry.field( + default=None, + description="Nº de artigos do grupo com Flesch pt-BR calculado (base de avgReadabilityFleschPtbr).", + ) @strawberry.type class ArticleSummary: unique_id: str title: str - agency_name: Optional[str] + agency_name: Optional[str] = strawberry.field( + description="Key da agência (o mesmo valor de agencyKey, apesar do nome). Mantido por compatibilidade.", + ) published_at: Optional[str] trending_score: Optional[float] + url: Optional[str] = strawberry.field(default=None, description="Link do artigo no portal de origem.") + agency_key: Optional[str] = strawberry.field(default=None, description="Key da agência (ex.: 'saude').") @strawberry.type diff --git a/src/graphql_api/schema/types/entities.py b/src/graphql_api/schema/types/entities.py index 492b5aa..c90a926 100644 --- a/src/graphql_api/schema/types/entities.py +++ b/src/graphql_api/schema/types/entities.py @@ -26,6 +26,14 @@ class EntityCoveragePoint: article_count: int total_mentions: int avg_sentiment_score: Optional[float] + unique_content_count: int = strawberry.field( + default=0, + description=( + "Conteúdos distintos (content_hash) creditados a esta agência: cada conteúdo conta só " + "para a primeira agência que o publicou no intervalo consultado, então o campo soma " + "entre agências e períodos sem contar republicações. articleCount conta artigos." + ), + ) @strawberry.type diff --git a/src/graphql_api/schema/types/features.py b/src/graphql_api/schema/types/features.py index 427dbf6..594d897 100644 --- a/src/graphql_api/schema/types/features.py +++ b/src/graphql_api/schema/types/features.py @@ -56,7 +56,17 @@ class ArticleFeatures: unique_sessions: Optional[int] = None trending_score: Optional[float] = None word_count: Optional[int] = None - readability_flesch: Optional[float] = None + readability_flesch: Optional[float] = strawberry.field( + default=None, + description="Índice de Flesch pela fórmula inglesa (legado; escala distorcida para português).", + ) + readability_flesch_ptbr: Optional[float] = strawberry.field( + default=None, + description=( + "Índice de Flesch adaptado ao português (Martins et al., 1996): 0–100, maior = mais fácil. " + "Null até o artigo ser recalculado." + ), + ) def _as_int(value: Any) -> Optional[int]: @@ -163,4 +173,5 @@ def article_features_from_json( trending_score=_as_float(features.get("trending_score")), word_count=_as_int(features.get("word_count")), readability_flesch=_as_float(features.get("readability_flesch")), + readability_flesch_ptbr=_as_float(features.get("readability_flesch_ptbr")), ) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index a4d342c..9bdd07d 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -5,11 +5,22 @@ vai SEMPRE parametrizado ($1), o clamp de depth e o mapeamento das linhas. """ +from datetime import date, datetime, timezone +from decimal import Decimal from unittest.mock import AsyncMock, MagicMock import pytest from graphql_api.datasources.postgres import ( + _CONTENT_DEDUP_KEY_SQL, + _ENTITY_COVERAGE_SQL, + _ENTITY_NETWORK_EDGES_SQL, + _ENTITY_NETWORK_EGO_EDGES_SQL, + _ENTITY_NETWORK_EGO_NODES_SQL, + _ENTITY_NETWORK_NODES_SQL, + _ENTITY_REGISTRY_SQL, + _RELATED_ENTITIES_SQL, + EntityGraphStatsRecord, EntityNetworkEdgeRecord, EntityNetworkNodeRecord, PostgresDatasource, @@ -17,16 +28,22 @@ ) -def _make_mock_pool(fetch_results=None): +def _flat(sql: str) -> str: + return " ".join(sql.split()) + + +def _make_mock_pool(fetch_results=None, *, fetchrow=None): """Pool com conn.fetch retornando, em sequência, cada item de `fetch_results` (lista de listas de rows). Útil quando o método faz - múltiplas queries (network: nós + arestas).""" + múltiplas queries (network: nós + arestas). `fetchrow` define o retorno + de `conn.fetchrow` (linha única).""" pool = MagicMock() conn = AsyncMock() if fetch_results is None: conn.fetch = AsyncMock(return_value=[]) else: conn.fetch = AsyncMock(side_effect=list(fetch_results)) + conn.fetchrow = AsyncMock(return_value=fetchrow) acm = AsyncMock() acm.__aenter__ = AsyncMock(return_value=conn) @@ -80,6 +97,103 @@ async def test_empty_entity_id_returns_empty_without_query(self): assert result == [] conn.fetch.assert_not_awaited() + @pytest.mark.asyncio + async def test_defaults_ordem_por_peso_e_peso_minimo_1(self): + # Default retrocompatível: weight >= 1 devolve a mesma lista de antes + # (chips de /entidades no portal); quem quiser cortar ruído passa 2. + pool, conn = _make_mock_pool([[]]) + ds = PostgresDatasource(pool) + + await ds.get_related_entities("Q123") + + # $1 = entity_id, $2 = limit, $3 = ordenação, $4 = peso mínimo. + assert conn.fetch.await_args.args == (_RELATED_ENTITIES_SQL, "Q123", 12, "weight", 1) + + @pytest.mark.asyncio + @pytest.mark.parametrize("order_by", ["weight", "unique_content", "lift"]) + async def test_repassa_ordenacao(self, order_by): + pool, conn = _make_mock_pool([[]]) + ds = PostgresDatasource(pool) + + await ds.get_related_entities("Q123", limit=5, order_by=order_by, min_weight=3) + + assert conn.fetch.await_args.args[1:] == ("Q123", 5, order_by, 3) + + @pytest.mark.asyncio + async def test_ordenacao_invalida_levanta_sem_query(self): + pool, conn = _make_mock_pool([[]]) + ds = PostgresDatasource(pool) + + with pytest.raises(ValueError): + await ds.get_related_entities("Q123", order_by="weight; DROP TABLE x") + conn.fetch.assert_not_awaited() + + @pytest.mark.asyncio + @pytest.mark.parametrize(("min_weight", "esperado"), [(0, 1), (-5, 1), (1, 1), (7, 7)]) + async def test_clampa_peso_minimo(self, min_weight, esperado): + pool, conn = _make_mock_pool([[]]) + ds = PostgresDatasource(pool) + + await ds.get_related_entities("Q123", min_weight=min_weight) + + assert conn.fetch.await_args.args[4] == esperado + + @pytest.mark.asyncio + async def test_mapeia_stats_e_lift_com_nulos(self): + rows = [ + { + "other_id": "Q2", + "weight": 40, + "kind": "co_mention", + "canonical_name": "MCTI", + "type": "ORG", + "wikidata_id": "Q2", + "article_count": 900, + "unique_content_count": 700, + "unique_content_weight": 31, + # float8 do Postgres; Decimal por garantia (graphql-core 3.3 rejeita). + "lift": Decimal("2.5"), + }, + { + "other_id": "Q3", + "weight": 3, + "kind": "co_mention", + "canonical_name": "Sem stats", + "type": "ORG", + "wikidata_id": None, + "article_count": None, + "unique_content_count": None, + "unique_content_weight": None, + "lift": None, + }, + ] + pool, _ = _make_mock_pool([rows]) + ds = PostgresDatasource(pool) + + a, b = await ds.get_related_entities("Q1", order_by="lift") + + assert (a.article_count, a.unique_content_count, a.unique_content_weight) == (900, 700, 31) + assert a.lift == 2.5 + assert isinstance(a.lift, float) + assert (b.article_count, b.unique_content_count, b.unique_content_weight, b.lift) == ( + None, + None, + None, + None, + ) + + def test_sql_lift_nulo_sem_stats_e_ordem_com_nulls_last(self): + sql = _flat(_RELATED_ENTITIES_SQL) + assert "e.weight >= $4" in sql + assert "LEFT JOIN entity_stats" in sql + assert "LEFT JOIN entity_graph_meta" in sql + # lift = weight·N/(cnt_ego·cnt_nbr), NULL se qualquer termo faltar ou for 0. + assert "NULLIF(m.total_articles, 0)" in sql + assert "NULLIF(se.article_count, 0)" in sql + assert "NULLIF(so.article_count, 0)" in sql + assert "DESC NULLS LAST" in sql + assert sql.endswith("weight DESC, other_id ASC LIMIT $2") + class TestGetEntityNetwork: @pytest.mark.asyncio @@ -145,3 +259,341 @@ async def test_empty_entity_id_returns_empty_without_query(self): assert net.nodes == [] assert net.edges == [] conn.fetch.assert_not_awaited() + + @pytest.mark.asyncio + async def test_legacy_mantem_sql_e_parametros(self): + # Modo legado (default, usado pelo portal): mesmas queries recursivas e + # os mesmos parâmetros posicionais de antes do modo ego. + pool, conn = _make_mock_pool([[], []]) + ds = PostgresDatasource(pool) + + await ds.get_entity_network("Q1", depth=1, limit=50) + + nodes_call, edges_call = conn.fetch.await_args_list + assert nodes_call.args == (_ENTITY_NETWORK_NODES_SQL, "Q1", 1) + assert edges_call.args == (_ENTITY_NETWORK_EDGES_SQL, "Q1", 1, 50) + + def test_legacy_sql_so_ganha_left_joins_de_stats(self): + nodes = _flat(_ENTITY_NETWORK_NODES_SQL) + edges = _flat(_ENTITY_NETWORK_EDGES_SQL) + assert "WITH RECURSIVE reachable" in nodes + assert "LEFT JOIN entity_stats s ON s.entity_id = r.entity_id" in nodes + assert "s.article_count AS article_count" in nodes + assert "s.unique_content_count AS unique_content_count" in nodes + assert "WITH RECURSIVE reachable" in edges + assert "e.unique_content_count AS unique_content_weight" in edges + assert edges.endswith("ORDER BY e.weight DESC LIMIT $3") + + @pytest.mark.asyncio + async def test_legacy_mapeia_stats_e_tolera_ausencia(self): + node_rows = [ + { + "entity_id": "Q1", + "canonical_name": "Finep", + "type": "ORG", + "wikidata_id": "Q1", + "article_count": 120, + "unique_content_count": 95, + }, + # Entidade sem linha em entity_stats (LEFT JOIN → NULL). + { + "entity_id": "Q2", + "canonical_name": "MCTI", + "type": "ORG", + "wikidata_id": "Q2", + "article_count": None, + "unique_content_count": None, + }, + ] + edge_rows = [ + {"src": "Q1", "dst": "Q2", "weight": 9, "kind": "co_mention", "unique_content_weight": 7}, + ] + pool, _ = _make_mock_pool([node_rows, edge_rows]) + ds = PostgresDatasource(pool) + + net = await ds.get_entity_network("Q1") + + assert net.nodes[0].article_count == 120 + assert net.nodes[0].unique_content_count == 95 + assert net.nodes[1].article_count is None + assert net.nodes[1].unique_content_count is None + assert net.edges[0].unique_content_weight == 7 + + +def _ego_rows(): + """Foco Q1 com vizinhos Q2 e Q3; aresta Q2–Q3 entre vizinhos.""" + node_rows = [ + {"entity_id": "Q1", "canonical_name": "Finep", "type": "ORG", "wikidata_id": "Q1"}, + {"entity_id": "Q2", "canonical_name": "MCTI", "type": "ORG", "wikidata_id": "Q2"}, + {"entity_id": "Q3", "canonical_name": "CNPq", "type": "ORG", "wikidata_id": "Q3"}, + ] + edge_rows = [ + {"src": "Q1", "dst": "Q2", "weight": 40, "kind": "co_mention"}, + {"src": "Q1", "dst": "Q3", "weight": 3, "kind": "co_mention"}, + {"src": "Q2", "dst": "Q3", "weight": 25, "kind": "co_mention"}, + ] + return node_rows, edge_rows + + +class TestGetEntityNetworkEgo: + @pytest.mark.asyncio + async def test_usa_sqls_ego_com_parametros(self): + node_rows, edge_rows = _ego_rows() + pool, conn = _make_mock_pool([node_rows, edge_rows]) + ds = PostgresDatasource(pool) + + await ds.get_entity_network( + "Q1", depth=2, limit=80, ego_centered=True, max_nodes=10, include_neighbor_edges=True + ) + + nodes_call, edges_call = conn.fetch.await_args_list + # $1 = foco, $2 = maxNodes, $3 = peso mínimo; depth é ignorado. + assert nodes_call.args == (_ENTITY_NETWORK_EGO_NODES_SQL, "Q1", 10, 2) + # $4 = incluir arestas entre vizinhos, $5 = corte dessas arestas. + assert edges_call.args == (_ENTITY_NETWORK_EGO_EDGES_SQL, "Q1", 10, 2, True, 80) + + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("max_nodes", "limit", "esperado"), + [(0, 0, (1, 1)), (-3, -9, (1, 1)), (999, 10_000, (100, 500)), (30, 50, (30, 50))], + ) + async def test_clampa_max_nodes_e_limit(self, max_nodes, limit, esperado): + pool, conn = _make_mock_pool([[], []]) + ds = PostgresDatasource(pool) + + await ds.get_entity_network("Q1", limit=limit, ego_centered=True, max_nodes=max_nodes) + + nodes_call, edges_call = conn.fetch.await_args_list + assert nodes_call.args[2] == esperado[0] + assert edges_call.args[2] == esperado[0] + assert edges_call.args[5] == esperado[1] + + @pytest.mark.asyncio + async def test_sem_arestas_entre_vizinhos(self): + pool, conn = _make_mock_pool([[], []]) + ds = PostgresDatasource(pool) + + await ds.get_entity_network("Q1", ego_centered=True, include_neighbor_edges=False) + + assert conn.fetch.await_args_list[1].args[4] is False + + def test_sql_ego_nunca_corta_arestas_do_foco(self): + sql = _flat(_ENTITY_NETWORK_EGO_EDGES_SQL) + # Vizinhos = top $2 arestas do foco com weight >= $3; o LIMIT $5 só vale + # para as arestas entre vizinhos; a união final não tem LIMIT. + assert "e.weight >= $3" in sql + assert "ORDER BY e.weight DESC, other_id ASC LIMIT $2" in sql + assert "LIMIT $5" in sql + tail = sql.rsplit("UNION ALL", 1)[1] + assert "LIMIT" not in tail + assert "$4::boolean" in sql + assert "RECURSIVE" not in sql + assert "RECURSIVE" not in _flat(_ENTITY_NETWORK_EGO_NODES_SQL) + + def test_sql_ego_nos_e_arestas_escolhem_os_mesmos_vizinhos(self): + # Nós e arestas são duas queries: o critério de vizinhança precisa ser + # idêntico (mesma ordem determinística + LIMIT) para não haver órfãos. + criterio = "ORDER BY e.weight DESC, other_id ASC LIMIT $2" + assert criterio in _flat(_ENTITY_NETWORK_EGO_NODES_SQL) + assert criterio in _flat(_ENTITY_NETWORK_EGO_EDGES_SQL) + assert "LEFT JOIN entity_stats s ON s.entity_id = r.entity_id" in _flat(_ENTITY_NETWORK_EGO_NODES_SQL) + + @pytest.mark.asyncio + async def test_mantem_todas_as_arestas_do_foco(self): + node_rows, edge_rows = _ego_rows() + pool, _ = _make_mock_pool([node_rows, edge_rows]) + ds = PostgresDatasource(pool) + + net = await ds.get_entity_network("Q1", limit=1, ego_centered=True) + + pares = {(e.src, e.dst) for e in net.edges} + assert {("Q1", "Q2"), ("Q1", "Q3")} <= pares + assert ("Q2", "Q3") in pares + + @pytest.mark.asyncio + async def test_sem_nos_ou_arestas_orfaos(self): + # Defesa contra o grafo mudar entre as duas queries (DAG recalculando + # entity_edges): aresta com ponta fora dos nós é descartada, e vizinho + # sem aresta para o foco também. + node_rows, edge_rows = _ego_rows() + node_rows.append({"entity_id": "Q9", "canonical_name": "Solto", "type": "ORG", "wikidata_id": None}) + edge_rows.append({"src": "Q2", "dst": "Q7", "weight": 30, "kind": "co_mention"}) + pool, _ = _make_mock_pool([node_rows, edge_rows]) + ds = PostgresDatasource(pool) + + net = await ds.get_entity_network("Q1", ego_centered=True) + + ids = {n.entity_id for n in net.nodes} + assert ids == {"Q1", "Q2", "Q3"} + for e in net.edges: + assert e.src in ids and e.dst in ids + com_aresta = {e.src for e in net.edges} | {e.dst for e in net.edges} + assert ids <= com_aresta + + @pytest.mark.asyncio + async def test_par_invertido_duplicado_nao_duplica_no_nem_aresta(self): + # entity_edges não tem CHECK (src_id < dst_id): a ordem canônica é só + # convenção da DAG. Se um par vier nos dois sentidos, a rede continua + # com um nó e uma aresta por par (a primeira, de maior peso). + node_rows, edge_rows = _ego_rows() + node_rows.insert(2, dict(node_rows[1])) # Q2 repetido + edge_rows.insert(1, {"src": "Q2", "dst": "Q1", "weight": 5, "kind": "co_mention"}) + pool, _ = _make_mock_pool([node_rows, edge_rows]) + ds = PostgresDatasource(pool) + + net = await ds.get_entity_network("Q1", ego_centered=True) + + assert [n.entity_id for n in net.nodes] == ["Q1", "Q2", "Q3"] + pares = [frozenset((e.src, e.dst)) for e in net.edges] + assert len(pares) == len(set(pares)) == 3 + assert next(e for e in net.edges if {e.src, e.dst} == {"Q1", "Q2"}).weight == 40 + + @pytest.mark.asyncio + async def test_empty_entity_id_returns_empty_without_query(self): + pool, conn = _make_mock_pool([[], []]) + ds = PostgresDatasource(pool) + net = await ds.get_entity_network("", ego_centered=True) + assert net.nodes == [] + assert net.edges == [] + conn.fetch.assert_not_awaited() + + +class TestGetEntityStats: + def test_entity_registry_sql_junta_entity_stats(self): + sql = _flat(_ENTITY_REGISTRY_SQL) + assert "LEFT JOIN entity_stats s ON s.entity_id = r.entity_id" in sql + assert "s.article_count AS article_count" in sql + assert "s.unique_content_count AS unique_content_count" in sql + + @pytest.mark.asyncio + async def test_get_entity_mapeia_stats(self): + row = { + "entity_id": "Q1", + "canonical_name": "Finep", + "type": "ORG", + "aliases": "[]", + "wikidata_id": "Q1", + "wikidata_url": None, + "description": None, + "agency_key": None, + "article_count": 1200, + "unique_content_count": 950, + } + pool, conn = _make_mock_pool(fetchrow=row) + ds = PostgresDatasource(pool) + + rec = await ds.get_entity("Q1") + + assert (rec.article_count, rec.unique_content_count) == (1200, 950) + assert conn.fetchrow.await_args.args == (_ENTITY_REGISTRY_SQL, "Q1") + + @pytest.mark.asyncio + async def test_get_entity_sem_stats(self): + row = {"entity_id": "Q1", "article_count": None, "unique_content_count": None} + pool, _ = _make_mock_pool(fetchrow=row) + ds = PostgresDatasource(pool) + + rec = await ds.get_entity("Q1") + + assert rec.article_count is None + assert rec.unique_content_count is None + + +class TestGetEntityGraphStats: + @pytest.mark.asyncio + async def test_mapeia_meta(self): + computed = datetime(2026, 10, 20, 3, 0, tzinfo=timezone.utc) + row = {"total_articles": 333000, "total_unique_content": 250000, "computed_at": computed} + pool, conn = _make_mock_pool(fetchrow=row) + ds = PostgresDatasource(pool) + + stats = await ds.get_entity_graph_stats() + + assert stats == EntityGraphStatsRecord( + total_articles=333000, total_unique_content=250000, computed_at=computed + ) + assert "FROM entity_graph_meta" in conn.fetchrow.await_args.args[0] + + @pytest.mark.asyncio + async def test_none_sem_linha(self): + pool, _ = _make_mock_pool(fetchrow=None) + ds = PostgresDatasource(pool) + + assert await ds.get_entity_graph_stats() is None + + +class TestEntityCoverageDatas: + """entityCoverage: dias UTC, dateFrom inclusivo e dateTo EXCLUSIVO (GQL-1). + + Antes, `published_at <= $4::timestamptz` com uma data comparava com a + meia-noite do dateTo no fuso da sessão: na prática exclusivo, exceto pelos + artigos publicados exatamente às 00:00:00.""" + + @pytest.mark.asyncio + async def test_datas_vao_como_date(self): + pool, conn = _make_mock_pool([[]]) + ds = PostgresDatasource(pool) + + await ds.entity_coverage("Q1", "day", "2026-10-01", "2026-10-08") + + assert conn.fetch.await_args.args == ( + _ENTITY_COVERAGE_SQL, + "day", + "Q1", + date(2026, 10, 1), + date(2026, 10, 8), + ) + + @pytest.mark.asyncio + async def test_sem_datas_vao_nulas(self): + pool, conn = _make_mock_pool([[]]) + ds = PostgresDatasource(pool) + + await ds.entity_coverage("Q1") + + assert conn.fetch.await_args.args[1:] == ("month", "Q1", None, None) + + def test_sql_date_to_exclusivo_em_utc(self): + sql = _flat(_ENTITY_COVERAGE_SQL) + assert "ne.published_at >= ($3::date)::timestamp AT TIME ZONE 'UTC'" in sql + assert "ne.published_at < ($4::date)::timestamp AT TIME ZONE 'UTC'" in sql + assert "<= $4" not in sql + assert "::timestamptz" not in sql + + def test_sql_period_em_utc_com_formato_inalterado(self): + # Mesmo texto que `timestamptz::text` dava com a sessão em UTC + # ("2026-08-27 00:00:00+00"), mas sem depender do fuso da sessão. + sql = _flat(_ENTITY_COVERAGE_SQL) + assert ( + "to_char(DATE_TRUNC($1, ne.published_at AT TIME ZONE 'UTC'), " + "'YYYY-MM-DD HH24:MI:SS\"+00\"') AS period" + ) in sql + + +class TestEntityCoverageConteudoUnico: + """uniqueContentCount: cada conteúdo (COALESCE(content_hash, unique_id)) é + creditado só à PRIMEIRA agência que o publicou no intervalo — o campo soma + entre agências e períodos sem contar republicações duas vezes.""" + + def test_sql_credita_a_primeira_publicacao(self): + sql = _flat(_ENTITY_COVERAGE_SQL) + assert "PARTITION BY COALESCE(n.content_hash, ne.unique_id)" in sql + assert "ORDER BY n.published_at, ne.unique_id" in sql + # Uma linha por artigo (PK de news_entities + joins 1:1): COUNT(*) é exato. + assert "COUNT(*) FILTER (WHERE m.is_first) AS unique_content_count" in sql + + def test_chave_de_dedup_isolada_numa_constante(self): + # A chave exata por content_hash quase não pega republicações entre + # órgãos (raramente idênticas byte a byte); trocar por uma chave de + # quase-duplicata deve mexer só nesta constante, sem mudar a API. + assert _CONTENT_DEDUP_KEY_SQL == "COALESCE(n.content_hash, ne.unique_id)" + sql = _flat(_ENTITY_COVERAGE_SQL) + assert f"PARTITION BY {_CONTENT_DEDUP_KEY_SQL}" in sql + assert sql.count("content_hash") == 1 + + def test_sql_preserva_agregados_existentes(self): + sql = _flat(_ENTITY_COVERAGE_SQL) + assert "COUNT(*) AS article_count" in sql + assert "SUM(m.count) AS total_mentions" in sql + assert "AVG(m.sentiment_score) AS avg_sentiment_score" in sql + assert "GROUP BY period, m.agency_key, m.agency_name" in sql diff --git a/tests/datasources/test_postgres_features.py b/tests/datasources/test_postgres_features.py index 8487ee7..e1574eb 100644 --- a/tests/datasources/test_postgres_features.py +++ b/tests/datasources/test_postgres_features.py @@ -435,3 +435,29 @@ async def test_entity_coverage_le_score_aninhado_com_fallback(self): sql = _flat(conn.fetch.await_args.args[0]) assert _NESTED_SCORE in sql assert "AVG((nf.features->>'sentiment_score')::float)" not in sql + + +class TestFleschPtbrNasQueries: + """GQL-1: agencyAnalytics (MONTH/WEEK e DAY) agrega também o Flesch pt-BR + (`readability_flesch_ptbr`) e conta quantos artigos o têm (cobertura do + backfill); o `avg_readability_flesch` continua igual.""" + + async def _sql(self, granularity: str) -> str: + pool, conn = _make_fetch_pool([]) + ds = PostgresDatasource(pool) + await ds.agency_analytics(granularity, ["mec"], "2026-09-01", "2026-09-30") + return _flat(conn.fetch.await_args.args[0]) + + @pytest.mark.asyncio + @pytest.mark.parametrize("granularity", ["month", "week", "day"]) + async def test_media_e_contagem_ptbr(self, granularity): + sql = await self._sql(granularity) + assert "AVG((nf.features->>'readability_flesch_ptbr')::float) AS avg_readability_flesch_ptbr" in sql + assert "COUNT(nf.features->>'readability_flesch_ptbr') AS readability_flesch_ptbr_count" in sql + assert "AVG((nf.features->>'readability_flesch')::float) AS avg_readability_flesch" in sql + + @pytest.mark.asyncio + async def test_day_preenche_contagem_zero_nos_dias_sem_artigo(self): + sql = await self._sql("day") + assert "da.avg_readability_flesch_ptbr" in sql + assert "COALESCE(da.readability_flesch_ptbr_count, 0) AS readability_flesch_ptbr_count" in sql diff --git a/tests/resolvers/test_analytics.py b/tests/resolvers/test_analytics.py index f232dc0..0bc2d0c 100644 --- a/tests/resolvers/test_analytics.py +++ b/tests/resolvers/test_analytics.py @@ -475,6 +475,66 @@ async def test_metricas_numeric_do_postgres_serializam_como_float(self): } assert all(v is None for v in second.values()) + @pytest.mark.asyncio + async def test_flesch_ptbr_media_float_e_contagem(self): + """GQL-1: Flesch pt-BR ao lado do inglês; AVG chega como Decimal.""" + from decimal import Decimal + + mock_pg = AsyncMock() + mock_pg.agency_analytics = AsyncMock(return_value=[ + { + "period": "2026-09-01 00:00:00+00", + "agency_key": "saude", + "agency_name": "Ministério da Saúde", + "article_count": 120, + "avg_readability_flesch": Decimal("33.5"), + "avg_readability_flesch_ptbr": Decimal("51.75"), + "readability_flesch_ptbr_count": 118, + }, + # Período sem nenhum artigo com Flesch pt-BR (antes do backfill). + { + "period": "2026-10-01 00:00:00+00", + "agency_key": "saude", + "agency_name": "Ministério da Saúde", + "article_count": 10, + "avg_readability_flesch": None, + "avg_readability_flesch_ptbr": None, + "readability_flesch_ptbr_count": 0, + }, + ]) + query = """ + query { + agencyAnalytics(agencies: ["saude"] dateFrom: "2026-09-01" dateTo: "2026-10-31" granularity: MONTH) { + avgReadabilityFlesch avgReadabilityFleschPtbr readabilityFleschPtbrCount + } + } + """ + result = await test_schema.execute(query, context_value=FakeContext(postgres_ds=mock_pg)) + assert result.errors is None + assert result.data["agencyAnalytics"] == [ + {"avgReadabilityFlesch": 33.5, "avgReadabilityFleschPtbr": 51.75, "readabilityFleschPtbrCount": 118}, + {"avgReadabilityFlesch": None, "avgReadabilityFleschPtbr": None, "readabilityFleschPtbrCount": 0}, + ] + + @pytest.mark.asyncio + async def test_flesch_ptbr_ausente_na_linha_vira_null(self): + mock_pg = AsyncMock() + mock_pg.agency_analytics = AsyncMock(return_value=[ + {"period": "2026-09", "agency_key": "mec", "agency_name": "MEC", "article_count": 1}, + ]) + query = """ + query { + agencyAnalytics(agencies: ["mec"] dateFrom: "2026-09-01" dateTo: "2026-09-30") { + avgReadabilityFleschPtbr readabilityFleschPtbrCount + } + } + """ + result = await test_schema.execute(query, context_value=FakeContext(postgres_ds=mock_pg)) + assert result.errors is None + assert result.data["agencyAnalytics"] == [ + {"avgReadabilityFleschPtbr": None, "readabilityFleschPtbrCount": None} + ] + @pytest.mark.asyncio async def test_retorna_metricas_por_periodo(self): mock_pg = AsyncMock() @@ -586,6 +646,78 @@ async def test_window_maior_que_baseline_levanta_erro(self): assert result.errors is not None +class TestTrendingThemesTopArticles: + """GQL-1: topArticles traz o link do artigo (url) e agencyKey; o Gobus + citava artigos sem link.""" + + @staticmethod + def _ts_mock(calls): + ts_mock = MagicMock() + + def _search(params): + calls.append(params) + if params.get("per_page") == 0: + return { + "found": 100, + "facet_counts": [ + {"field_name": "theme_1_level_1_label", "counts": [{"value": "Saúde", "count": 21}]} + ], + } + return { + "hits": [ + { + "document": { + "unique_id": "a1", + "title": "Vacinação", + "url": "https://www.gov.br/saude/pt-br/a1", + "agency": "saude", + "published_at": 1760000000, + "trending_score": 2.0, + } + }, + {"document": {"id": "a2", "title": "Sem url"}}, + ] + } + + ts_mock.client.collections["news"].documents.search.side_effect = _search + return ts_mock + + @pytest.mark.asyncio + async def test_top_articles_trazem_url_e_agency_key(self): + calls = [] + query = """ + query { + trendingThemes(windowDays: 7 baselineDays: 28) { + themeLabel + topArticles { uniqueId url agencyKey agencyName } + } + } + """ + result = await test_schema.execute(query, context_value=FakeContext(typesense_ds=self._ts_mock(calls))) + assert result.errors is None + top = result.data["trendingThemes"][0]["topArticles"] + assert top == [ + { + "uniqueId": "a1", + "url": "https://www.gov.br/saude/pt-br/a1", + "agencyKey": "saude", + "agencyName": "saude", + }, + {"uniqueId": "a2", "url": None, "agencyKey": None, "agencyName": None}, + ] + article_search = calls[-1] + assert "url" in article_search["include_fields"].split(",") + + def test_sdl_article_summary(self): + sdl = test_schema.as_str() + block = sdl.split("type ArticleSummary {", 1)[1].split("}", 1)[0] + assert "url: String\n" in block + assert "agencyKey: String\n" in block + # agencyName continua (compat) e documenta que carrega a key. + assert "agencyName: String\n" in block + assert "agencyKey" in block.split("agencyName: String", 1)[0] + + class TestAgencyAnalyticsDayGapFill: """Testa que granularity=DAY usa generate_series (gap-fill) e MONTH usa DATE_TRUNC.""" diff --git a/tests/resolvers/test_article_features.py b/tests/resolvers/test_article_features.py index c4b868d..416be7d 100644 --- a/tests/resolvers/test_article_features.py +++ b/tests/resolvers/test_article_features.py @@ -373,3 +373,42 @@ async def test_malformed_annotations_are_skipped(): {"start": 0, "end": 5, "type": "ORG", "text": "Valid", "canonicalId": None}, {"start": 7, "end": 9, "type": "LOC", "text": "OK2", "canonicalId": None}, ] + + +# GQL-1: Flesch adaptado ao português (Martins et al., 1996), gravado pelo +# data-platform em `readability_flesch_ptbr`. O `readability_flesch` (fórmula +# inglesa) continua igual. +FLESCH_PTBR_QUERY = """ + query($id: String!) { + article(uniqueId: $id) { + features { readabilityFlesch readabilityFleschPtbr } + } + } +""" + + +@pytest.mark.asyncio +async def test_readability_flesch_ptbr_mapeado(): + ts = _ts_with_article("a") + pg = _pg_with_features({"a": {"readability_flesch": 12.5, "readability_flesch_ptbr": 48.25}}) + ctx = GraphQLContext(typesense_ds=ts, postgres_ds=pg) + result = await test_schema.execute(FLESCH_PTBR_QUERY, variable_values={"id": "a"}, context_value=ctx) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["article"]["features"] == { + "readabilityFlesch": 12.5, + "readabilityFleschPtbr": 48.25, + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize("valor", [None, True, "48.2", [1]]) +async def test_readability_flesch_ptbr_ausente_ou_invalido_vira_null(valor): + ts = _ts_with_article("a") + features = {"word_count": 10} + if valor is not None: + features["readability_flesch_ptbr"] = valor + pg = _pg_with_features({"a": features}) + ctx = GraphQLContext(typesense_ds=ts, postgres_ds=pg) + result = await test_schema.execute(FLESCH_PTBR_QUERY, variable_values={"id": "a"}, context_value=ctx) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["article"]["features"]["readabilityFleschPtbr"] is None diff --git a/tests/resolvers/test_entities.py b/tests/resolvers/test_entities.py index d71576d..85b71a4 100644 --- a/tests/resolvers/test_entities.py +++ b/tests/resolvers/test_entities.py @@ -49,6 +49,45 @@ async def test_retorna_pontos_de_cobertura(self): assert pts[0]["articleCount"] == 12 mock_pg.entity_coverage.assert_awaited_once_with("Q4294522", "month", None, None) + @pytest.mark.asyncio + async def test_unique_content_count(self): + mock_pg = AsyncMock() + mock_pg.entity_coverage = AsyncMock(return_value=[ + { + "period": "2026-10-01 00:00:00+00", + "agency_key": "mec", + "agency_name": "MEC", + "article_count": 3, + "unique_content_count": 2, + "total_mentions": 5, + "avg_sentiment_score": None, + }, + # Só republicações: nenhum conteúdo creditado a esta agência. + { + "period": "2026-10-01 00:00:00+00", + "agency_key": "ebc", + "agency_name": "EBC", + "article_count": 2, + "unique_content_count": 0, + "total_mentions": 2, + "avg_sentiment_score": None, + }, + ]) + query = """ + query { + entityCoverage(entityId: "Q1", dateFrom: "2026-10-01", dateTo: "2026-10-08", granularity: DAY) { + agencyKey articleCount uniqueContentCount + } + } + """ + result = await test_schema.execute(query, context_value=_make_ctx(postgres_ds=mock_pg)) + assert result.errors is None + assert result.data["entityCoverage"] == [ + {"agencyKey": "mec", "articleCount": 3, "uniqueContentCount": 2}, + {"agencyKey": "ebc", "articleCount": 2, "uniqueContentCount": 0}, + ] + mock_pg.entity_coverage.assert_awaited_once_with("Q1", "day", "2026-10-01", "2026-10-08") + @pytest.mark.asyncio async def test_entity_id_vazio_retorna_lista_vazia(self): mock_pg = AsyncMock() @@ -99,3 +138,19 @@ async def test_query_vazia_retorna_lista_vazia(self): result = await test_schema.execute(query, context_value=_make_ctx(postgres_ds=mock_pg)) assert result.errors is None assert result.data["entitySearch"] == [] + + +class TestEntityCoverageSDL: + def test_descricao_documenta_dias_utc_e_date_to_exclusivo(self): + field = next( + f for f in test_schema.get_type_by_name("Query").fields if f.python_name == "entity_coverage" + ) + assert "dias UTC" in field.description + assert "dateFrom inclusivo" in field.description + assert "dateTo exclusivo" in field.description + + + def test_unique_content_count_no_sdl(self): + sdl = test_schema.as_str() + block = sdl.split("type EntityCoveragePoint {", 1)[1].split("}", 1)[0] + assert "uniqueContentCount: Int!" in block diff --git a/tests/resolvers/test_public_content.py b/tests/resolvers/test_public_content.py index 268201a..2544860 100644 --- a/tests/resolvers/test_public_content.py +++ b/tests/resolvers/test_public_content.py @@ -14,6 +14,7 @@ from graphql_api.context import GraphQLContext, User from graphql_api.datasources.firestore import ClippingData, ReleaseData, SubscriptionData from graphql_api.datasources.postgres import ( + EntityGraphStatsRecord, EntityNetworkEdgeRecord, EntityNetworkNodeRecord, EntityNetworkRecord, @@ -623,7 +624,37 @@ def test_related_entity_type_and_query_signature(self): assert "wikidataId: String" in block assert "weight: Int!" in block assert "kind: String!" in block - assert "relatedEntities(id: String!, limit: Int! = 12): [RelatedEntity!]!" in sdl + assert ( + "relatedEntities(id: String!, limit: Int! = 12, " + "orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 1): [RelatedEntity!]!" + in sdl + ) + + def test_related_entity_stats_fields_and_order_enum(self): + # GQL-1: estatísticas nullable + ordenação por peso, conteúdo único ou lift. + sdl = test_schema.as_str() + block = sdl.split("type RelatedEntity {", 1)[1].split("}", 1)[0] + for field in ( + "articleCount: Int", + "uniqueContentCount: Int", + "uniqueContentWeight: Int", + "lift: Float", + ): + assert field in block + assert field + "!" not in block + enum_block = sdl.split("enum RelatedEntityOrder {", 1)[1].split("}", 1)[0] + assert enum_block.split() == ["WEIGHT", "UNIQUE_CONTENT", "LIFT"] + + def test_entity_node_stats_and_graph_stats(self): + sdl = test_schema.as_str() + block = sdl.split("type EntityNode {", 1)[1].split("}", 1)[0] + assert "articleCount: Int" in block + assert "uniqueContentCount: Int" in block + gblock = sdl.split("type EntityGraphStats {", 1)[1].split("}", 1)[0] + assert "totalArticles: Int!" in gblock + assert "totalUniqueContent: Int!" in gblock + assert "computedAt: DateTime" in gblock + assert "entityGraphStats: EntityGraphStats\n" in sdl def test_entity_network_types_and_query_signature(self): sdl = test_schema.as_str() @@ -647,10 +678,23 @@ def test_entity_network_types_and_query_signature(self): assert "edges: [EntityNetworkEdge!]!" in gblock assert ( - "entityNetwork(id: String!, depth: Int! = 1, limit: Int! = 50): EntityNetwork!" + "entityNetwork(id: String!, depth: Int! = 1, limit: Int! = 50, " + "egoCentered: Boolean! = false, maxNodes: Int! = 30, " + "includeNeighborEdges: Boolean! = true): EntityNetwork!" in sdl ) + def test_entity_network_stats_fields(self): + # GQL-1: estatísticas do grafo (entity_stats / entity_edges), nullable. + sdl = test_schema.as_str() + nblock = sdl.split("type EntityNetworkNode {", 1)[1].split("}", 1)[0] + assert "articleCount: Int" in nblock + assert "articleCount: Int!" not in nblock + assert "uniqueContentCount: Int" in nblock + eblock = sdl.split("type EntityNetworkEdge {", 1)[1].split("}", 1)[0] + assert "uniqueContentWeight: Int" in eblock + assert "uniqueContentWeight: Int!" not in eblock + # --------------------------------------------------------------------------- # relatedEntities (Fase 6c — 1-hop co-menção) @@ -717,7 +761,9 @@ async def test_maps_records_preserving_order(self): "kind": "co_mention", }, ] - pg.get_related_entities.assert_awaited_once_with("Q123", limit=12) + pg.get_related_entities.assert_awaited_once_with( + "Q123", limit=12, order_by="weight", min_weight=1 + ) @pytest.mark.asyncio async def test_default_limit(self): @@ -726,7 +772,67 @@ async def test_default_limit(self): query = "{ relatedEntities(id: \"Q1\") { canonicalId } }" result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) assert result.errors is None, f"Errors: {result.errors}" - pg.get_related_entities.assert_awaited_once_with("Q1", limit=12) + # Default retrocompatível (portal não passa minWeight): weight >= 1. + pg.get_related_entities.assert_awaited_once_with( + "Q1", limit=12, order_by="weight", min_weight=1 + ) + + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("order_by", "valor"), + [("WEIGHT", "weight"), ("UNIQUE_CONTENT", "unique_content"), ("LIFT", "lift")], + ) + async def test_repassa_order_by_e_min_weight(self, order_by, valor): + pg = MagicMock() + pg.get_related_entities = AsyncMock(return_value=[]) + query = ( + f'{{ relatedEntities(id: "Q1", limit: 5, orderBy: {order_by}, minWeight: 3) ' + "{ canonicalId } }" + ) + result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + pg.get_related_entities.assert_awaited_once_with( + "Q1", limit=5, order_by=valor, min_weight=3 + ) + + @pytest.mark.asyncio + async def test_mapeia_stats_e_lift_nulos(self): + pg = MagicMock() + pg.get_related_entities = AsyncMock( + return_value=[ + RelatedEntityRecord( + entity_id="Q2", + weight=40, + article_count=900, + unique_content_count=700, + unique_content_weight=31, + lift=2.5, + ), + RelatedEntityRecord(entity_id="Q3", weight=3), + ] + ) + query = ( + '{ relatedEntities(id: "Q1", orderBy: LIFT) ' + "{ canonicalId articleCount uniqueContentCount uniqueContentWeight lift } }" + ) + result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["relatedEntities"] == [ + { + "canonicalId": "Q2", + "articleCount": 900, + "uniqueContentCount": 700, + "uniqueContentWeight": 31, + "lift": 2.5, + }, + { + "canonicalId": "Q3", + "articleCount": None, + "uniqueContentCount": None, + "uniqueContentWeight": None, + "lift": None, + }, + ] @pytest.mark.asyncio async def test_empty_without_postgres(self): @@ -803,7 +909,14 @@ async def test_maps_nodes_and_edges(self): assert data["edges"] == [ {"src": "Q1", "dst": "Q2", "weight": 9, "kind": "co_mention"} ] - pg.get_entity_network.assert_awaited_once_with("Q1", depth=2, limit=50) + pg.get_entity_network.assert_awaited_once_with( + "Q1", + depth=2, + limit=50, + ego_centered=False, + max_nodes=30, + include_neighbor_edges=True, + ) @pytest.mark.asyncio async def test_defaults_depth_and_limit(self): @@ -814,7 +927,72 @@ async def test_defaults_depth_and_limit(self): query = "{ entityNetwork(id: \"Q1\") { nodes { entityId } edges { src } } }" result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) assert result.errors is None, f"Errors: {result.errors}" - pg.get_entity_network.assert_awaited_once_with("Q1", depth=1, limit=50) + # Default = modo legado (o portal não passa os args novos). + pg.get_entity_network.assert_awaited_once_with( + "Q1", + depth=1, + limit=50, + ego_centered=False, + max_nodes=30, + include_neighbor_edges=True, + ) + + @pytest.mark.asyncio + async def test_ego_centered_repassa_args(self): + pg = MagicMock() + pg.get_entity_network = AsyncMock( + return_value=EntityNetworkRecord(nodes=[], edges=[]) + ) + query = ( + '{ entityNetwork(id: "Q1", egoCentered: true, maxNodes: 10, ' + "includeNeighborEdges: false, limit: 80) { nodes { entityId } } }" + ) + result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + pg.get_entity_network.assert_awaited_once_with( + "Q1", + depth=1, + limit=80, + ego_centered=True, + max_nodes=10, + include_neighbor_edges=False, + ) + + @pytest.mark.asyncio + async def test_mapeia_stats_dos_nos_e_arestas(self): + pg = MagicMock() + pg.get_entity_network = AsyncMock( + return_value=EntityNetworkRecord( + nodes=[ + EntityNetworkNodeRecord( + entity_id="Q1", article_count=120, unique_content_count=95 + ), + EntityNetworkNodeRecord(entity_id="Q2"), + ], + edges=[ + EntityNetworkEdgeRecord( + src="Q1", dst="Q2", weight=9, unique_content_weight=7 + ), + EntityNetworkEdgeRecord(src="Q2", dst="Q1", weight=2), + ], + ) + ) + query = ( + '{ entityNetwork(id: "Q1", egoCentered: true) { ' + "nodes { entityId articleCount uniqueContentCount } " + "edges { src uniqueContentWeight } } }" + ) + result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + data = result.data["entityNetwork"] + assert data["nodes"] == [ + {"entityId": "Q1", "articleCount": 120, "uniqueContentCount": 95}, + {"entityId": "Q2", "articleCount": None, "uniqueContentCount": None}, + ] + assert data["edges"] == [ + {"src": "Q1", "uniqueContentWeight": 7}, + {"src": "Q2", "uniqueContentWeight": None}, + ] @pytest.mark.asyncio async def test_empty_without_postgres(self): @@ -1025,3 +1203,71 @@ async def test_null_without_postgres(self): ) assert result.errors is None, f"Errors: {result.errors}" assert result.data["entity"] is None + + +# --------------------------------------------------------------------------- +# entity(id) com estatísticas + entityGraphStats (GQL-1) +# --------------------------------------------------------------------------- +class TestEntityStats: + @pytest.mark.asyncio + async def test_entity_expoe_article_count_e_unique_content_count(self): + pg = MagicMock() + pg.get_entity = AsyncMock( + return_value=EntityRegistryRecord( + entity_id="Q1", article_count=1200, unique_content_count=950 + ) + ) + query = '{ entity(id: "Q1") { entityId articleCount uniqueContentCount } }' + result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["entity"] == { + "entityId": "Q1", + "articleCount": 1200, + "uniqueContentCount": 950, + } + + @pytest.mark.asyncio + async def test_entity_sem_stats_nulos(self): + pg = MagicMock() + pg.get_entity = AsyncMock(return_value=EntityRegistryRecord(entity_id="Q1")) + query = '{ entity(id: "Q1") { articleCount uniqueContentCount } }' + result = await test_schema.execute(query, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["entity"] == {"articleCount": None, "uniqueContentCount": None} + + +GRAPH_STATS_QUERY = "{ entityGraphStats { totalArticles totalUniqueContent computedAt } }" + + +class TestEntityGraphStats: + @pytest.mark.asyncio + async def test_retorna_meta(self): + pg = MagicMock() + pg.get_entity_graph_stats = AsyncMock( + return_value=EntityGraphStatsRecord( + total_articles=333000, + total_unique_content=250000, + computed_at=datetime(2026, 10, 20, 3, 0, tzinfo=timezone.utc), + ) + ) + result = await test_schema.execute(GRAPH_STATS_QUERY, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["entityGraphStats"] == { + "totalArticles": 333000, + "totalUniqueContent": 250000, + "computedAt": "2026-10-20T03:00:00+00:00", + } + + @pytest.mark.asyncio + async def test_null_sem_meta(self): + pg = MagicMock() + pg.get_entity_graph_stats = AsyncMock(return_value=None) + result = await test_schema.execute(GRAPH_STATS_QUERY, context_value=_ctx(postgres_ds=pg)) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["entityGraphStats"] is None + + @pytest.mark.asyncio + async def test_null_sem_postgres(self): + result = await test_schema.execute(GRAPH_STATS_QUERY, context_value=_ctx()) + assert result.errors is None, f"Errors: {result.errors}" + assert result.data["entityGraphStats"] is None diff --git a/tests/test_schema.py b/tests/test_schema.py index 55ed292..01b876f 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -76,6 +76,19 @@ def test_article_exposes_features_field(): assert "wordCount: Int" in feats_block # Fase 5: contentAnnotations (lente semântica). assert "contentAnnotations: [ContentAnnotation!]!" in feats_block + # GQL-1: Flesch pt-BR (Martins/1996) ao lado do inglês. + assert "readabilityFlesch: Float" in feats_block + assert "readabilityFleschPtbr: Float" in feats_block + + +def test_agency_period_metrics_expoe_flesch_ptbr(): + from graphql_api.schema import schema + + sdl = schema.as_str() + block = sdl.split("type AgencyPeriodMetrics {", 1)[1].split("}", 1)[0] + assert "avgReadabilityFlesch: Float" in block + assert "avgReadabilityFleschPtbr: Float" in block + assert "readabilityFleschPtbrCount: Int" in block def test_content_annotation_type_exposed():