From 6de08692f55257f1e92c17e6c2a2d919f34a201b Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:49:26 -0300 Subject: [PATCH 01/20] =?UTF-8?q?test:=20entityNetwork=20ego-centrado=20e?= =?UTF-8?q?=20estat=C3=ADsticas=20do=20grafo=20nos=20n=C3=B3s/arestas=20(r?= =?UTF-8?q?ed)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. O roteiro de testes do Gobus mostrou que a rede legada (CTE recursiva, arestas cortadas por peso global) não fica centrada na entidade: com limit=50 as arestas mais pesadas entre vizinhos expulsam as do próprio foco. Cobre: - modo legado (default, usado pelo portal) com as mesmas queries recursivas e os mesmos parâmetros posicionais; só ganha LEFT JOIN em entity_stats e e.unique_content_count; - modo ego (egoCentered): foco + top maxNodes vizinhos por peso (>= 2), todas as arestas do foco preservadas, arestas entre vizinhos cortadas em limit; clamps de maxNodes (1–100) e limit (1–500); depth ignorado; - sem nós ou arestas órfãos mesmo se o grafo mudar entre as queries; - articleCount/uniqueContentCount nos nós e uniqueContentWeight nas arestas, nulos quando faltam estatísticas; - assinatura do SDL com os args novos. --- .../datasources/test_postgres_entity_graph.py | 187 ++++++++++++++++++ tests/resolvers/test_public_content.py | 91 ++++++++- 2 files changed, 275 insertions(+), 3 deletions(-) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index a4d342c..e6d7bad 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -10,6 +10,10 @@ import pytest from graphql_api.datasources.postgres import ( + _ENTITY_NETWORK_EDGES_SQL, + _ENTITY_NETWORK_EGO_EDGES_SQL, + _ENTITY_NETWORK_EGO_NODES_SQL, + _ENTITY_NETWORK_NODES_SQL, EntityNetworkEdgeRecord, EntityNetworkNodeRecord, PostgresDatasource, @@ -17,6 +21,10 @@ ) +def _flat(sql: str) -> str: + return " ".join(sql.split()) + + def _make_mock_pool(fetch_results=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 @@ -145,3 +153,182 @@ 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_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() diff --git a/tests/resolvers/test_public_content.py b/tests/resolvers/test_public_content.py index 268201a..3f8dfe1 100644 --- a/tests/resolvers/test_public_content.py +++ b/tests/resolvers/test_public_content.py @@ -647,10 +647,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) @@ -803,7 +816,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 +834,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): From 946accc9af7c4def2321c1ca0375edd10ff41b24 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:52:01 -0300 Subject: [PATCH 02/20] feature: entityNetwork ego-centrado com articleCount/uniqueContentCount/uniqueContentWeight (green) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. Args novos (aditivos; o default mantém o modo legado do portal): - egoCentered (false), maxNodes (30, clamp 1–100), includeNeighborEdges (true). No modo ego, os nós são a entidade + seus maxNodes vizinhos mais fortes (weight >= 2, desempate por id) e TODAS as arestas da entidade para eles entram; só as arestas entre vizinhos são cortadas em limit (clamp 1–500). depth é ignorado. - _ENTITY_NETWORK_EGO_NODES_SQL/_EDGES_SQL compartilham o mesmo CTE neighbors (mesma ordem + LIMIT ⇒ mesmo conjunto); o datasource ainda poda nós e arestas órfãos caso a DAG recalcule entity_edges entre as duas queries. Foco primeiro na lista de nós; ids sempre parametrizados. - Legado: mesmas queries recursivas e mesmos parâmetros; só ganha LEFT JOIN em entity_stats (PK, não multiplica linhas) e a coluna e.unique_content_count. Conferido num Postgres local descartável: nós/arestas idênticos aos do SQL anterior para 5 ids × depth 0–2 × limit 5/50/500. - EntityNetworkNode ganha articleCount/uniqueContentCount e EntityNetworkEdge ganha uniqueContentWeight, todos nullable. Requer a migração 032 do data-platform (entity_stats e entity_edges.unique_content_count) aplicada antes do deploy. SDL de referência regenerado (make docs-schema). --- docs/reference/schema.graphql | 19 +- docs/reference/schema.md | 19 +- src/graphql_api/datasources/postgres.py | 181 ++++++++++++++++-- .../schema/resolvers/public_content.py | 47 ++++- 4 files changed, 245 insertions(+), 21 deletions(-) diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index 21850b8..a3d039a 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -320,6 +320,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 +332,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 { @@ -718,9 +733,9 @@ type Query { relatedEntities(id: String!, limit: Int! = 12): [RelatedEntity!]! """ - 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. diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 0fd27f5..43661ed 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -331,6 +331,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 +343,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 { @@ -729,9 +744,9 @@ type Query { relatedEntities(id: String!, limit: Int! = 12): [RelatedEntity!]! """ - 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. diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 597d8ed..9cad6fe 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -91,22 +91,31 @@ class RelatedEntityRecord: @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 @@ -193,6 +202,12 @@ class TypesenseDocRecord(NewsRecord): LIMIT $2 """ +# 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 +231,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 +255,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 +265,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, @@ -746,12 +834,18 @@ def _row_to_related_entity(row: dict) -> RelatedEntityRecord: ) +def _as_optional_int(value: Any) -> Optional[int]: + return None if value is None else int(value) + + def _row_to_network_node(row: dict) -> EntityNetworkNodeRecord: return EntityNetworkNodeRecord( entity_id=row["entity_id"], 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 +855,28 @@ 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.""" + node_ids = {n.entity_id for n in nodes} + edges = [e for e in edges if e.src in node_ids and e.dst in node_ids] + 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], ) @@ -946,18 +1062,34 @@ async def get_related_entities( return [_row_to_related_entity(dict(r)) for r in rows] 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 +1104,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: diff --git a/src/graphql_api/schema/resolvers/public_content.py b/src/graphql_api/schema/resolvers/public_content.py index bb89a98..1bc96ed 100644 --- a/src/graphql_api/schema/resolvers/public_content.py +++ b/src/graphql_api/schema/resolvers/public_content.py @@ -108,6 +108,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 +129,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 @@ -318,11 +336,15 @@ async def related_entities( @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 +353,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 +376,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 +387,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 ], From 293c934ea758733e0cba6dcaa003948864438857 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:53:13 -0300 Subject: [PATCH 03/20] test: relatedEntities com orderBy/minWeight/lift, stats no entity(id) e entityGraphStats (red) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. Entidades genéricas ("Brasil", "Governo Federal") dominam os vizinhos por peso bruto; o lift (weight·N / (cnt_ego·cnt_vizinho)) destaca associações específicas, e uniqueContentWeight desconta republicações. Cobre: - datasource: $3 = ordenação (weight|unique_content|lift, whitelist; inválida levanta sem consultar), $4 = peso mínimo (default 2, clamp >= 1), limit continua em $2; SQL com LEFT JOIN em entity_stats (das duas pontas) e entity_graph_meta, NULLIF nos termos do lift e ORDER BY com NULLS LAST e desempate weight desc, other_id; - mapeamento de articleCount/uniqueContentCount/uniqueContentWeight/lift (Decimal → float) e nulos quando faltam estatísticas; - entity(id) com articleCount/uniqueContentCount via LEFT JOIN; - Query.entityGraphStats (entity_graph_meta), null sem linha ou sem Postgres; - SDL: enum RelatedEntityOrder, args novos e campos nullable. --- .../datasources/test_postgres_entity_graph.py | 170 +++++++++++++++++- tests/resolvers/test_public_content.py | 166 ++++++++++++++++- 2 files changed, 331 insertions(+), 5 deletions(-) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index e6d7bad..1f92f24 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -5,6 +5,8 @@ vai SEMPRE parametrizado ($1), o clamp de depth e o mapeamento das linhas. """ +from datetime import datetime, timezone +from decimal import Decimal from unittest.mock import AsyncMock, MagicMock import pytest @@ -14,6 +16,9 @@ _ENTITY_NETWORK_EGO_EDGES_SQL, _ENTITY_NETWORK_EGO_NODES_SQL, _ENTITY_NETWORK_NODES_SQL, + _ENTITY_REGISTRY_SQL, + _RELATED_ENTITIES_SQL, + EntityGraphStatsRecord, EntityNetworkEdgeRecord, EntityNetworkNodeRecord, PostgresDatasource, @@ -25,16 +30,18 @@ def _flat(sql: str) -> str: return " ".join(sql.split()) -def _make_mock_pool(fetch_results=None): +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) @@ -88,6 +95,101 @@ 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_2(self): + 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", 2) + + @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 @@ -332,3 +434,67 @@ async def test_empty_entity_id_returns_empty_without_query(self): 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 diff --git a/tests/resolvers/test_public_content.py b/tests/resolvers/test_public_content.py index 3f8dfe1..cc76401 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! = 2): [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() @@ -730,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=2 + ) @pytest.mark.asyncio async def test_default_limit(self): @@ -739,7 +772,66 @@ 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) + pg.get_related_entities.assert_awaited_once_with( + "Q1", limit=12, order_by="weight", min_weight=2 + ) + + @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): @@ -1110,3 +1202,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 From 0740f16ce5907c8d88807365da5bbc9e93ad5046 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:55:08 -0300 Subject: [PATCH 04/20] feature: relatedEntities com orderBy/minWeight/lift, stats no entity(id) e entityGraphStats (green) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. - relatedEntities ganha orderBy: RelatedEntityOrder = WEIGHT (WEIGHT | UNIQUE_CONTENT | LIFT) e minWeight: Int = 2, e os campos nullable articleCount, uniqueContentCount (do vizinho), uniqueContentWeight (da aresta) e lift. - lift = weight·N / (cnt_ego·cnt_vizinho), N = entity_graph_meta.total_articles e cnt = entity_stats.article_count; NULLIF em cada termo ⇒ NULL quando falta estatística de uma ponta, a meta ou algum termo é 0. ORDER BY por CASE no parâmetro (whitelist no datasource), NULLS LAST, desempate weight desc, other_id. - Com orderBy WEIGHT e minWeight 1 a lista é idêntica à do SQL anterior (conferido num Postgres local descartável, inclusive empates); minWeight 2 só remove as co-menções únicas. - entity(id): articleCount/uniqueContentCount via LEFT JOIN em entity_stats (o batch de entitySuggestions não muda). - Query.entityGraphStats { totalArticles totalUniqueContent computedAt }, null sem linha em entity_graph_meta. Mudança de default: relatedEntities passa a omitir vizinhos com weight 1 (minWeight 2). minWeight: 1 restaura a lista anterior. Requer a migração 032 do data-platform aplicada antes do deploy. SDL de referência regenerado. --- docs/reference/schema.graphql | 57 ++++++- docs/reference/schema.md | 57 ++++++- src/graphql_api/datasources/postgres.py | 159 +++++++++++++++--- .../schema/resolvers/public_content.py | 103 +++++++++++- 4 files changed, 342 insertions(+), 34 deletions(-) diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index a3d039a..a291bd5 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -301,6 +301,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 @@ -353,6 +362,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 { @@ -728,9 +747,14 @@ 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` (mínimo 1), 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): [RelatedEntity!]! + relatedEntities(id: String!, limit: Int! = 12, orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 2): [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. + """ + entityGraphStats: EntityGraphStats """ 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. @@ -797,6 +821,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 43661ed..626e5eb 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -312,6 +312,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 @@ -364,6 +373,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 { @@ -739,9 +758,14 @@ 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` (mínimo 1), 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): [RelatedEntity!]! + relatedEntities(id: String!, limit: Int! = 12, orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 2): [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. + """ + entityGraphStats: EntityGraphStats """ 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. @@ -808,6 +832,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 9cad6fe..fdb04d4 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,6 +91,21 @@ 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 @@ -166,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 = """ @@ -183,25 +205,70 @@ 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 @@ -810,6 +877,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"], @@ -820,6 +897,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")), ) @@ -831,13 +910,13 @@ 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")), ) -def _as_optional_int(value: Any) -> Optional[int]: - return None if value is None else int(value) - - def _row_to_network_node(row: dict) -> EntityNetworkNodeRecord: return EntityNetworkNodeRecord( entity_id=row["entity_id"], @@ -1047,20 +1126,48 @@ 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 = 2, ) -> 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). `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, diff --git a/src/graphql_api/schema/resolvers/public_content.py b/src/graphql_api/schema/resolvers/public_content.py index 1bc96ed..5bbfb06 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 @@ -299,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` (mínimo 1), 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( @@ -315,12 +382,16 @@ async def related_entities( info: Info, id: str, limit: int = 12, + order_by: RelatedEntityOrder = RelatedEntityOrder.WEIGHT, + min_weight: int = 2, ) -> 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, @@ -329,10 +400,34 @@ 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 " From 5d91ef97cd229a4c5fea47191e9b72858903cad5 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:55:37 -0300 Subject: [PATCH 05/20] test: entityCoverage com dias UTC, dateFrom inclusivo e dateTo exclusivo (red) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. O filtro comparava `published_at <= $4::timestamptz` com uma data: meia-noite do dateTo no fuso da sessão, ou seja, exclusivo na prática exceto pelos artigos publicados exatamente às 00:00:00, e dependente do TimeZone da conexão. O gobus-mcp já manda dateTo = último dia + 1. Cobre: datas repassadas como date; limites `>= ($3::date)::timestamp AT TIME ZONE 'UTC'` e `< ($4::date)::timestamp AT TIME ZONE 'UTC'`; `period` com o mesmo texto de antes ("AAAA-MM-DD 00:00:00+00") calculado em UTC fixo; e a descrição do campo documentando a convenção. --- .../datasources/test_postgres_entity_graph.py | 51 ++++++++++++++++++- tests/resolvers/test_entities.py | 10 ++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index 1f92f24..49f67d4 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -5,13 +5,14 @@ vai SEMPRE parametrizado ($1), o clamp de depth e o mapeamento das linhas. """ -from datetime import datetime, timezone +from datetime import date, datetime, timezone from decimal import Decimal from unittest.mock import AsyncMock, MagicMock import pytest from graphql_api.datasources.postgres import ( + _ENTITY_COVERAGE_SQL, _ENTITY_NETWORK_EDGES_SQL, _ENTITY_NETWORK_EGO_EDGES_SQL, _ENTITY_NETWORK_EGO_NODES_SQL, @@ -498,3 +499,51 @@ async def test_none_sem_linha(self): 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 diff --git a/tests/resolvers/test_entities.py b/tests/resolvers/test_entities.py index d71576d..1105d00 100644 --- a/tests/resolvers/test_entities.py +++ b/tests/resolvers/test_entities.py @@ -99,3 +99,13 @@ 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 From 5c4463b484a656e0bb99e5e5169e41c3cedc43eb Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:56:53 -0300 Subject: [PATCH 06/20] fix: entityCoverage com dias UTC, dateFrom inclusivo e dateTo exclusivo (green) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. - Limites `ne.published_at >= ($3::date)::timestamp AT TIME ZONE 'UTC'` e `< ($4::date)::timestamp AT TIME ZONE 'UTC'`: dateTo estritamente exclusivo. Antes, `<= $4::timestamptz` incluía os artigos publicados exatamente às 00:00:00 do dateTo e os limites dependiam do fuso: o asyncpg converte o `date` para timestamptz pelo fuso do PROCESSO (Cloud Run = UTC; num `make dev` em BRT os limites viravam 03:00 UTC). - `period` truncado em UTC fixo e formatado com to_char no mesmo texto que o `timestamptz::text` de uma sessão UTC dava ("2026-08-27 00:00:00+00"), sem depender do TimeZone da sessão. - Descrição do campo documenta a convenção (para incluir o dia D, dateTo = D + 1). Conferido num Postgres local descartável com o processo em UTC (como no Cloud Run): period, articleCount, totalMentions e avgSentimentScore idênticos aos do SQL anterior para day/week/month; a única diferença é o artigo das 00:00:00 do dateTo, que sai. O resultado novo é o mesmo com sessão ou processo em America/Sao_Paulo. Consumidores: o gobus-mcp já manda dateTo exclusivo (utc_day_bounds) e o get_entity_profile repassa a data do usuário (já era exclusiva na prática). O portal não usa entityCoverage. --- docs/reference/schema.graphql | 4 +++- docs/reference/schema.md | 4 +++- src/graphql_api/datasources/postgres.py | 13 +++++++++---- src/graphql_api/schema/resolvers/entities.py | 9 ++++++++- 4 files changed, 23 insertions(+), 7 deletions(-) diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index a291bd5..8cfc37b 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -776,7 +776,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""" diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 626e5eb..c29d443 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -787,7 +787,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""" diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index fdb04d4..71886a8 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -594,10 +594,14 @@ class TypesenseDocRecord(NewsRecord): # 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. # Score de sentimento aninhado com fallback plano (ver `_AGENCY_ANALYTICS_SQL`). _ENTITY_COVERAGE_SQL = """ SELECT - DATE_TRUNC($1, ne.published_at)::text AS period, + to_char(DATE_TRUNC($1, ne.published_at AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS"+00"') AS period, n.agency_key, n.agency_name, COUNT(DISTINCT ne.unique_id) AS article_count, @@ -607,8 +611,8 @@ class TypesenseDocRecord(NewsRecord): 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) + 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') GROUP BY period, n.agency_key, n.agency_name ORDER BY period """ @@ -1369,7 +1373,8 @@ 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`. diff --git a/src/graphql_api/schema/resolvers/entities.py b/src/graphql_api/schema/resolvers/entities.py index bea8f6b..2ffe935 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, From a1507b07d3762a915286cba804dcdbb2506ae4bd Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:57:13 -0300 Subject: [PATCH 07/20] =?UTF-8?q?test:=20entityCoverage.uniqueContentCount?= =?UTF-8?q?=20credita=20cada=20conte=C3=BAdo=20=C3=A0=20primeira=20ag?= =?UTF-8?q?=C3=AAncia=20(red)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. Uma mesma nota republicada por N agências conta N vezes em articleCount (o roteiro do Gobus achou séries infladas por duplicatas). uniqueContentCount credita cada conteúdo, COALESCE(content_hash, unique_id), só à primeira agência que o publicou no intervalo (ROW_NUMBER por published_at, unique_id), então o campo pode ser somado entre agências e períodos. Cobre o SQL (janela + COUNT DISTINCT FILTER, agregados existentes preservados), o mapeamento no resolver e o campo não nulo no SDL. --- .../datasources/test_postgres_entity_graph.py | 18 ++++++++ tests/resolvers/test_entities.py | 45 +++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index 49f67d4..f5ea48a 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -547,3 +547,21 @@ def test_sql_period_em_utc_com_formato_inalterado(self): "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 + assert "COUNT(DISTINCT m.unique_id) FILTER (WHERE m.is_first) AS unique_content_count" in sql + + def test_sql_preserva_agregados_existentes(self): + sql = _flat(_ENTITY_COVERAGE_SQL) + assert "COUNT(DISTINCT m.unique_id) AS article_count" in sql + assert "SUM(m.count) AS total_mentions" in sql + assert "GROUP BY period, m.agency_key, m.agency_name" in sql diff --git a/tests/resolvers/test_entities.py b/tests/resolvers/test_entities.py index 1105d00..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() @@ -109,3 +148,9 @@ def test_descricao_documenta_dias_utc_e_date_to_exclusivo(self): 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 From 85cebd3ee3e78cbb8deaecfb629760710c6d6624 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:58:17 -0300 Subject: [PATCH 08/20] =?UTF-8?q?feature:=20entityCoverage.uniqueContentCo?= =?UTF-8?q?unt=20credita=20cada=20conte=C3=BAdo=20=C3=A0=20primeira=20ag?= =?UTF-8?q?=C3=AAncia=20(green)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. - CTE `mentions` com ROW_NUMBER() OVER (PARTITION BY COALESCE(n.content_hash, ne.unique_id) ORDER BY n.published_at, ne.unique_id) = 1 AS is_first; o agregado ganha COUNT(DISTINCT unique_id) FILTER (WHERE is_first) por (period, agência). A janela roda sobre as menções já filtradas pelo intervalo: o crédito vai para a primeira agência que publicou o conteúdo DENTRO do intervalo consultado, o que mantém o campo somável (a soma em qualquer granularidade = conteúdos distintos do intervalo). - period passa a ser calculado no CTE (mesmo texto); article_count, total_mentions e avg_sentiment_score não mudam (mesmas linhas de news_entities × news × news_features). - EntityCoveragePoint.uniqueContentCount: Int! (default 0). Conferido num Postgres local descartável: republicações (mesmo content_hash) em três agências creditadas só à primeira; soma por dia e por mês igual ao nº de conteúdos distintos; demais colunas idênticas ao SQL anterior. Não depende da migração 032 (content_hash existe desde a 009). SDL de referência regenerado. --- docs/reference/schema.graphql | 5 +++ docs/reference/schema.md | 5 +++ src/graphql_api/datasources/postgres.py | 45 ++++++++++++++------ src/graphql_api/schema/resolvers/entities.py | 1 + src/graphql_api/schema/types/entities.py | 8 ++++ 5 files changed, 51 insertions(+), 13 deletions(-) diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index 8cfc37b..3220c90 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -292,6 +292,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 { diff --git a/docs/reference/schema.md b/docs/reference/schema.md index c29d443..bbb04a1 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -303,6 +303,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 { diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 71886a8..0e70eef 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -598,22 +598,40 @@ class TypesenseDocRecord(NewsRecord): # 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, COALESCE(content_hash, +# unique_id), 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. # Score de sentimento aninhado com fallback plano (ver `_AGENCY_ANALYTICS_SQL`). _ENTITY_COVERAGE_SQL = """ +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.unique_id, + ne.count, + n.agency_key, + n.agency_name, + ROW_NUMBER() OVER ( + PARTITION BY COALESCE(n.content_hash, ne.unique_id) + 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 + 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 - to_char(DATE_TRUNC($1, ne.published_at AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS"+00"') AS period, - n.agency_key, - n.agency_name, - COUNT(DISTINCT ne.unique_id) AS article_count, - SUM(ne.count) AS total_mentions, + m.period, + m.agency_key, + m.agency_name, + COUNT(DISTINCT m.unique_id) AS article_count, + COUNT(DISTINCT m.unique_id) FILTER (WHERE m.is_first) AS unique_content_count, + SUM(m.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::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') -GROUP BY period, n.agency_key, n.agency_name +FROM mentions m +LEFT JOIN news_features nf ON m.unique_id = nf.unique_id +GROUP BY period, m.agency_key, m.agency_name ORDER BY period """ @@ -1377,7 +1395,8 @@ async def entity_coverage( 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/entities.py b/src/graphql_api/schema/resolvers/entities.py index 2ffe935..5544b76 100644 --- a/src/graphql_api/schema/resolvers/entities.py +++ b/src/graphql_api/schema/resolvers/entities.py @@ -76,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/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 From 81ee8c1f987b503ccd2e150c72665f36b0b1cdb4 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:58:45 -0300 Subject: [PATCH 09/20] test: trendingThemes.topArticles com url e agencyKey (red) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. O Gobus cita os artigos em alta sem link porque ArticleSummary não tem url (o Typesense tem). E agencyName, apesar do nome, carrega a key da agência (campo `agency` do Typesense). Cobre: include_fields pede url; url e agencyKey mapeados (null quando ausentes); agencyName mantido por compatibilidade, com descrição apontando para agencyKey. --- tests/resolvers/test_analytics.py | 72 +++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/tests/resolvers/test_analytics.py b/tests/resolvers/test_analytics.py index f232dc0..b22fe37 100644 --- a/tests/resolvers/test_analytics.py +++ b/tests/resolvers/test_analytics.py @@ -586,6 +586,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.""" From 956c6c225570e99ec9013815e51f86c6be93170a Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 19:59:01 -0300 Subject: [PATCH 10/20] feature: ArticleSummary com url e agencyKey (green) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. trendingThemes.topArticles passa a pedir `url` ao Typesense e ArticleSummary ganha url e agencyKey (nullable, aditivos). agencyName continua com o mesmo valor (a key, campo `agency` do Typesense), agora documentado no SDL; consumidores novos devem usar agencyKey. SDL de referência regenerado. --- docs/reference/schema.graphql | 10 ++++++++++ docs/reference/schema.md | 10 ++++++++++ src/graphql_api/schema/resolvers/analytics.py | 4 +++- src/graphql_api/schema/types/analytics.py | 6 +++++- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index 3220c90..43ffe15 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -149,9 +149,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 { diff --git a/docs/reference/schema.md b/docs/reference/schema.md index bbb04a1..dc8c297 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -160,9 +160,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 { diff --git a/src/graphql_api/schema/resolvers/analytics.py b/src/graphql_api/schema/resolvers/analytics.py index 6645244..6da402f 100644 --- a/src/graphql_api/schema/resolvers/analytics.py +++ b/src/graphql_api/schema/resolvers/analytics.py @@ -261,7 +261,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 +276,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/types/analytics.py b/src/graphql_api/schema/types/analytics.py index f12b931..3ff70e6 100644 --- a/src/graphql_api/schema/types/analytics.py +++ b/src/graphql_api/schema/types/analytics.py @@ -74,9 +74,13 @@ class AgencyPeriodMetrics: 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 From c3b7ff8bbb9be9b92a9c191d404391ca4b1b8287 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:00:07 -0300 Subject: [PATCH 11/20] test: Flesch pt-BR no ArticleFeatures e no agencyAnalytics (red) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. O readability_flesch gravado hoje usa a fórmula inglesa (escala distorcida para português: notas negativas em agências normais). O data-platform (DP-1) passa a gravar features.readability_flesch_ptbr (Martins et al., 1996). Cobre: - ArticleFeatures.readabilityFleschPtbr (null quando ausente ou não numérico; bool/str rejeitados como nos demais escalares); - agencyAnalytics MONTH/WEEK e DAY: AVG e COUNT de readability_flesch_ptbr, com contagem 0 nos dias preenchidos pelo generate_series; avg_readability_flesch inalterado; - AgencyPeriodMetrics.avgReadabilityFleschPtbr (Decimal → float) e readabilityFleschPtbrCount; - SDL. --- tests/datasources/test_postgres_features.py | 26 +++++++++ tests/resolvers/test_analytics.py | 60 +++++++++++++++++++++ tests/resolvers/test_article_features.py | 39 ++++++++++++++ tests/test_schema.py | 13 +++++ 4 files changed, 138 insertions(+) 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 b22fe37..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() 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/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(): From 31fc76708705bf14c398627df6613786d38f30cc Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:00:34 -0300 Subject: [PATCH 12/20] feature: Flesch pt-BR no ArticleFeatures e no agencyAnalytics (green) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GQL-1. - ArticleFeatures.readabilityFleschPtbr: Float, lido de features.readability_flesch_ptbr (gravado pelo DP-1 do data-platform). - agencyAnalytics (MONTH/WEEK e DAY): AVG e COUNT de readability_flesch_ptbr; no DAY, contagem 0 nos dias preenchidos. AgencyPeriodMetrics ganha avgReadabilityFleschPtbr (via _as_float, por causa do Decimal no graphql-core 3.3) e readabilityFleschPtbrCount, para o consumidor medir a cobertura do backfill. - readabilityFlesch/avgReadabilityFlesch seguem iguais; só ganham descrição no SDL apontando que são a fórmula inglesa. Conferido num Postgres local descartável (MONTH e DAY). Sem dependência da migração 032: a chave nova do JSONB só fica nula até o backfill. SDL de referência regenerado. --- docs/reference/schema.graphql | 23 +++++++++++++++++++ docs/reference/schema.md | 23 +++++++++++++++++++ src/graphql_api/datasources/postgres.py | 9 ++++++++ src/graphql_api/schema/resolvers/analytics.py | 6 +++++ src/graphql_api/schema/types/analytics.py | 15 +++++++++++- src/graphql_api/schema/types/features.py | 13 ++++++++++- 6 files changed, 87 insertions(+), 2 deletions(-) diff --git a/docs/reference/schema.graphql b/docs/reference/schema.graphql index 43ffe15..41959ab 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 { diff --git a/docs/reference/schema.md b/docs/reference/schema.md index dc8c297..3ca36a4 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 { diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 0e70eef..e23f093 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -484,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, @@ -494,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 @@ -531,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 @@ -552,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 diff --git a/src/graphql_api/schema/resolvers/analytics.py b/src/graphql_api/schema/resolvers/analytics.py index 6da402f..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 ] diff --git a/src/graphql_api/schema/types/analytics.py b/src/graphql_api/schema/types/analytics.py index 3ff70e6..cb66604 100644 --- a/src/graphql_api/schema/types/analytics.py +++ b/src/graphql_api/schema/types/analytics.py @@ -65,9 +65,22 @@ 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 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")), ) From 3afb25d48a8494568c6203d365a1a75d0aa448c2 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:01:08 -0300 Subject: [PATCH 13/20] =?UTF-8?q?docs:=20grafo=20de=20entidades,=20entityC?= =?UTF-8?q?overage=20com=20dateTo=20exclusivo=20e=20depend=C3=AAncia=20da?= =?UTF-8?q?=20migra=C3=A7=C3=A3o=20032?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - datasources.md: PostgresDatasource atende também entity, relatedEntities, entityNetwork e entityGraphStats; aviso de que essas queries dependem de entity_stats, entity_graph_meta e entity_edges.unique_content_count (migração 032 do data-platform) e do comportamento antes da primeira execução da DAG. - exemplos.md: aba "Entidades" (lift, rede ego-centrada, cobertura com uniqueContentCount, entityGraphStats; query validada contra o schema) e gotchas de dateTo exclusivo, rede legada × egoCentered, minWeight padrão 2 e agencyName com a key. --- docs/datasources.md | 12 +++++++++++- docs/exemplos.md | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) 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..1866435 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,13 @@ 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` omite co-menções únicas por padrão** (`minWeight: 2`); + `minWeight: 1` devolve a lista completa de antes. + - **`ArticleSummary.agencyName` carrega a key** da agência (igual a + `agencyKey`), não o nome. From 0c043683c0c55e569af9f7b0fa2161362dcf6fd6 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:08:15 -0300 Subject: [PATCH 14/20] =?UTF-8?q?test:=20ego-network=20n=C3=A3o=20duplica?= =?UTF-8?q?=20n=C3=B3=20nem=20aresta=20com=20par=20invertido=20em=20entity?= =?UTF-8?q?=5Fedges=20(red)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit entity_edges não tem CHECK (src_id < dst_id); a ordem canônica do par de co-menção é só convenção da DAG. Se o par aparecer nos dois sentidos, o modo ego devolveria o vizinho duas vezes e duas arestas para o mesmo par. A rede deve manter um nó por entidade e uma aresta por par (a de maior peso, que vem primeiro). --- .../datasources/test_postgres_entity_graph.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index f5ea48a..eb73173 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -427,6 +427,24 @@ async def test_sem_nos_ou_arestas_orfaos(self): 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([[], []]) From 2b5b59062207f824fa2f65a27815c9d3d5467b73 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:08:51 -0300 Subject: [PATCH 15/20] =?UTF-8?q?fix:=20ego-network=20deduplica=20n=C3=B3s?= =?UTF-8?q?=20por=20id=20e=20arestas=20por=20par=20n=C3=A3o-ordenado=20(gr?= =?UTF-8?q?een)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _prune_ego_network mantém o primeiro nó de cada entity_id e a primeira aresta de cada par {src, dst} (as arestas chegam por peso desc, então fica a mais forte). Protege o modo ego de um par gravado nos dois sentidos em entity_edges, já que src_id < dst_id é convenção da DAG e não CHECK no banco. Invariantes do modo ego reconferidos no Postgres local. --- src/graphql_api/datasources/postgres.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index e23f093..3105cd4 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -977,9 +977,21 @@ def _prune_ego_network( """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.""" - node_ids = {n.entity_id for n in nodes} - edges = [e for e in edges if e.src in node_ids and e.dst in node_ids] + 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): From 664ef3b0408b1f2c5a18d5cbf87cb761b691a43d Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:13:06 -0300 Subject: [PATCH 16/20] refactor: entityCoverage agrega com COUNT(*) e junta news_features antes da janela MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Num grafo sintético (300k notícias, 1,5M menções; entidade-hub com 68k menções, MONTH sem limite de datas), a versão com COUNT(DISTINCT) depois do ROW_NUMBER levava p50 ~265 ms contra ~205 ms do SQL anterior: o DISTINCT força GroupAggregate com sort (spill em disco com work_mem de 4 MB) num nó single-thread acima da janela. - news_features entra no CTE (antes da janela, ainda paralelo) e o score de sentimento sai já calculado; - COUNT(*) no lugar de COUNT(DISTINCT unique_id): news_entities tem PK (unique_id, entity_id) e os joins com news/news_features são 1:1, então há uma linha por artigo e as contagens são as mesmas. Resultado idêntico (linhas ordenadas, AVG arredondado) para MONTH/WEEK/ DAY em três entidades, e de volta a ~p50 170 ms no caso do hub (DAY com janela de 3 meses: +10 ms sobre o SQL anterior). Testes de SQL atualizados para as novas expressões. --- src/graphql_api/datasources/postgres.py | 13 ++++++++----- tests/datasources/test_postgres_entity_graph.py | 6 ++++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 3105cd4..29a45c6 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -611,21 +611,25 @@ class TypesenseDocRecord(NewsRecord): # unique_id), 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 = """ 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.unique_id, 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 COALESCE(n.content_hash, ne.unique_id) 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') @@ -634,12 +638,11 @@ class TypesenseDocRecord(NewsRecord): m.period, m.agency_key, m.agency_name, - COUNT(DISTINCT m.unique_id) AS article_count, - COUNT(DISTINCT m.unique_id) FILTER (WHERE m.is_first) AS unique_content_count, + COUNT(*) AS article_count, + COUNT(*) FILTER (WHERE m.is_first) AS unique_content_count, SUM(m.count) AS total_mentions, - AVG(COALESCE(nf.features->'sentiment'->>'score', nf.features->>'sentiment_score')::float) AS avg_sentiment_score + AVG(m.sentiment_score) AS avg_sentiment_score FROM mentions m -LEFT JOIN news_features nf ON m.unique_id = nf.unique_id GROUP BY period, m.agency_key, m.agency_name ORDER BY period """ diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index eb73173..429ae2c 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -576,10 +576,12 @@ 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 - assert "COUNT(DISTINCT m.unique_id) FILTER (WHERE m.is_first) AS unique_content_count" 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_sql_preserva_agregados_existentes(self): sql = _flat(_ENTITY_COVERAGE_SQL) - assert "COUNT(DISTINCT m.unique_id) AS article_count" in 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 From eb115f5da6544256d74e19028d9d73140224c8fb Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:17:12 -0300 Subject: [PATCH 17/20] test: chave de dedup do entityCoverage isolada numa constante (red) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O dedup exato por content_hash quase não muda as contagens na prática: republicações entre órgãos raramente são idênticas byte a byte, e uma chave de quase-duplicata está em avaliação. A expressão da chave (COALESCE(n.content_hash, ne.unique_id)) deve viver numa única constante, para ser trocada sem mudar a API (uniqueContentCount fica com o mesmo nome). --- tests/datasources/test_postgres_entity_graph.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index 429ae2c..81e7744 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -12,6 +12,7 @@ import pytest from graphql_api.datasources.postgres import ( + _CONTENT_DEDUP_KEY_SQL, _ENTITY_COVERAGE_SQL, _ENTITY_NETWORK_EDGES_SQL, _ENTITY_NETWORK_EGO_EDGES_SQL, @@ -579,6 +580,15 @@ def test_sql_credita_a_primeira_publicacao(self): # 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 From dac7a38472164ada8f411d856543bad9636fab90 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:17:40 -0300 Subject: [PATCH 18/20] refactor: chave de dedup do entityCoverage em _CONTENT_DEDUP_KEY_SQL (green) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A expressão COALESCE(n.content_hash, ne.unique_id) sai do SQL para uma constante documentada, interpolada no PARTITION BY (constante de código, não entrada do usuário). O SQL renderizado é idêntico ao anterior. O comentário registra que o hash exato quase não pega republicações entre órgãos e que entity_stats/entity_edges (DAG do grafo no data-platform) usam a mesma definição, então uma troca de chave precisa andar junto nas duas pontas. --- src/graphql_api/datasources/postgres.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 29a45c6..35fba99 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -600,6 +600,15 @@ 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). @@ -607,15 +616,15 @@ class TypesenseDocRecord(NewsRecord): # 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, COALESCE(content_hash, -# unique_id), 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. +# `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, @@ -624,7 +633,7 @@ class TypesenseDocRecord(NewsRecord): n.agency_name, COALESCE(nf.features->'sentiment'->>'score', nf.features->>'sentiment_score')::float AS sentiment_score, ROW_NUMBER() OVER ( - PARTITION BY COALESCE(n.content_hash, ne.unique_id) + PARTITION BY {_CONTENT_DEDUP_KEY_SQL} ORDER BY n.published_at, ne.unique_id ) = 1 AS is_first FROM news_entities ne From e249cc0fa9da83810386c39acb6c8ea83572be7a Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:32:00 -0300 Subject: [PATCH 19/20] =?UTF-8?q?test:=20relatedEntities=20com=20minWeight?= =?UTF-8?q?=20padr=C3=A3o=201,=20retrocompat=C3=ADvel=20com=20o=20portal?= =?UTF-8?q?=20(red)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O default 2 tirava os vizinhos de co-menção única e encolhia os chips de /entidades/[slug] no portal, que chama relatedEntities(id, limit) sem args novos. Com default 1 a lista padrão volta a ser idêntica à de antes; o gobus passa minWeight: 2 explicitamente. O limiar >= 2 do modo ego (opt-in) não muda. --- tests/datasources/test_postgres_entity_graph.py | 6 ++++-- tests/resolvers/test_public_content.py | 7 ++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/datasources/test_postgres_entity_graph.py b/tests/datasources/test_postgres_entity_graph.py index 81e7744..9bdd07d 100644 --- a/tests/datasources/test_postgres_entity_graph.py +++ b/tests/datasources/test_postgres_entity_graph.py @@ -98,14 +98,16 @@ async def test_empty_entity_id_returns_empty_without_query(self): conn.fetch.assert_not_awaited() @pytest.mark.asyncio - async def test_defaults_ordem_por_peso_e_peso_minimo_2(self): + 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", 2) + 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"]) diff --git a/tests/resolvers/test_public_content.py b/tests/resolvers/test_public_content.py index cc76401..2544860 100644 --- a/tests/resolvers/test_public_content.py +++ b/tests/resolvers/test_public_content.py @@ -626,7 +626,7 @@ def test_related_entity_type_and_query_signature(self): assert "kind: String!" in block assert ( "relatedEntities(id: String!, limit: Int! = 12, " - "orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 2): [RelatedEntity!]!" + "orderBy: RelatedEntityOrder! = WEIGHT, minWeight: Int! = 1): [RelatedEntity!]!" in sdl ) @@ -762,7 +762,7 @@ async def test_maps_records_preserving_order(self): }, ] pg.get_related_entities.assert_awaited_once_with( - "Q123", limit=12, order_by="weight", min_weight=2 + "Q123", limit=12, order_by="weight", min_weight=1 ) @pytest.mark.asyncio @@ -772,8 +772,9 @@ 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}" + # 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=2 + "Q1", limit=12, order_by="weight", min_weight=1 ) @pytest.mark.asyncio From dfef0517ad47699d42a2ec67b82a03b5e8b4a410 Mon Sep 17 00:00:00 2001 From: nitai Date: Wed, 21 Oct 2026 20:32:19 -0300 Subject: [PATCH 20/20] =?UTF-8?q?fix:=20relatedEntities=20com=20minWeight?= =?UTF-8?q?=20padr=C3=A3o=201,=20retrocompat=C3=ADvel=20com=20o=20portal?= =?UTF-8?q?=20(green)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Default de minWeight volta a incluir os vizinhos de co-menção única (weight >= 1): sem args novos, relatedEntities devolve a mesma lista de antes, então os chips do portal não encolhem. minWeight: 2 continua disponível para cortar ruído (o gobus passa explicitamente). O limiar >= 2 do entityNetwork egoCentered (opt-in) não muda. Descrição do campo e gotcha em docs/exemplos.md atualizados; SDL regenerado. --- docs/exemplos.md | 5 +++-- docs/reference/schema.graphql | 4 ++-- docs/reference/schema.md | 4 ++-- src/graphql_api/datasources/postgres.py | 7 ++++--- src/graphql_api/schema/resolvers/public_content.py | 8 ++++---- 5 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/exemplos.md b/docs/exemplos.md index 1866435..b02c008 100644 --- a/docs/exemplos.md +++ b/docs/exemplos.md @@ -320,7 +320,8 @@ mutation Features($id: String!, $f: JSON!) { upsertFeatures(uniqueId: $id, featu - **`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` omite co-menções únicas por padrão** (`minWeight: 2`); - `minWeight: 1` devolve a lista completa de antes. + - **`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 41959ab..b8f27c4 100644 --- a/docs/reference/schema.graphql +++ b/docs/reference/schema.graphql @@ -785,9 +785,9 @@ 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 com weight >= `minWeight` (mínimo 1), ordenados por `orderBy` (default 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! = 2): [RelatedEntity!]! + 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. diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 3ca36a4..d3ae440 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -796,9 +796,9 @@ 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 com weight >= `minWeight` (mínimo 1), ordenados por `orderBy` (default 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! = 2): [RelatedEntity!]! + 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. diff --git a/src/graphql_api/datasources/postgres.py b/src/graphql_api/datasources/postgres.py index 35fba99..db4f9ab 100644 --- a/src/graphql_api/datasources/postgres.py +++ b/src/graphql_api/datasources/postgres.py @@ -1185,7 +1185,7 @@ async def get_related_entities( entity_id: str, limit: int = 12, order_by: str = "weight", - min_weight: int = 2, + min_weight: int = 1, ) -> list[RelatedEntityRecord]: """Vizinhos 1-hop de `entity_id` na rede de co-menção (Fase 6c). @@ -1193,8 +1193,9 @@ async def get_related_entities( ponta, pega a "outra ponta" e junta com `entity_registry` para hidratar 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). `order_by`: 'weight' (default), 'unique_content' ou 'lift' - (nulos por último; desempate weight desc). Até `limit`. `entity_id` + (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}") diff --git a/src/graphql_api/schema/resolvers/public_content.py b/src/graphql_api/schema/resolvers/public_content.py index 5bbfb06..f199c4b 100644 --- a/src/graphql_api/schema/resolvers/public_content.py +++ b/src/graphql_api/schema/resolvers/public_content.py @@ -372,9 +372,9 @@ async def entity(self, info: Info, id: str) -> Optional[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 com weight >= " - "`minWeight` (mínimo 1), ordenados por `orderBy` (default WEIGHT = nº " - "de artigos em co-menção) desc, até `limit`. Retorna [] sem Postgres " - "ou sem vizinhos. PÚBLICO." + "`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( @@ -383,7 +383,7 @@ async def related_entities( id: str, limit: int = 12, order_by: RelatedEntityOrder = RelatedEntityOrder.WEIGHT, - min_weight: int = 2, + min_weight: int = 1, ) -> list[RelatedEntity]: ctx = info.context pg = ctx.postgres_ds