Open
fix(nl2sql): 为 Reflector 增加跨轮账本避免改对又改错 #14
jaxAdd on Sep 18
fix(nl2sql): 为 Reflector 增加跨轮账本避免改对又改错 #14
Open
Merged fromfix/reflector-history-0930intoupstream-br_release_930
Total: 31 files changed+1743-514
| @@ -72,14 +72,20 @@ class BaseNL2SQLNode(BaseNode): | |||
| 72 | else: | 72 | else: |
| 73 | self._nl2sql_context_dump_dir = None | 73 | self._nl2sql_context_dump_dir = None |
| 74 | 74 | ||
| 75 | - async def execute_with_llm(self, context: dict[str, str], action: str = "") -> str: | 75 | + async def execute_with_llm( |
| 76 | - """Render the node prompts and asynchronously invoke the configured LLM.""" | 76 | + self, context: dict[str, str], action: str = "", *, prompt_node: str | None = None |
| 77 | + ) -> str: | ||
| 78 | + """Render NL2SQL prompts and asynchronously invoke the configured LLM. | ||
| 79 | + | ||
| 80 | + ``prompt_node`` selects which prompt directory to load. It defaults to | ||
| 81 | + this node's name so callers can reuse another node's templates without | ||
| 82 | + copying the invocation logic. | ||
| 83 | + """ | ||
| 84 | + node = prompt_node or self.name | ||
| 77 | llm = llm_manager.get_default_llm() | 85 | llm = llm_manager.get_default_llm() |
| 78 | - system_prompt = PromptTemplate.from_package_relative( | 86 | + system_prompt = PromptTemplate.from_package_relative(f"{NL2SQL_PROMPT_PREFIX}/{node}/{action}system").content |
| 79 | - f"{NL2SQL_PROMPT_PREFIX}/{self.name}/{action}system" | ||
| 80 | - ).content | ||
| 81 | user_prompt = PromptTemplate.from_package_relative( | 87 | user_prompt = PromptTemplate.from_package_relative( |
| 82 | - f"{NL2SQL_PROMPT_PREFIX}/{self.name}/{action}user" | 88 | + f"{NL2SQL_PROMPT_PREFIX}/{node}/{action}user" |
| 83 | ).apply_prompt_template(**context) | 89 | ).apply_prompt_template(**context) |
| 84 | prompts = [ | 90 | prompts = [ |
| 85 | {"role": "system", "content": system_prompt}, | 91 | {"role": "system", "content": system_prompt}, |
| @@ -87,9 +93,13 @@ class BaseNL2SQLNode(BaseNode): | |||
| 87 | ] | 93 | ] |
| 88 | response = await llm.ainvoke(prompts) | 94 | response = await llm.ainvoke(prompts) |
| 89 | content = response.content | 95 | content = response.content |
| 90 | - self._dump_llm_context(system_prompt, user_prompt, content, self.name, action) | 96 | + self._dump_llm_context(system_prompt, user_prompt, content, node, action) |
| 91 | return content | 97 | return content |
| 92 | 98 | ||
| 99 | + async def execute_dimension_join_llm(self, context: dict[str, str], action: str = "dimension_join_") -> str: | ||
| 100 | + """Rewrite dimension joins with the generator templates, regardless of node name.""" | ||
| 101 | + return await self.execute_with_llm(context, action, prompt_node="generator") | ||
| 102 | + | ||
| 93 | async def execute_with_llm_json(self, context: dict[str, str], action: str = "") -> Any: | 103 | async def execute_with_llm_json(self, context: dict[str, str], action: str = "") -> Any: |
| 94 | """Execute the LLM with the given context and action, returning parsed JSON output.""" | 104 | """Execute the LLM with the given context and action, returning parsed JSON output.""" |
| 95 | for attempt in range(3): | 105 | for attempt in range(3): |
| @@ -275,8 +275,8 @@ class BusinessTwinPerceptorNode(PerceptorNode): | |||
| 275 | return None | 275 | return None |
| 276 | 276 | ||
| 277 | async def _business_twin_schema_linking(self, question: str): | 277 | async def _business_twin_schema_linking(self, question: str): |
| 278 | - """Select the business-twin table family and return its schema, joins, and catalog.""" | 278 | + """Select the business-twin table family and return its schema, joins, catalog, and granularity.""" |
| 279 | - table = await self._select_table_by_business_family(question) | 279 | + table, explicit_granularity = await self._select_table_by_business_family(question) |
| 280 | schema, joins = await asyncio.to_thread(self.full_schema, [table]) | 280 | schema, joins = await asyncio.to_thread(self.full_schema, [table]) |
| 281 | for table in schema.values(): | 281 | for table in schema.values(): |
| 282 | for column in table["columns"].values(): | 282 | for column in table["columns"].values(): |
| @@ -286,7 +286,7 @@ class BusinessTwinPerceptorNode(PerceptorNode): | |||
| 286 | if item | 286 | if item |
| 287 | ) | 287 | ) |
| 288 | catalog = await asyncio.to_thread(self._column_metadata) | 288 | catalog = await asyncio.to_thread(self._column_metadata) |
| 289 | - return schema, joins, catalog | 289 | + return schema, joins, catalog, explicit_granularity |
| 290 | 290 | ||
| 291 | async def _aprocess(self, state: NL2SQLState, runtime: Any = None) -> NL2SQLState: | 291 | async def _aprocess(self, state: NL2SQLState, runtime: Any = None) -> NL2SQLState: |
| 292 | _ = runtime | 292 | _ = runtime |
| @@ -299,7 +299,14 @@ class BusinessTwinPerceptorNode(PerceptorNode): | |||
| 299 | format_administrative_division_rules, | 299 | format_administrative_division_rules, |
| 300 | state["question"], | 300 | state["question"], |
| 301 | ) | 301 | ) |
| 302 | - schema, joins, catalog = await self._business_twin_schema_linking(state["question"]) | 302 | + schema, joins, catalog, explicit_granularity = await self._business_twin_schema_linking(state["question"]) |
| 303 | + if explicit_granularity: | ||
| 304 | + state["sql_rules"] += ( | ||
| 305 | + "\n\n## 时间粒度" | ||
| 306 | + "\n- 问题明确要求了时间粒度:`time` 必须出现在 SELECT 和 GROUP BY,结果每个时间桶一行。" | ||
| 307 | + "\n- 问题中出现的 统计 / 汇总 / 总计 等措辞不改变这一点,不得把结果压成单行。" | ||
| 308 | + "\n- 不得从 SELECT 或 GROUP BY 移除 `time`,任何要求移除 `time` 的意见都应判为无效。" | ||
| 309 | + ) | ||
| 303 | state["schema"] = schema | 310 | state["schema"] = schema |
| 304 | state["joins"] = joins | 311 | state["joins"] = joins |
| 305 | state["schema_str"] = schema_to_ddl(schema, joins, catalog) | 312 | state["schema_str"] = schema_to_ddl(schema, joins, catalog) |
| @@ -350,13 +357,21 @@ class BusinessTwinPerceptorNode(PerceptorNode): | |||
| 350 | ) | 357 | ) |
| 351 | family_name = str(parsed.get("family_name") or "").strip() | 358 | family_name = str(parsed.get("family_name") or "").strip() |
| 352 | granularity = str(parsed.get("granularity") or "").strip() | 359 | granularity = str(parsed.get("granularity") or "").strip() |
| 353 | - return {"family_name": family_name, "granularity": granularity} if family_name and granularity else None | 360 | + if not family_name or not granularity: |
| 361 | + return None | ||
| 362 | + return { | ||
| 363 | + "family_name": family_name, | ||
| 364 | + "granularity": granularity, | ||
| 365 | + "explicit_granularity": parsed.get("explicit_granularity") is True, | ||
| 366 | + } | ||
| 354 | 367 | ||
| 355 | - async def _select_table_by_business_family(self, question: str) -> str: | 368 | + async def _select_table_by_business_family(self, question: str) -> tuple[str, bool]: |
| 369 | + """Return the selected table and whether the question named its time granularity.""" | ||
| 356 | catalog = await asyncio.to_thread(self._full_table_catalog) | 370 | catalog = await asyncio.to_thread(self._full_table_catalog) |
| 357 | pinned = self._pinned_table(question, catalog) | 371 | pinned = self._pinned_table(question, catalog) |
| 358 | if pinned: | 372 | if pinned: |
| 359 | - return pinned | 373 | + # Pinning names a table, not an output granularity, so nothing is claimed here. |
| 374 | + return pinned, False | ||
| 360 | business_id = await self._select_business_id(question) | 375 | business_id = await self._select_business_id(question) |
| 361 | families = self._build_table_family_candidates( | 376 | families = self._build_table_family_candidates( |
| 362 | [table for table in catalog if table["bare_table_name"].lower() not in self._EXPLICIT_ONLY_TABLES], | 377 | [table for table in catalog if table["bare_table_name"].lower() not in self._EXPLICIT_ONLY_TABLES], |
| @@ -371,4 +386,4 @@ class BusinessTwinPerceptorNode(PerceptorNode): | |||
| 371 | table = self._resolve_table_family_selection(selection, families) | 386 | table = self._resolve_table_family_selection(selection, families) |
| 372 | if not table: | 387 | if not table: |
| 373 | raise NL2SQLError("Business-twin table family selection returned no valid table") | 388 | raise NL2SQLError("Business-twin table family selection returned no valid table") |
| 374 | - return table | 389 | + return table, bool(selection and selection.get("explicit_granularity")) |
| @@ -116,7 +116,7 @@ class GeneratorNode(BaseNL2SQLNode): | |||
| 116 | state, | 116 | state, |
| 117 | scenario=self._get_agent_config("DATABASE.perceptor_type", ""), | 117 | scenario=self._get_agent_config("DATABASE.perceptor_type", ""), |
| 118 | dialect=self.dialect, | 118 | dialect=self.dialect, |
| 119 | - execute_with_llm=self.execute_with_llm, | 119 | + execute_with_llm=self.execute_dimension_join_llm, |
| 120 | ) | 120 | ) |
| 121 | ) | 121 | ) |
| 122 | state["sql"] = state["generation_results"][0].sql | 122 | state["sql"] = state["generation_results"][0].sql |
| @@ -15,12 +15,19 @@ from typing import Any | |||
| 15 | 15 | ||
| 16 | from dataagent.agents.nl2sql.errors import SQLSecurityValidationError | 16 | from dataagent.agents.nl2sql.errors import SQLSecurityValidationError |
| 17 | from dataagent.agents.nl2sql.nodes.base_nl2sql_node import BaseNL2SQLNode | 17 | from dataagent.agents.nl2sql.nodes.base_nl2sql_node import BaseNL2SQLNode |
| 18 | -from dataagent.agents.nl2sql.utils.nl2sql_utils import quote_sql_placeholders | 18 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import normalize_sql, process_dimension_joins, quote_sql_placeholders |
| 19 | from dataagent.agents.nl2sql.workflow.state import NL2SQLState, Result | 19 | from dataagent.agents.nl2sql.workflow.state import NL2SQLState, Result |
| 20 | from dataagent.utils.constants import DEFAULT_NL2SQL_REFLECTOR_THRESHOLD | 20 | from dataagent.utils.constants import DEFAULT_NL2SQL_REFLECTOR_THRESHOLD |
| 21 | from dataagent.utils.log import logger | 21 | from dataagent.utils.log import logger |
| 22 | 22 | ||
| 23 | 23 | ||
| 24 | +def _as_str_list(value: Any) -> list[str]: | ||
| 25 | + """Normalize a model-supplied field into a list of strings.""" | ||
| 26 | + if isinstance(value, list | tuple): | ||
| 27 | + return [str(item) for item in value] | ||
| 28 | + return [str(value)] if value else [] | ||
| 29 | + | ||
| 30 | + | ||
| 24 | class ReflectorNode(BaseNL2SQLNode): | 31 | class ReflectorNode(BaseNL2SQLNode): |
| 25 | def __init__(self, **kwargs): | 32 | def __init__(self, **kwargs): |
| 26 | super().__init__(name="reflector", **kwargs) | 33 | super().__init__(name="reflector", **kwargs) |
| @@ -41,38 +48,97 @@ class ReflectorNode(BaseNL2SQLNode): | |||
| 41 | raise SQLSecurityValidationError(violations=violations) | 48 | raise SQLSecurityValidationError(violations=violations) |
| 42 | best = max(safe_results or state["validation_results"], key=lambda result: result.score) | 49 | best = max(safe_results or state["validation_results"], key=lambda result: result.score) |
| 43 | if safe_results and ((best.score >= self.threshold and not best.need_ref) or state["ref_retries"] <= 0): | 50 | if safe_results and ((best.score >= self.threshold and not best.need_ref) or state["ref_retries"] <= 0): |
| 44 | - state["validation_results"] = safe_results | 51 | + return self._approve(state, safe_results, best) |
| 45 | - state["proceed"] = True | ||
| 46 | - state["sql"] = best.sql | ||
| 47 | - state["security_sql_approved"] = True | ||
| 48 | - return state | ||
| 49 | state["ref_retries"] -= 1 | 52 | state["ref_retries"] -= 1 |
| 50 | state["proceed"] = False | 53 | state["proceed"] = False |
| 51 | state["security_sql_approved"] = False | 54 | state["security_sql_approved"] = False |
| 55 | + history = state.setdefault("review_history", []) | ||
| 56 | + reviewed_before = bool(history) | ||
| 57 | + repaired = None | ||
| 52 | for _ in range(3): | 58 | for _ in range(3): |
| 53 | - out = await self._fix_sql(state["validation_results"]) | 59 | + out = await self._fix_sql(state["validation_results"], history) |
| 54 | if len(out) == len(state["validation_results"]): | 60 | if len(out) == len(state["validation_results"]): |
| 55 | - fix_sqls = out | 61 | + repaired = out |
| 56 | break | 62 | break |
| 57 | - else: | 63 | + if repaired is None: |
| 58 | # skip if fail | 64 | # skip if fail |
| 59 | logger.warning("Reflector failed.") | 65 | logger.warning("Reflector failed.") |
| 60 | fix_sqls = [v.sql for v in state["validation_results"]] | 66 | fix_sqls = [v.sql for v in state["validation_results"]] |
| 67 | + else: | ||
| 68 | + fix_sqls = [fix["sql"] for fix in repaired] | ||
| 69 | + changed = self._record_review_round(history, state["validation_results"], repaired) | ||
| 70 | + # The first unchanged round still goes back, so the Validator can read this | ||
| 71 | + # round's `unresolved` report before the loop gives up. | ||
| 72 | + if reviewed_before and safe_results and not best.need_ref and not any(changed): | ||
| 73 | + logger.info("Reflector stopped: SQL unchanged across rounds.") | ||
| 74 | + return self._approve(state, safe_results, best) | ||
| 75 | + current_batch = [] | ||
| 61 | for v, sql in zip(state["validation_results"], fix_sqls, strict=True): | 76 | for v, sql in zip(state["validation_results"], fix_sqls, strict=True): |
| 62 | v.sql, v.score, v.issues, v.need_ref = sql, 0, [], False | 77 | v.sql, v.score, v.issues, v.need_ref = sql, 0, [], False |
| 63 | v.security_checked = False | 78 | v.security_checked = False |
| 64 | v.security_violations = [] | 79 | v.security_violations = [] |
| 80 | + current_batch.append(v) | ||
| 65 | state["generation_results"].append(v) | 81 | state["generation_results"].append(v) |
| 66 | state["validation_results"].clear() | 82 | state["validation_results"].clear() |
| 83 | + if self._config_manager is not None and current_batch: | ||
| 84 | + rewritten = await process_dimension_joins( | ||
| 85 | + [(item.sql, item.prompt, item.strategy) for item in current_batch], | ||
| 86 | + state, | ||
| 87 | + scenario=self._get_agent_config("DATABASE.perceptor_type", ""), | ||
| 88 | + dialect=self.dialect, | ||
| 89 | + execute_with_llm=self.execute_dimension_join_llm, | ||
| 90 | + ) | ||
| 91 | + for original, new in zip(current_batch, rewritten, strict=True): | ||
| 92 | + original.sql = new.sql | ||
| 93 | + original.prompt = new.prompt | ||
| 94 | + original.need_ref = new.need_ref | ||
| 67 | p = "\n".join([s.sql for s in state["generation_results"]]) | 95 | p = "\n".join([s.sql for s in state["generation_results"]]) |
| 68 | message = f"=== Reflector ===\n{p}" | 96 | message = f"=== Reflector ===\n{p}" |
| 69 | logger.info(message) | 97 | logger.info(message) |
| 70 | state["stream_message"] = message | 98 | state["stream_message"] = message |
| 71 | return state | 99 | return state |
| 72 | 100 | ||
| 73 | - async def _fix_sql(self, val_res: list[Result]) -> list[str]: | 101 | + def _approve(self, state: NL2SQLState, safe_results: list[Result], best: Result) -> NL2SQLState: |
| 74 | - cases = [{"id": v.id, "sql": v.sql, "issues": v.issues} for v in val_res] | 102 | + """Accept ``best`` as the final SQL and let the workflow move past reflection.""" |
| 75 | - cases = json.dumps(cases, ensure_ascii=False, separators=(",", ":")) | 103 | + state["validation_results"] = safe_results |
| 76 | - context = {"cases": cases, "prompt": val_res[0].prompt} | 104 | + state["proceed"] = True |
| 105 | + state["sql"] = best.sql | ||
| 106 | + state["security_sql_approved"] = True | ||
| 107 | + return state | ||
| 108 | + | ||
| 109 | + def _record_review_round( | ||
| 110 | + self, history: list[dict[str, Any]], results: list[Result], fixes: list[dict[str, Any]] | ||
| 111 | + ) -> list[bool]: | ||
| 112 | + """Append this round to the ledger and return which candidates actually changed.""" | ||
| 113 | + round_index = max((entry.get("round", 0) for entry in history), default=0) + 1 | ||
| 114 | + changed = [] | ||
| 115 | + for v, fix in zip(results, fixes, strict=True): | ||
| 116 | + is_changed = normalize_sql(v.sql) != normalize_sql(fix["sql"]) | ||
| 117 | + changed.append(is_changed) | ||
| 118 | + history.append( | ||
| 119 | + { | ||
| 120 | + "round": round_index, | ||
| 121 | + "id": v.id, | ||
| 122 | + "sql_before": v.sql, | ||
| 123 | + "issues": list(v.issues), | ||
| 124 | + "sql_after": fix["sql"], | ||
| 125 | + "changed": is_changed, | ||
| 126 | + "unresolved": list(fix["unresolved"]), | ||
| 127 | + } | ||
| 128 | + ) | ||
| 129 | + return changed | ||
| 130 | + | ||
| 131 | + async def _fix_sql( | ||
| 132 | + self, val_res: list[Result], review_history: list[dict[str, Any]] | None = None | ||
| 133 | + ) -> list[dict[str, Any]]: | ||
| 134 | + cases = json.dumps( | ||
| 135 | + [{"id": v.id, "sql": v.sql, "issues": v.issues} for v in val_res], | ||
| 136 | + ensure_ascii=False, | ||
| 137 | + separators=(",", ":"), | ||
| 138 | + ) | ||
| 139 | + history = json.dumps(review_history, ensure_ascii=False, separators=(",", ":")) if review_history else "" | ||
| 140 | + context = {"cases": cases, "prompt": val_res[0].prompt, "review_history": history} | ||
| 77 | response = await self.execute_with_llm_json(context) | 141 | response = await self.execute_with_llm_json(context) |
| 78 | - return [quote_sql_placeholders(x["sql"]) for x in response] | 142 | + return [ |
| 143 | + {"sql": quote_sql_placeholders(x["sql"]), "unresolved": _as_str_list(x.get("unresolved"))} for x in response | ||
| 144 | + ] | ||
| @@ -54,12 +54,14 @@ class ValidatorNode(BaseNL2SQLNode): | |||
| 54 | 54 | ||
| 55 | async def _validate_semantic(self, state: NL2SQLState) -> list[dict[str, Any]]: | 55 | async def _validate_semantic(self, state: NL2SQLState) -> list[dict[str, Any]]: |
| 56 | res = [{"id": r.id, "sql": r.sql} for r in state["generation_results"]] | 56 | res = [{"id": r.id, "sql": r.sql} for r in state["generation_results"]] |
| 57 | + history = state.get("review_history") or [] | ||
| 57 | context = { | 58 | context = { |
| 58 | "schema": state["schema_str"], | 59 | "schema": state["schema_str"], |
| 59 | "evidence": state["evidence"], | 60 | "evidence": state["evidence"], |
| 60 | "question": state["question"], | 61 | "question": state["question"], |
| 61 | "sql_rules": state["sql_rules"], | 62 | "sql_rules": state["sql_rules"], |
| 62 | "sqls": json.dumps(res), | 63 | "sqls": json.dumps(res), |
| 64 | + "review_history": json.dumps(history, ensure_ascii=False) if history else "", | ||
| 63 | } | 65 | } |
| 64 | for _ in range(3): | 66 | for _ in range(3): |
| 65 | out = await self.execute_with_llm_json(context, "validate_semantic_") | 67 | out = await self.execute_with_llm_json(context, "validate_semantic_") |
| @@ -72,6 +74,12 @@ class ValidatorNode(BaseNL2SQLNode): | |||
| 72 | # skip if fail | 74 | # skip if fail |
| 73 | logger.warning("Semantic validator failed.") | 75 | logger.warning("Semantic validator failed.") |
| 74 | res = [{"score": 1, "issues": []}] * len(state["generation_results"]) | 76 | res = [{"score": 1, "issues": []}] * len(state["generation_results"]) |
| 77 | + for r in res: | ||
| 78 | + # Repair is driven by issues, so a score below 1 with nothing to repair | ||
| 79 | + # would send an unrepairable SQL round-tripping through the Reflector. | ||
| 80 | + if not r.get("issues"): | ||
| 81 | + r["issues"] = [] | ||
| 82 | + r["score"] = 1 | ||
| 75 | return res | 83 | return res |
| 76 | 84 | ||
| 77 | async def _validate_syntax(self, gen_res: list[Result], schema: dict) -> list[dict[str, Any]]: | 85 | async def _validate_syntax(self, gen_res: list[Result], schema: dict) -> list[dict[str, Any]]: |
| @@ -56,11 +56,6 @@ | |||
| 56 | "key_column": "cell_group", | 56 | "key_column": "cell_group", |
| 57 | "value_column": "cell_group_value" | 57 | "value_column": "cell_group_value" |
| 58 | }, | 58 | }, |
| 59 | - "ne_name": { | ||
| 60 | - "dimension_table": "dim_exp_ne", | ||
| 61 | - "key_column": "ne_name", | ||
| 62 | - "value_column": "ne_value" | ||
| 63 | - }, | ||
| 64 | "info_indicate": { | 59 | "info_indicate": { |
| 65 | "dimension_table": "dim_exp_info_indicate", | 60 | "dimension_table": "dim_exp_info_indicate", |
| 66 | "key_column": "info_indicate", | 61 | "key_column": "info_indicate", |
| @@ -53,13 +53,34 @@ | |||
| 53 | 11. PRB 即无线负载。查询“上行/下行 PRB 使用量、使用率、利用率、负载量或负载值”本身时,抽取对应 `cell_prb_*` 指标;PRB/负载仅用于限定业务体验或应用流量场景时,抽取 `cell_ul_group` 或 `cell_dl_group` 维度。 | 53 | 11. PRB 即无线负载。查询“上行/下行 PRB 使用量、使用率、利用率、负载量或负载值”本身时,抽取对应 `cell_prb_*` 指标;PRB/负载仅用于限定业务体验或应用流量场景时,抽取 `cell_ul_group` 或 `cell_dl_group` 维度。 |
| 54 | 12. AMF、PCF、NWDAF 网元指标必须严格对应。优先抽取字段名中带对应 `_of_amf`、`_of_pcf`、`_of_nwdaf` 后缀的指标,不得把不同网元的相似指标互相替代;仅在具体网元实例作为筛选、分组或输出列时抽取 `ne_name`。 | 54 | 12. AMF、PCF、NWDAF 网元指标必须严格对应。优先抽取字段名中带对应 `_of_amf`、`_of_pcf`、`_of_nwdaf` 后缀的指标,不得把不同网元的相似指标互相替代;仅在具体网元实例作为筛选、分组或输出列时抽取 `ne_name`。 |
| 55 | 55 | ||
| 56 | -# 完整规范字段目录(共 104 项) | 56 | +# 完整规范字段目录(共 156 项) |
| 57 | 57 | ||
| 58 | +- 15min_granularity | 维度 | 15分钟时间粒度维度 | ||
| 58 | - 1h_granularity | 维度 | 1小时时间粒度维度 | 59 | - 1h_granularity | 维度 | 1小时时间粒度维度 |
| 59 | - 1d_granularity | 维度 | 1天时间粒度维度 | 60 | - 1d_granularity | 维度 | 1天时间粒度维度 |
| 60 | -- 15min_granularity | 维度 | 15分钟时间粒度维度 | ||
| 61 | -- app_assurance_times_of_nwdaf | 指标 | 应用保障触发次数 | ||
| 62 | - app_id | 维度 | 业务分类;具体业务及其规范值见示例 | 示例:mobile_game=手游类业务, live_streaming=直播类业务, vod_streaming=视频类业务, instant_message=即时通信(消息)业务, voip=即时通信(语音)业务, meeting=会议业务 | 61 | - app_id | 维度 | 业务分类;具体业务及其规范值见示例 | 示例:mobile_game=手游类业务, live_streaming=直播类业务, vod_streaming=视频类业务, instant_message=即时通信(消息)业务, voip=即时通信(语音)业务, meeting=会议业务 |
| 62 | +- cell_dl_group | 维度 | 小区下行负载分群 | 示例:1=下行重载小区, 2=下行中载小区, 3=下行轻载小区 | ||
| 63 | +- cell_id | 维度 | 5G小区,MCC(3)+MNC(2~3)+NCI(9字节,16进制字符串) | ||
| 64 | +- cell_ul_group | 维度 | 小区上行负载分群 | 示例:1=上行重载小区, 2=上行中载小区, 3=上行轻载小区 | ||
| 65 | +- city | 维度 | 地市 | 示例:320200=无锡市, 110000=北京市 | ||
| 66 | +- county | 维度 | 区县 | 示例:320205=锡山区 | ||
| 67 | +- crh_group | 维度 | 高铁分群 | ||
| 68 | +- crh_railway_id | 维度 | 高铁线路 | ||
| 69 | +- crh_section_id | 维度 | 高铁线路段 | ||
| 70 | +- crh_station_id | 维度 | 高铁站点 | ||
| 71 | +- custom_group | 维度 | 自定义用户分群 | ||
| 72 | +- default5qi_group | 维度 | 默载5QI分群 | 示例:6=5qi6, 8=5qi8, 9=5qi9 | ||
| 73 | +- gnb | 维度 | 5G基站ID,长度22~32bit;16进制的字符串 | ||
| 74 | +- gpsi | 维度 | gpsi/msisdn用户手机号,包含国家码 | ||
| 75 | +- guarantee_group | 维度 | 保障分群 | 示例:1=保障签约用户质差前, 2=保障签约用户质差未保障, 3=保障签约用户质差保障/质差保障中, 4=保障未签约用户 | ||
| 76 | +- most_resolution | 维度 | 最大占比分辨率 | ||
| 77 | +- ne_name | 维度 | NWDAF/PCF/AMF网元名称 NWADF | 示例:nwdaf1、nwdaf2, PCF example: pcf1、pcf2, AMF example: amf1、amf2 | ||
| 78 | +- sub_app_id | 维度 | 各业务分类下的子应用;具体子应用及其规范值见示例 | 示例:mobile_game: wangzherongyao_game=王者荣耀, hepingjingying_game=和平精英, yingxionglianmeng_game=英雄联盟, migu_game=咪咕快游; live_streaming: taobao_live=淘宝, pinduoduo_live=拼多多, huya_live=虎牙直播, douyu_live=斗鱼直播, yy_live=YY直播, migu_live=咪咕直播, douyin_live=抖音, kuaishou_live=快手; instant_message: weixin_im=微信/企业微信IM, qq_im=QQ IM; voip: weixin_voip=微信/企业微信VOIP, qq_voip=QQ VOIP; vod_streaming: migu_vod=咪咕视频, tencent_vod=腾讯视频, iqiyi_vod=爱奇艺视频, mangguo_vod=芒果TV, bilibili_vod=哔哩哔哩, youku_vod=优酷视频, xigua_vod=西瓜视频; meeting: yunshixun_meeting=云视讯, dingding_meeting=钉钉, tencent_meeting=腾讯会议, feishu_meeting=飞书 | ||
| 79 | +- tai | 维度 | MCC(3)+MNC(2~3)+NCI(2字节,16进制字符串) | ||
| 80 | +- term_brand | 维度 | 终端或手机品牌 | 示例:1=苹果, 2=华为, 3=小米, 4=荣耀, 5=OPPO, 6=VIVO, 7=其他品牌 | ||
| 81 | +- accuracy_of_public_usr_id_of_nwdaf | 指标 | 公网用户识别准确率 | ||
| 82 | +- accuracy_of_rail_usr_id_of_nwdaf | 指标 | 高铁用户识别准确率 | ||
| 83 | +- app_assurance_times_of_nwdaf | 指标 | 应用保障触发次数 | ||
| 63 | - app_poor_quality_times_of_nwdaf | 指标 | 应用质差次数 | 84 | - app_poor_quality_times_of_nwdaf | 指标 | 应用质差次数 |
| 64 | - assurance_abnormal_release_times_of_nwdaf | 指标 | NWDAF保障异常释放次数 | 85 | - assurance_abnormal_release_times_of_nwdaf | 指标 | NWDAF保障异常释放次数 |
| 65 | - assurance_duration | 指标 | 保障时长 | 86 | - assurance_duration | 指标 | 保障时长 |
| @@ -69,41 +90,54 @@ | |||
| 69 | - assurance_failure_reason4_times | 指标 | 保障失败原因次数(其他原因) | 90 | - assurance_failure_reason4_times | 指标 | 保障失败原因次数(其他原因) |
| 70 | - assurance_times | 指标 | 保障次数 | 91 | - assurance_times | 指标 | 保障次数 |
| 71 | - assurance_users | 指标 | 保障用户数 | 92 | - assurance_users | 指标 | 保障用户数 |
| 93 | +- att_create_rail_usr_char_ana_pcf_of_nwdaf | 指标 | 接收PCF发送的RAIL_USR_CHAR_ANALYSIS事件订阅创建请求次数 | ||
| 94 | +- att_create_sub_session_amf_of_nwdaf | 指标 | 向AMF发送事件订阅请求次数 | ||
| 95 | +- att_public_usr_events_notify_pcf_of_nwdaf | 指标 | 向PCF发送订阅结果通知请求次数-用户属性为公网用户 | ||
| 96 | +- att_rail_usr_events_notify_pcf_of_nwdaf | 指标 | 向PCF发送订阅结果通知请求次数-用户属性为高铁用户 | ||
| 97 | +- att_update_rail_usr_char_ana_pcf_of_nwdaf | 指标 | 接收PCF发送的RAIL_USR_CHAR_ANALYSIS事件订阅更新请求次数 | ||
| 98 | +- att_update_sub_session_amf_of_nwdaf | 指标 | 向AMF发送事件订阅更新请求次数 | ||
| 72 | - avg_qoe | 指标 | MOS分数总和 | 99 | - avg_qoe | 指标 | MOS分数总和 |
| 100 | +- avg_rail_usr_char_ana_event_of_nwdaf | 指标 | NWDAF上RAIL_USR_CHAR_ANALYSIS事件平均在线订阅事件数 | ||
| 73 | - bit_rate | 指标 | 码率总和 | 101 | - bit_rate | 指标 | 码率总和 |
| 74 | - bit_rate_times | 指标 | 码率计数 | 102 | - bit_rate_times | 指标 | 码率计数 |
| 75 | -- cell_dl_group | 维度 | 小区下行负载分群 | 示例:1=下行重载小区, 2=下行中载小区, 3=下行轻载小区 | ||
| 76 | -- cell_id | 维度 | 5G小区,MCC(3)+MNC(2~3)+NCI(9字节,16进制字符串) | ||
| 77 | - cell_prb_dl_total | 指标 | 无线小区下行PRB可用数 | 103 | - cell_prb_dl_total | 指标 | 无线小区下行PRB可用数 |
| 78 | - cell_prb_dl_usage | 指标 | 无线小区下行PRB占用数 | 104 | - cell_prb_dl_usage | 指标 | 无线小区下行PRB占用数 |
| 79 | - cell_prb_ul_total | 指标 | 无线小区上行PRB可用数 | 105 | - cell_prb_ul_total | 指标 | 无线小区上行PRB可用数 |
| 80 | - cell_prb_ul_usage | 指标 | 无线小区上行PRB占用数 | 106 | - cell_prb_ul_usage | 指标 | 无线小区上行PRB占用数 |
| 81 | -- cell_ul_group | 维度 | 小区上行负载分群 | 示例:1=上行重载小区, 2=上行中载小区, 3=上行轻载小区 | 107 | +- com_users | 指标 | 普通用户数 |
| 82 | -- city | 维度 | 地市 | 示例:320200=无锡市, 110000=北京市 | ||
| 83 | -- county | 维度 | 区县 | 示例:320205=锡山区 | ||
| 84 | -- crh_group | 维度 | 高铁分群 | ||
| 85 | - crh_ride_times | 指标 | 高铁乘坐次数 | 108 | - crh_ride_times | 指标 | 高铁乘坐次数 |
| 109 | +- crh_sub_users | 指标 | 高铁签约用户数 | ||
| 110 | +- crh_trigger_first_n23_create_times | 指标 | 首次N23会话创建上报次数 | ||
| 111 | +- crh_trigger_nwdaf_n23_cancel_subs_times | 指标 | NWDAF触发的N23取消订阅次数 | ||
| 112 | +- crh_trigger_pcf_n23_cancel_subs_times | 指标 | PCF触发的N23取消订阅次数 | ||
| 113 | +- crh_trigger_pra_in_times | 指标 | PRA_IN次数 | ||
| 114 | +- crh_trigger_pra_out_times | 指标 | PRA_OUT次数 | ||
| 115 | +- crh_trigger_usertype_chg_times | 指标 | 用户类型切换次数 | ||
| 116 | +- crh_unsub_users | 指标 | 高铁未签约用户数 | ||
| 86 | - crh_users | 指标 | 高铁画像用户数 | 117 | - crh_users | 指标 | 高铁画像用户数 |
| 87 | -- custom_group | 维度 | 自定义用户分群 | 118 | +- cur_act_public_usr_num_of_nwdaf | 指标 | 当前在线的公网用户数 |
| 88 | -- default5qi_group | 维度 | 默载5QI分群 | 示例:6=5qi6, 8=5qi8, 9=5qi9 | 119 | +- cur_de_num_of_public_usr_of_nwdaf | 指标 | 当前在线的公网用户在专网数 |
| 120 | +- de_acc_num_of_public_usr_of_nwdaf | 指标 | 公网用户接入高铁专网次数(空闲态进入连接态) | ||
| 121 | +- de_acc_num_of_rail_usr_of_nwdaf | 指标 | 高铁用户接入高铁专网次数(空闲态进入连接态) | ||
| 122 | +- de_mig_num_of_public_usr_of_nwdaf | 指标 | 公网用户迁出高铁专网次数(空闲态进入连接态) | ||
| 123 | +- de_mig_num_of_rail_usr_of_nwdaf | 指标 | 高铁用户迁出高铁专网次数(空闲态进入连接态) | ||
| 89 | - delay_an | 指标 | 无线时延总和 | 124 | - delay_an | 指标 | 无线时延总和 |
| 90 | - delay_an_times | 指标 | 无线时延计数 | 125 | - delay_an_times | 指标 | 无线时延计数 |
| 91 | - delay_dn | 指标 | 有线时延总和 | 126 | - delay_dn | 指标 | 有线时延总和 |
| 92 | - delay_dn_times | 指标 | 有线时延计数 | 127 | - delay_dn_times | 指标 | 有线时延计数 |
| 93 | - delay_e2e | 指标 | 端到端时延总和 | 128 | - delay_e2e | 指标 | 端到端时延总和 |
| 94 | - delay_e2e_times | 指标 | 端到端时延计数 | 129 | - delay_e2e_times | 指标 | 端到端时延计数 |
| 130 | +- downlink_avg_duration | 指标 | 下行平均总时长 | ||
| 131 | +- downlink_avg_traffic | 指标 | 下行平均总流量 | ||
| 95 | - downlink_duration | 指标 | 下行总时长 | 132 | - downlink_duration | 指标 | 下行总时长 |
| 96 | - downlink_traffic | 指标 | 下行总流量 | 133 | - downlink_traffic | 指标 | 下行总流量 |
| 97 | -- exp_subs_count | 指标 | 用户数 | ||
| 98 | - from_amf_policy_auth_request_times_of_pcf | 指标 | AMF向PCF发送AM策略授权请求次数 | 134 | - from_amf_policy_auth_request_times_of_pcf | 指标 | AMF向PCF发送AM策略授权请求次数 |
| 99 | -- gnb | 维度 | 5G基站ID,长度22~32bit;16进制的字符串 | ||
| 100 | -- gpsi | 维度 | gpsi/msisdn用户手机号,包含国家码 | ||
| 101 | -- guarantee_group | 维度 | 保障分群 | 示例:1=保障签约用户质差前, 2=保障签约用户质差未保障, 3=保障签约用户质差保障/质差保障中, 4=保障未签约用户 | ||
| 102 | -- info_indicate | 维度 | 体验信息单据类型 | ||
| 103 | - key_service_assurance_req_times_of_nwdaf | 指标 | 重点业务保障请求次数 | 135 | - key_service_assurance_req_times_of_nwdaf | 指标 | 重点业务保障请求次数 |
| 104 | - key_service_assurance_success_times_of_nwdaf | 指标 | 重点业务保障完全成功次数 | 136 | - key_service_assurance_success_times_of_nwdaf | 指标 | 重点业务保障完全成功次数 |
| 105 | - lost_pkg_dl | 指标 | 下行丢包数 | 137 | - lost_pkg_dl | 指标 | 下行丢包数 |
| 106 | - lost_pkg_ul | 指标 | 上行丢包数 | 138 | - lost_pkg_ul | 指标 | 上行丢包数 |
| 139 | +- max_act_public_usr_num_of_nwdaf | 指标 | 最大在线的公网用户数 | ||
| 140 | +- max_act_rail_usr_num_of_nwdaf | 指标 | 最大在线的高铁用户数 | ||
| 107 | - max_bit_rate | 指标 | 最大码率总和 | 141 | - max_bit_rate | 指标 | 最大码率总和 |
| 108 | - max_bit_rate_times | 指标 | 最大码率计数 | 142 | - max_bit_rate_times | 指标 | 最大码率计数 |
| 109 | - max_delay_an | 指标 | 无线最大时延 | 143 | - max_delay_an | 指标 | 无线最大时延 |
| @@ -112,13 +146,13 @@ | |||
| 112 | - max_delay_dn_times | 指标 | 有线最大时延计数 | 146 | - max_delay_dn_times | 指标 | 有线最大时延计数 |
| 113 | - max_online_qos_ana_event_subs_sessions_of_nwdaf | 指标 | 最大在线的QOS_ANALYSIS事件订阅会话数 | 147 | - max_online_qos_ana_event_subs_sessions_of_nwdaf | 指标 | 最大在线的QOS_ANALYSIS事件订阅会话数 |
| 114 | - max_online_qos_exp_event_subs_sessions_of_nwdaf | 指标 | 最大在线的QOS体验事件订阅会话数 | 148 | - max_online_qos_exp_event_subs_sessions_of_nwdaf | 指标 | 最大在线的QOS体验事件订阅会话数 |
| 149 | +- max_rail_usr_char_ana_event_of_nwdaf | 指标 | NWDAF上RAIL_USR_CHAR_ANALYSIS事件最大在线订阅事件数 | ||
| 115 | - max_resolution*_times | 指标 | 最高分辨率的次数分布 | 150 | - max_resolution*_times | 指标 | 最高分辨率的次数分布 |
| 116 | -- mos4_qds | 维度 | 保障MOS四象限 | 151 | +- med_duration_of_public_usr_id_of_nwdaf | 指标 | 公网用户识别时长(中位数) |
| 152 | +- med_duration_of_rail_usr_id_of_nwdaf | 指标 | 高铁用户识别时长(中位数) | ||
| 117 | - mos_sec*_times | 指标 | MOS分段次数分布 | 153 | - mos_sec*_times | 指标 | MOS分段次数分布 |
| 118 | -- mos_sec*_users | 指标 | MOS分段用户数分布 | ||
| 119 | - mos_times | 指标 | MOS分数计数 | 154 | - mos_times | 指标 | MOS分数计数 |
| 120 | - most_resolution*_times | 指标 | 占比最高分辨率的次数分布 | 155 | - most_resolution*_times | 指标 | 占比最高分辨率的次数分布 |
| 121 | -- ne_name | 维度 | NWDAF/PCF/AMF网元名称 NWADF | 示例:nwdaf1、nwdaf2, PCF example: pcf1、pcf2, AMF example: amf1、amf2 | ||
| 122 | - online_qos_ana_event_subs_sessions_of_nwdaf | 指标 | 当前在线的QOS_ANALYSIS事件订阅会话数 | 156 | - online_qos_ana_event_subs_sessions_of_nwdaf | 指标 | 当前在线的QOS_ANALYSIS事件订阅会话数 |
| 123 | - online_qos_exp_event_subs_sessions_of_nwdaf | 指标 | 当前在线的QOS体验事件订阅会话数 | 157 | - online_qos_exp_event_subs_sessions_of_nwdaf | 指标 | 当前在线的QOS体验事件订阅会话数 |
| 124 | - pkg_dl | 指标 | 下行总包数 | 158 | - pkg_dl | 指标 | 下行总包数 |
| @@ -128,6 +162,18 @@ | |||
| 128 | - poor_delay_an_times | 指标 | NWDAF保障业务有线时延质差次数 | 162 | - poor_delay_an_times | 指标 | NWDAF保障业务有线时延质差次数 |
| 129 | - poor_delay_dn_times | 指标 | NWDAF保障业务无线时延质差次数 | 163 | - poor_delay_dn_times | 指标 | NWDAF保障业务无线时延质差次数 |
| 130 | - poor_delay_e2e_times | 指标 | NWDAF保障业务端到端时延质差次数 | 164 | - poor_delay_e2e_times | 指标 | NWDAF保障业务端到端时延质差次数 |
| 165 | +- poor_mos_times | 指标 | MOS质差次数 | ||
| 166 | +- poor_service_delay_times | 指标 | 业务时延质差次数 | ||
| 167 | +- poor_stalling_duration_times | 指标 | 卡顿时长质差次数 | ||
| 168 | +- poor_total_times | 指标 | 总质差次数 | ||
| 169 | +- pub_users | 指标 | 公网用户数 | ||
| 170 | +- record_count | 指标 | 单据数 | ||
| 171 | +- record_duration_100_150 | 指标 | 单据时长100-150ms计数 | ||
| 172 | +- record_duration_150_200 | 指标 | 单据时长150-200ms计数 | ||
| 173 | +- record_duration_200_250 | 指标 | 单据时长200-250ms计数 | ||
| 174 | +- record_duration_50_100 | 指标 | 单据时长50-100ms计数 | ||
| 175 | +- record_duration_gt_250 | 指标 | 单据时长>250ms计数 | ||
| 176 | +- record_duration_lt_50 | 指标 | 单据时长<50ms计数 | ||
| 131 | - recv_pcf_policy_auth_creation_success_times_of_nwdaf | 指标 | NWDAF接收PCF回复的策略授权创建成功次数 | 177 | - recv_pcf_policy_auth_creation_success_times_of_nwdaf | 指标 | NWDAF接收PCF回复的策略授权创建成功次数 |
| 132 | - recv_pcf_qos_ana_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF接收PCF发送的QOS_ANALYSIS事件订阅创建请求次数 | 178 | - recv_pcf_qos_ana_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF接收PCF发送的QOS_ANALYSIS事件订阅创建请求次数 |
| 133 | - recv_pcf_qos_exp_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF接收PCF发送(即PCF发起)的QOS体验事件订阅创建请求次数 | 179 | - recv_pcf_qos_exp_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF接收PCF发送(即PCF发起)的QOS体验事件订阅创建请求次数 |
| @@ -142,11 +188,15 @@ | |||
| 142 | - service_initial_duration_times | 指标 | 业务初始时长计数 | 188 | - service_initial_duration_times | 指标 | 业务初始时长计数 |
| 143 | - service_times | 指标 | 业务使用次数 | 189 | - service_times | 指标 | 业务使用次数 |
| 144 | - stalling_duration | 指标 | 卡顿时长总和 | 190 | - stalling_duration | 指标 | 卡顿时长总和 |
| 191 | +- stalling_duration_times | 指标 | 卡顿时长计数 | ||
| 145 | - stalling_number | 指标 | 卡顿次数总和 | 192 | - stalling_number | 指标 | 卡顿次数总和 |
| 146 | - sub_app_eff_duration | 指标 | 应用有效时长 | 193 | - sub_app_eff_duration | 指标 | 应用有效时长 |
| 147 | -- sub_app_id | 维度 | 各业务分类下的子应用;具体子应用及其规范值见示例 | 示例:mobile_game: wangzherongyao_game=王者荣耀, hepingjingying_game=和平精英, yingxionglianmeng_game=英雄联盟, migu_game=咪咕快游; live_streaming: taobao_live=淘宝, pinduoduo_live=拼多多, huya_live=虎牙直播, douyu_live=斗鱼直播, yy_live=YY直播, migu_live=咪咕直播, douyin_live=抖音, kuaishou_live=快手; instant_message: weixin_im=微信/企业微信IM, qq_im=QQ IM; voip: weixin_voip=微信/企业微信VOIP, qq_voip=QQ VOIP; vod_streaming: migu_vod=咪咕视频, tencent_vod=腾讯视频, iqiyi_vod=爱奇艺视频, mangguo_vod=芒果TV, bilibili_vod=哔哩哔哩, youku_vod=优酷视频, xigua_vod=西瓜视频; meeting: yunshixun_meeting=云视讯, dingding_meeting=钉钉, tencent_meeting=腾讯会议, feishu_meeting=飞书 | 194 | +- succ_create_rail_usr_char_ana_pcf_of_nwdaf | 指标 | 向PCF回复RAIL_USR_CHAR_ANALYSIS事件订阅创建成功次数 |
| 148 | -- tai | 维度 | MCC(3)+MNC(2~3)+NCI(2字节,16进制字符串) | 195 | +- succ_create_sub_session_amf_of_nwdaf | 指标 | 接收AMF事件订阅成功次数 |
| 149 | -- term_brand | 维度 | 终端或手机品牌 | 示例:1=苹果, 2=华为, 3=小米, 4=荣耀, 5=OPPO, 6=VIVO, 7=其他品牌 | 196 | +- succ_public_usr_events_notify_pcf_of_nwdaf | 指标 | 接收PCF回复的订阅结果通知成功次数-用户属性为公网用户 |
| 197 | +- succ_rail_usr_events_notify_rail_usr_pcf_of_nwdaf | 指标 | 接收PCF回复的订阅结果通知成功次数-用户属性为高铁用户 | ||
| 198 | +- succ_update_rail_usr_char_ana_pcf_of_nwdaf | 指标 | 向PCF回复RAIL_USR_CHAR_ANALYSIS事件订阅更新成功次数 | ||
| 199 | +- succ_update_sub_session_amf_of_nwdaf | 指标 | 接收AMF事件订阅更新成功次数 | ||
| 150 | - to_amf_policy_auth_request_success_times_of_pcf | 指标 | PCF向AMF回复AM策略授权请求成功次数 | 200 | - to_amf_policy_auth_request_success_times_of_pcf | 指标 | PCF向AMF回复AM策略授权请求成功次数 |
| 151 | - to_pcf_policy_auth_creation_request_times_of_nwdaf | 指标 | NWDAF向PCF发送策略授权创建请求次数 | 201 | - to_pcf_policy_auth_creation_request_times_of_nwdaf | 指标 | NWDAF向PCF发送策略授权创建请求次数 |
| 152 | - to_pcf_qos_ana_event_subs_creation_success_times_of_nwdaf | 指标 | NWDAF向PCF回复QOS_ANALYSIS事件订阅创建成功次数 | 202 | - to_pcf_qos_ana_event_subs_creation_success_times_of_nwdaf | 指标 | NWDAF向PCF回复QOS_ANALYSIS事件订阅创建成功次数 |
| @@ -154,8 +204,10 @@ | |||
| 154 | - to_smf_qos_ana_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF向SMF发送的QOS_ANA事件订阅创建请求次数 | 204 | - to_smf_qos_ana_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF向SMF发送的QOS_ANA事件订阅创建请求次数 |
| 155 | - to_smf_qos_exp_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF向SMF发送的QOS_EXP事件订阅创建请求次数 | 205 | - to_smf_qos_exp_event_subs_creation_request_times_of_nwdaf | 指标 | NWDAF向SMF发送的QOS_EXP事件订阅创建请求次数 |
| 156 | - trigger_assurance_users | 指标 | 触发保障用户数 | 206 | - trigger_assurance_users | 指标 | 触发保障用户数 |
| 207 | +- unk_users | 指标 | 未知用户数 | ||
| 208 | +- uplink_avg_duration | 指标 | 上行平均总时长 | ||
| 209 | +- uplink_avg_traffic | 指标 | 上行平均总流量 | ||
| 157 | - uplink_duration | 指标 | 上行总时长 | 210 | - uplink_duration | 指标 | 上行总时长 |
| 158 | - uplink_traffic | 指标 | 上行总流量 | 211 | - uplink_traffic | 指标 | 上行总流量 |
| 159 | -- user_type | 维度 | 高铁用户类型 | ||
| 160 | - volume_dl | 指标 | 下行有效流量 | 212 | - volume_dl | 指标 | 下行有效流量 |
| 161 | -- volume_ul | 指标 | 上行有效流量 | 213 | +- volume_ul | 指标 | 上行有效流量 |
| @@ -1,6 +1,6 @@ | |||
| 1 | # 任务 | 1 | # 任务 |
| 2 | 2 | ||
| 3 | -你是云核业务孪生表簇与时间粒度选择器。根据用户问题和候选表簇,选择一个最合适的 `family_name`,以及该表簇真实存在的一个 `granularity`。 | 3 | +你是云核业务孪生表簇与时间粒度选择器。根据用户问题和候选表簇,选择一个最合适的 `family_name`、该表簇真实存在的一个 `granularity`,并报告该粒度是用户显式要求的还是你自己推导的。 |
| 4 | 4 | ||
| 5 | # 不可违反的硬约束 | 5 | # 不可违反的硬约束 |
| 6 | 6 | ||
| @@ -9,8 +9,9 @@ | |||
| 9 | 3. 用户请求但候选中不存在的粒度只能作为选择目标参与回退,不得输出用户请求但候选中不存在的粒度。 | 9 | 3. 用户请求但候选中不存在的粒度只能作为选择目标参与回退,不得输出用户请求但候选中不存在的粒度。 |
| 10 | 4. 所选表簇必须包含问题明确需要的全部非时间维度;缺少任一必需维度的表簇不可选择。 | 10 | 4. 所选表簇必须包含问题明确需要的全部非时间维度;缺少任一必需维度的表簇不可选择。 |
| 11 | 5. 必须且只能选择一个表簇和一个粒度。即使存在并列候选,也必须按本提示词的规则选出一个。 | 11 | 5. 必须且只能选择一个表簇和一个粒度。即使存在并列候选,也必须按本提示词的规则选出一个。 |
| 12 | -6. 只返回 `family_name` 和 `granularity`,不得构造或返回具体的 `_metric_*` 表名。 | 12 | +6. 只返回 `family_name`、`granularity` 和 `explicit_granularity`,不得构造或返回具体的 `_metric_*` 表名。 |
| 13 | 7. 必须保持下方规定的输出格式,不得添加分析过程、解释或其他字段。 | 13 | 7. 必须保持下方规定的输出格式,不得添加分析过程、解释或其他字段。 |
| 14 | +8. `explicit_granularity` 必须如实反映第二步的判断:问题里存在显式时间粒度时为 `true`,只有查询时间范围而由第三步推导粒度时为 `false`。它与回退无关——即使显式粒度在候选中不存在而回退到别的值,只要问题写明了粒度就仍为 `true`。 | ||
| 14 | 15 | ||
| 15 | # 输入说明 | 16 | # 输入说明 |
| 16 | 17 | ||
| @@ -106,7 +107,8 @@ | |||
| 106 | 2. 该表簇是否包含全部必需维度。 | 107 | 2. 该表簇是否包含全部必需维度。 |
| 107 | 3. `granularity` 是否逐字存在于该表簇的“表簇可用时间粒度”。 | 108 | 3. `granularity` 是否逐字存在于该表簇的“表簇可用时间粒度”。 |
| 108 | 4. 如果 `granularity` 不在该表簇列表中,当前答案无效,必须按照第四步重新选择后再输出。 | 109 | 4. 如果 `granularity` 不在该表簇列表中,当前答案无效,必须按照第四步重新选择后再输出。 |
| 109 | -5. 是否只输出了一个 JSON 对象,并且没有具体 `_metric_*` 表名或额外字段。 | 110 | +5. `explicit_granularity` 是否与第二步的判断一致。 |
| 111 | +6. 是否只输出了一个 JSON 对象,并且没有具体 `_metric_*` 表名或额外字段。 | ||
| 110 | 112 | ||
| 111 | # Output Format | 113 | # Output Format |
| 112 | 114 | ||
| @@ -115,6 +117,7 @@ Return exactly one JSON object enclosed in a `json` code block. | |||
| 115 | ```json | 117 | ```json |
| 116 | { | 118 | { |
| 117 | "family_name": "fact_dw1745159007_00000000000181c4", | 119 | "family_name": "fact_dw1745159007_00000000000181c4", |
| 118 | - "granularity": "1d" | 120 | + "granularity": "1d", |
| 121 | + "explicit_granularity": false | ||
| 119 | } | 122 | } |
| 120 | ``` | 123 | ``` |
| @@ -4,10 +4,13 @@ Your task is to minimally fix each given SQL queries strictly based on its provi | |||
| 4 | 4 | ||
| 5 | # Input | 5 | # Input |
| 6 | - <cases>: SQLs and issues. | 6 | - <cases>: SQLs and issues. |
| 7 | +- <review_history>: Prior rounds of issues, the repairs made, and the issues reported unresolved. | ||
| 7 | - <prev_prompt>: Previous generation prompt, with schema, query, and rules as reference. | 8 | - <prev_prompt>: Previous generation prompt, with schema, query, and rules as reference. |
| 8 | 9 | ||
| 9 | # Instructions | 10 | # Instructions |
| 10 | -- Modify each SQL to resolve its corresponding issues. | 11 | +- Modify each SQL to resolve only its current issues. |
| 12 | +- Do not undo a repair recorded in <review_history>. If a current issue conflicts with one, keep the earlier repair and report the current issue in `unresolved`. | ||
| 13 | +- If no edit can resolve an issue, leave that SQL as it is and report the issue in `unresolved`. That happens when the schema or SQL cannot express the requirement, or when the SQL already satisfies it. | ||
| 11 | - Preserve the original intent and structure of each SQL as much as possible. | 14 | - Preserve the original intent and structure of each SQL as much as possible. |
| 12 | - You may adjust related clauses if necessary to fully resolve the issue. | 15 | - You may adjust related clauses if necessary to fully resolve the issue. |
| 13 | - Use only tables and columns from the provided schema. | 16 | - Use only tables and columns from the provided schema. |
| @@ -17,12 +20,16 @@ Your task is to minimally fix each given SQL queries strictly based on its provi | |||
| 17 | For each SQL, analyze and repair independently, return: | 20 | For each SQL, analyze and repair independently, return: |
| 18 | - id | 21 | - id |
| 19 | - sql: the repaired SQL | 22 | - sql: the repaired SQL |
| 23 | +- unresolved: issues you could not resolve by changing the SQL, each with a short reason; use an empty list when every issue was fixed | ||
| 20 | Return a json array enclosed in ```json``` block. | 24 | Return a json array enclosed in ```json``` block. |
| 21 | ```json | 25 | ```json |
| 22 | [ | 26 | [ |
| 23 | { | 27 | { |
| 24 | "id": <id>, | 28 | "id": <id>, |
| 25 | - "sql": <sql> | 29 | + "sql": <sql>, |
| 30 | + "unresolved": [ | ||
| 31 | + <issue and why it cannot be fixed by changing SQL> | ||
| 32 | + ] | ||
| 26 | } | 33 | } |
| 27 | ] | 34 | ] |
| 28 | -``` | 35 | +``` |
| @@ -2,6 +2,12 @@ | |||
| 2 | {{ cases }} | 2 | {{ cases }} |
| 3 | </cases> | 3 | </cases> |
| 4 | 4 | ||
| 5 | +{% if review_history %} | ||
| 6 | +<review_history> | ||
| 7 | +{{ review_history }} | ||
| 8 | +</review_history> | ||
| 9 | +{% endif %} | ||
| 10 | + | ||
| 5 | <prev_prompt> | 11 | <prev_prompt> |
| 6 | {{ prompt }} | 12 | {{ prompt }} |
| 7 | -</prev_prompt> | 13 | +</prev_prompt> |
| @@ -17,8 +17,9 @@ Before applying any other rules, first determine whether the compared items are | |||
| 17 | - Schema descriptions starting with '维度' are dimension fields. | 17 | - Schema descriptions starting with '维度' are dimension fields. |
| 18 | - Schema descriptions starting with '指标' are metric fields. | 18 | - Schema descriptions starting with '指标' are metric fields. |
| 19 | - Identify the dimensions involved in the user question. A dimension is involved only when the question refers to the dimension itself or one of its values. | 19 | - Identify the dimensions involved in the user question. A dimension is involved only when the question refers to the dimension itself or one of its values. |
| 20 | +- Scope wording such as 全省, 全网, 不区分X, 不按X, 汇聚全部X, or 覆盖全部X states that the result must NOT be split by X, so X is NOT an involved dimension: keep it out of SELECT and GROUP BY and do not filter on it. Such wording never asks for an extra dimension. 全省 and 全网 mean do not split by `city` or `county`. | ||
| 20 | - SELECT and GROUP BY MUST contain exactly the involved dimensions. | 21 | - SELECT and GROUP BY MUST contain exactly the involved dimensions. |
| 21 | -- **If the user explicitly requests a time-series breakdown (by mentioning any time granularity such as '1h', '1d', '每小时', '每天', '按小时聚合', '时间粒度', or equivalent), then `time` MUST also be included in SELECT and GROUP BY. This includes phrases like "支持时间粒度" or "建议时间粒度".** | 22 | +- **If the user requests a time-series breakdown by naming a bucket size for the result, then `time` MUST also be included in SELECT and GROUP BY. Match on meaning, not on the exact string: '1h', '1d', '粒度为1h', '1h粒度', '时间粒度为15分钟', '每小时', '每天', '按小时聚合', '支持时间粒度', 'hourly' and any other wording or word order all count. Once this applies, `time` is mandatory: the result is one row per bucket, and wording like 统计 or 汇总 elsewhere in the question does not collapse it into a single row. Never drop `time` from SELECT or GROUP BY, and treat any request to remove it as invalid.** |
| 22 | - All metric fields must be aggregated using SUM() (or appropriate aggregate functions) across all dimensions not explicitly involved in the query, and MUST NOT appear in the GROUP BY clause. | 23 | - All metric fields must be aggregated using SUM() (or appropriate aggregate functions) across all dimensions not explicitly involved in the query, and MUST NOT appear in the GROUP BY clause. |
| 23 | - A time range alone does not make time an output dimension; only an explicit time granularity or time-series request does. | 24 | - A time range alone does not make time an output dimension; only an explicit time granularity or time-series request does. |
| 24 | - Use HAVING for filtering aggregated metric results (with the same expression as SELECT). Use WHERE only for pre-aggregation row filtering when explicitly requested. | 25 | - Use HAVING for filtering aggregated metric results (with the same expression as SELECT). Use WHERE only for pre-aggregation row filtering when explicitly requested. |
| @@ -8,7 +8,9 @@ For each SQL, understand its intent, and compare with the question: | |||
| 8 | 1. Does the SQL include EXACT AND ONLY the information asked in the question in the `SELECT` clause? | 8 | 1. Does the SQL include EXACT AND ONLY the information asked in the question in the `SELECT` clause? |
| 9 | 2. Does the SQL include EXACT AND ONLY the conditions and operations stated in the question, such as `JOIN`/`UNION` logic, aggregation level / `GROUP BY` granularity, `WHERE` conditions, and only necessary `DISTINCT`, `ORDER BY`, `LIMIT`, or other transformations? | 9 | 2. Does the SQL include EXACT AND ONLY the conditions and operations stated in the question, such as `JOIN`/`UNION` logic, aggregation level / `GROUP BY` granularity, `WHERE` conditions, and only necessary `DISTINCT`, `ORDER BY`, `LIMIT`, or other transformations? |
| 10 | 3. If the question or evidence defines a metric or formula, does the SQL follow that definition exactly? | 10 | 3. If the question or evidence defines a metric or formula, does the SQL follow that definition exactly? |
| 11 | -4. Does the SQL follow all additional rules? | 11 | +4. Does the SQL follow all additional rules? Additional Rules outrank your own reading of the question: a column an additional rule requires is correct even when the question never names it, and a dimension an additional rule excludes is correctly absent. |
| 12 | + | ||
| 13 | +`Prior Review Rounds`, when present, records earlier rounds for this same question, including the issues raised then and the ones the repairer reported as `unresolved`. Do not repeat an issue already reported `unresolved` unless an edit within the provided schema can now fix it. | ||
| 12 | 14 | ||
| 13 | # Output | 15 | # Output |
| 14 | For each SQL, evaluate independently, return: | 16 | For each SQL, evaluate independently, return: |
| @@ -14,5 +14,10 @@ | |||
| 14 | {{ sql_rules }} | 14 | {{ sql_rules }} |
| 15 | {% endif %} | 15 | {% endif %} |
| 16 | 16 | ||
| 17 | +{% if review_history %} | ||
| 18 | +## Prior Review Rounds | ||
| 19 | +{{ review_history }} | ||
| 20 | +{% endif %} | ||
| 21 | + | ||
| 17 | ## Generated SQLs | 22 | ## Generated SQLs |
| 18 | {{ sqls }} | 23 | {{ sqls }} |
| @@ -260,7 +260,65 @@ def check_allowed_query_syntax(statement: exp.Expression) -> list[SecurityViolat | |||
| 260 | for limit in statement.find_all(exp.Limit): | 260 | for limit in statement.find_all(exp.Limit): |
| 261 | if limit.args.get("offset") or limit.args.get("limit_options") or limit.args.get("expressions"): | 261 | if limit.args.get("offset") or limit.args.get("limit_options") or limit.args.get("expressions"): |
| 262 | return [SecurityViolation("SYNTAX-001", "LIMIT modifier is not in the syntax allowlist.")] | 262 | return [SecurityViolation("SYNTAX-001", "LIMIT modifier is not in the syntax allowlist.")] |
| 263 | - return [] | 263 | + return _check_grouped_projections(statement) |
| 264 | + | ||
| 265 | + | ||
| 266 | +def _check_grouped_projections(statement: exp.Expression) -> list[SecurityViolation]: | ||
| 267 | + """Reject a selected column that GROUP BY leaves neither grouped nor aggregated.""" | ||
| 268 | + violations = [] | ||
| 269 | + for select in statement.find_all(exp.Select): | ||
| 270 | + group = select.args.get("group") | ||
| 271 | + if not isinstance(group, exp.Group): | ||
| 272 | + continue | ||
| 273 | + grouped = _grouped_column_names(select, group) | ||
| 274 | + missing = [] | ||
| 275 | + seen = set() | ||
| 276 | + for projection in select.expressions: | ||
| 277 | + for column in projection.find_all(exp.Column): | ||
| 278 | + name = column.name.casefold() | ||
| 279 | + if ( | ||
| 280 | + column.find_ancestor(exp.Select) is not select | ||
| 281 | + or _column_is_aggregated(column, select) | ||
| 282 | + or name in grouped | ||
| 283 | + or name in seen | ||
| 284 | + ): | ||
| 285 | + continue | ||
| 286 | + seen.add(name) | ||
| 287 | + missing.append(column.name) | ||
| 288 | + if missing: | ||
| 289 | + rendered = ", ".join(f"`{name}`" for name in missing) | ||
| 290 | + violations.append( | ||
| 291 | + SecurityViolation( | ||
| 292 | + "SYNTAX-001", | ||
| 293 | + ( | ||
| 294 | + f"Selected column {rendered} is not in GROUP BY and is not aggregated, " | ||
| 295 | + "so the query cannot execute. Wrap a metric in SUM(), or add a dimension to GROUP BY." | ||
| 296 | + ), | ||
| 297 | + ) | ||
| 298 | + ) | ||
| 299 | + return violations | ||
| 300 | + | ||
| 301 | + | ||
| 302 | +def _grouped_column_names(select: exp.Select, group: exp.Group) -> set[str]: | ||
| 303 | + names = set() | ||
| 304 | + for expression in group.expressions: | ||
| 305 | + for column in expression.find_all(exp.Column): | ||
| 306 | + if column.find_ancestor(exp.Select) is select: | ||
| 307 | + names.add(column.name.casefold()) | ||
| 308 | + return names | ||
| 309 | + | ||
| 310 | + | ||
| 311 | +def _column_is_aggregated(node: exp.Expression, select: exp.Select) -> bool: | ||
| 312 | + current = node.parent | ||
| 313 | + while current is not None and current is not select: | ||
| 314 | + if isinstance(current, exp.Select): | ||
| 315 | + return False | ||
| 316 | + if isinstance(current, exp.AggFunc): | ||
| 317 | + return True | ||
| 318 | + if isinstance(current, exp.Filter) and isinstance(current.this, exp.AggFunc): | ||
| 319 | + return True | ||
| 320 | + current = current.parent | ||
| 321 | + return False | ||
| 264 | 322 | ||
| 265 | 323 | ||
| 266 | def check_resource_usage(statement: exp.Expression) -> list[SecurityViolation]: | 324 | def check_resource_usage(statement: exp.Expression) -> list[SecurityViolation]: |
| @@ -584,11 +642,34 @@ def _returns_unfiltered_rows(statement: exp.Expression) -> bool: | |||
| 584 | ) | 642 | ) |
| 585 | ): | 643 | ): |
| 586 | return False | 644 | return False |
| 645 | + if isinstance(statement, exp.Select) and _is_grouped_aggregate(statement): | ||
| 646 | + return False | ||
| 587 | if isinstance(statement, exp.Select): | 647 | if isinstance(statement, exp.Select): |
| 588 | return not all(isinstance(expression.unnest(), exp.Exists) for expression in statement.expressions) | 648 | return not all(isinstance(expression.unnest(), exp.Exists) for expression in statement.expressions) |
| 589 | return True | 649 | return True |
| 590 | 650 | ||
| 591 | 651 | ||
| 652 | +def _is_grouped_aggregate(statement: exp.Select) -> bool: | ||
| 653 | + """A GROUP BY aggregate collapses rows, so it is not an unfiltered row dump.""" | ||
| 654 | + group = statement.args.get("group") | ||
| 655 | + if not isinstance(group, exp.Group) or statement.find(exp.Window) or not statement.find(exp.AggFunc): | ||
| 656 | + return False | ||
| 657 | + grouped = _grouped_column_names(statement, group) | ||
| 658 | + saw_aggregate = False | ||
| 659 | + for projection in statement.expressions: | ||
| 660 | + if ( | ||
| 661 | + projection.find(exp.AggFunc) is not None | ||
| 662 | + and projection.find(exp.AggFunc).find_ancestor(exp.Select) is statement | ||
| 663 | + ): | ||
| 664 | + saw_aggregate = True | ||
| 665 | + for column in projection.find_all(exp.Column): | ||
| 666 | + if column.find_ancestor(exp.Select) is not statement or _column_is_aggregated(column, statement): | ||
| 667 | + continue | ||
| 668 | + if column.name.casefold() not in grouped: | ||
| 669 | + return False | ||
| 670 | + return saw_aggregate | ||
| 671 | + | ||
| 672 | + | ||
| 592 | def _union_returns_unfiltered_rows(statement: exp.Union) -> bool: | 673 | def _union_returns_unfiltered_rows(statement: exp.Union) -> bool: |
| 593 | if statement.args.get("limit") is not None: | 674 | if statement.args.get("limit") is not None: |
| 594 | return False | 675 | return False |
| @@ -39,6 +39,11 @@ _DIMENSION_CONFIG_FILES = { | |||
| 39 | _Strategy = Literal["prompt", "skeleton", "icl", "dc"] | 39 | _Strategy = Literal["prompt", "skeleton", "icl", "dc"] |
| 40 | 40 | ||
| 41 | 41 | ||
| 42 | +def normalize_sql(sql: str) -> str: | ||
| 43 | + """Collapse whitespace and trailing semicolons for SQL equality checks.""" | ||
| 44 | + return re.sub(r"\s+", " ", (sql or "").strip()).strip(" ;").casefold() | ||
| 45 | + | ||
| 46 | + | ||
| 42 | def sql_sha256(sql: str) -> str: | 47 | def sql_sha256(sql: str) -> str: |
| 43 | """Return a stable SHA-256 fingerprint for normalized SQL.""" | 48 | """Return a stable SHA-256 fingerprint for normalized SQL.""" |
| 44 | normalized = re.sub(r"\s+", " ", (sql or "").strip()) | 49 | normalized = re.sub(r"\s+", " ", (sql or "").strip()) |
| @@ -325,14 +330,28 @@ async def _process_dimension_candidate( | |||
| 325 | return rewritten, prompt, strategy, dimensions, False | 330 | return rewritten, prompt, strategy, dimensions, False |
| 326 | 331 | ||
| 327 | 332 | ||
| 333 | +def _dimension_rule_line(name: str, mapping: dict[str, str]) -> str: | ||
| 334 | + table = mapping["dimension_table"] | ||
| 335 | + key = mapping["key_column"] | ||
| 336 | + value = mapping["value_column"] | ||
| 337 | + return ( | ||
| 338 | + f"- When `{name}` is projected, use `{table}.{value}` through " | ||
| 339 | + f"`INNER JOIN {table} ON <fact>.{name} = {table}.{key}`. " | ||
| 340 | + "This is a required display-value lookup, not extra business logic; " | ||
| 341 | + "WHERE/HAVING predicates remain on the fact key." | ||
| 342 | + ) | ||
| 343 | + | ||
| 344 | + | ||
| 328 | def _add_dimension_context( | 345 | def _add_dimension_context( |
| 329 | state: NL2SQLState, | 346 | state: NL2SQLState, |
| 330 | dimensions: list[str], | 347 | dimensions: list[str], |
| 331 | mappings: dict[str, dict[str, str]], | 348 | mappings: dict[str, dict[str, str]], |
| 332 | ) -> str: | 349 | ) -> str: |
| 333 | fact_table = next(iter(state["schema"]), "") | 350 | fact_table = next(iter(state["schema"]), "") |
| 334 | - dimension_tables = {} | 351 | + schema_str = state["schema_str"] or "" |
| 335 | - rule_lines = ["## Required Dimension Value Mappings"] | 352 | + sql_rules = state["sql_rules"] or "" |
| 353 | + new_tables: dict[str, dict[str, Any]] = {} | ||
| 354 | + new_rule_lines: list[str] = [] | ||
| 336 | for name in dimensions: | 355 | for name in dimensions: |
| 337 | mapping = mappings[name] | 356 | mapping = mappings[name] |
| 338 | table = mapping["dimension_table"] | 357 | table = mapping["dimension_table"] |
| @@ -344,22 +363,33 @@ def _add_dimension_context( | |||
| 344 | ) | 363 | ) |
| 345 | for column in (key, value): | 364 | for column in (key, value): |
| 346 | table_meta["columns"].setdefault(column, {"description": "", "value_type": ""}) | 365 | table_meta["columns"].setdefault(column, {"description": "", "value_type": ""}) |
| 347 | - dimension_tables[table] = table_meta | ||
| 348 | if fact_table: | 366 | if fact_table: |
| 349 | join = (f"{fact_table}.{name}", f"{table}.{key}") | 367 | join = (f"{fact_table}.{name}", f"{table}.{key}") |
| 350 | if join not in state["joins"]: | 368 | if join not in state["joins"]: |
| 351 | state["joins"].append(join) | 369 | state["joins"].append(join) |
| 352 | - rule_lines.append( | 370 | + if f"CREATE TABLE `{table}`" not in schema_str: |
| 353 | - f"- When `{name}` is projected, use `{table}.{value}` through " | 371 | + new_tables[table] = table_meta |
| 354 | - f"`INNER JOIN {table} ON <fact>.{name} = {table}.{key}`. " | 372 | + rule_line = _dimension_rule_line(name, mapping) |
| 355 | - "This is a required display-value lookup, not extra business logic; " | 373 | + if rule_line not in sql_rules: |
| 356 | - "WHERE/HAVING predicates remain on the fact key." | 374 | + new_rule_lines.append(rule_line) |
| 375 | + parts: list[str] = [] | ||
| 376 | + if new_tables: | ||
| 377 | + schema_ddl = schema_to_ddl(new_tables) | ||
| 378 | + schema_block = ( | ||
| 379 | + schema_ddl if "## Dimension Lookup Schema" in schema_str else f"## Dimension Lookup Schema\n{schema_ddl}" | ||
| 357 | ) | 380 | ) |
| 358 | - schema_context = "## Dimension Lookup Schema\n" + schema_to_ddl(dimension_tables) | 381 | + state["schema_str"] = f"{schema_str}\n\n{schema_block}".strip() |
| 359 | - rules_context = "\n".join(rule_lines) | 382 | + parts.append(schema_block) |
| 360 | - state["schema_str"] = f"{state['schema_str']}\n\n{schema_context}".strip() | 383 | + if new_rule_lines: |
| 361 | - state["sql_rules"] = f"{state['sql_rules']}\n\n{rules_context}".strip() | 384 | + rules_body = "\n".join(new_rule_lines) |
| 362 | - return f"{schema_context}\n\n{rules_context}" | 385 | + rules_block = ( |
| 386 | + rules_body | ||
| 387 | + if "## Required Dimension Value Mappings" in sql_rules | ||
| 388 | + else f"## Required Dimension Value Mappings\n{rules_body}" | ||
| 389 | + ) | ||
| 390 | + state["sql_rules"] = f"{sql_rules}\n\n{rules_block}".strip() | ||
| 391 | + parts.append(rules_block) | ||
| 392 | + return "\n\n".join(parts) | ||
| 363 | 393 | ||
| 364 | 394 | ||
| 365 | async def process_dimension_joins( | 395 | async def process_dimension_joins( |
| @@ -64,6 +64,7 @@ class NL2SQLState(BaseState): | |||
| 64 | # reflector | 64 | # reflector |
| 65 | ref_retries: int | 65 | ref_retries: int |
| 66 | proceed: bool | 66 | proceed: bool |
| 67 | + review_history: list[dict[str, Any]] | ||
| 67 | 68 | ||
| 68 | # executor | 69 | # executor |
| 69 | execution_results: list[Result] | 70 | execution_results: list[Result] |
| @@ -114,6 +115,7 @@ def get_default_state(question: str, **override) -> NL2SQLState: | |||
| 114 | "security_sql_approved": False, | 115 | "security_sql_approved": False, |
| 115 | "ref_retries": DEFAULT_NL2SQL_REF_RETRIES, | 116 | "ref_retries": DEFAULT_NL2SQL_REF_RETRIES, |
| 116 | "proceed": True, | 117 | "proceed": True, |
| 118 | + "review_history": [], | ||
| 117 | "execution_results": [], | 119 | "execution_results": [], |
| 118 | "sel_retries": DEFAULT_NL2SQL_SEL_RETRIES, | 120 | "sel_retries": DEFAULT_NL2SQL_SEL_RETRIES, |
| 119 | "stream_message": "", | 121 | "stream_message": "", |
| @@ -13,18 +13,19 @@ | |||
| 13 | import json | 13 | import json |
| 14 | import os | 14 | import os |
| 15 | from collections.abc import AsyncGenerator | 15 | from collections.abc import AsyncGenerator |
| 16 | -from typing import Any | 16 | +from typing import Annotated, Any, Literal |
| 17 | 17 | ||
| 18 | -from fastapi import Body, Depends, FastAPI | 18 | +from fastapi import Depends, FastAPI, Request |
| 19 | +from fastapi.exceptions import RequestValidationError | ||
| 19 | from fastapi.responses import JSONResponse, StreamingResponse | 20 | from fastapi.responses import JSONResponse, StreamingResponse |
| 20 | -from pydantic import BaseModel, ConfigDict, Field | 21 | +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError |
| 21 | 22 | ||
| 22 | from dataagent.interface.rest_api.middleware import SecurityLimitsMiddleware, load_rest_api_limits | 23 | from dataagent.interface.rest_api.middleware import SecurityLimitsMiddleware, load_rest_api_limits |
| 23 | from dataagent.interface.rest_api.service import DataAgentService | 24 | from dataagent.interface.rest_api.service import DataAgentService |
| 24 | 25 | ||
| 25 | 26 | ||
| 26 | class DataAgentQueryRequest(BaseModel): | 27 | class DataAgentQueryRequest(BaseModel): |
| 27 | - """DataAgent query request.""" | 28 | + """Original /api/agent/query body. Callers of this path keep this contract.""" |
| 28 | 29 | ||
| 29 | model_config = ConfigDict(extra="forbid") | 30 | model_config = ConfigDict(extra="forbid") |
| 30 | 31 | ||
| @@ -32,6 +33,30 @@ class DataAgentQueryRequest(BaseModel): | |||
| 32 | stream: bool = False | 33 | stream: bool = False |
| 33 | 34 | ||
| 34 | 35 | ||
| 36 | +class QueryContent(BaseModel): | ||
| 37 | + """Body of the query operation. stream belongs here, not on other types.""" | ||
| 38 | + | ||
| 39 | + model_config = ConfigDict(extra="forbid") | ||
| 40 | + | ||
| 41 | + query: str = Field(min_length=1) | ||
| 42 | + stream: bool = False | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class QueryRequest(BaseModel): | ||
| 46 | + """One northbound operation. type selects the operation; query is implemented first.""" | ||
| 47 | + | ||
| 48 | + model_config = ConfigDict(extra="forbid") | ||
| 49 | + | ||
| 50 | + type: Literal["query"] = Field(description="Operation type. query is one operation; more can be added later.") | ||
| 51 | + content: QueryContent | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +# Discriminated by `type`. First wave registers query only. | ||
| 55 | +# Later operations add another model; they will not inherit query/stream. | ||
| 56 | +DataAgentRequest = Annotated[QueryRequest, Field(discriminator="type")] | ||
| 57 | +_DATA_AGENT_REQUEST_ADAPTER: TypeAdapter[QueryRequest] = TypeAdapter(DataAgentRequest) | ||
| 58 | + | ||
| 59 | + | ||
| 35 | _data_agent_service: DataAgentService | None = None | 60 | _data_agent_service: DataAgentService | None = None |
| 36 | _CONFIG_ENV_NAME = "DATAAGENT_REST_CONFIG" | 61 | _CONFIG_ENV_NAME = "DATAAGENT_REST_CONFIG" |
| 37 | 62 | ||
| @@ -43,6 +68,34 @@ def get_data_agent_service() -> DataAgentService: | |||
| 43 | return _data_agent_service | 68 | return _data_agent_service |
| 44 | 69 | ||
| 45 | 70 | ||
| 71 | +async def get_data_agent_request(http_request: Request) -> QueryRequest: | ||
| 72 | + """Parse a type-discriminated body. Other operations are not registered yet.""" | ||
| 73 | + try: | ||
| 74 | + payload = await http_request.json() | ||
| 75 | + except Exception as exc: | ||
| 76 | + raise RequestValidationError( | ||
| 77 | + [ | ||
| 78 | + { | ||
| 79 | + "type": "json_invalid", | ||
| 80 | + "loc": ("body",), | ||
| 81 | + "msg": "JSON decode error", | ||
| 82 | + "input": {}, | ||
| 83 | + "ctx": {"error": str(exc)}, | ||
| 84 | + } | ||
| 85 | + ] | ||
| 86 | + ) from exc | ||
| 87 | + try: | ||
| 88 | + return _DATA_AGENT_REQUEST_ADAPTER.validate_python(payload) | ||
| 89 | + except ValidationError as exc: | ||
| 90 | + errors = [] | ||
| 91 | + for err in exc.errors(): | ||
| 92 | + loc = err.get("loc", ()) | ||
| 93 | + if not loc or loc[0] != "body": | ||
| 94 | + err = {**err, "loc": ("body", *loc)} | ||
| 95 | + errors.append(err) | ||
| 96 | + raise RequestValidationError(errors, body=payload) from exc | ||
| 97 | + | ||
| 98 | + | ||
| 46 | def agent_error_payload(result: Any) -> dict[str, Any] | None: | 99 | def agent_error_payload(result: Any) -> dict[str, Any] | None: |
| 47 | """Return an agent error payload when result carries one.""" | 100 | """Return an agent error payload when result carries one.""" |
| 48 | if not isinstance(result, dict): | 101 | if not isinstance(result, dict): |
| @@ -108,17 +161,33 @@ async def health_check(): | |||
| 108 | return {"status": "ok"} | 161 | return {"status": "ok"} |
| 109 | 162 | ||
| 110 | 163 | ||
| 111 | -@app.post("/api/agent/query") | 164 | +async def _dispatch_query(query: str, stream: bool, service: DataAgentService): |
| 112 | -async def query_agent( | 165 | + """Run the query operation. Output shape is unchanged.""" |
| 113 | - request: DataAgentQueryRequest = Body(...), | 166 | + if stream: |
| 114 | - service: DataAgentService = Depends(get_data_agent_service), | 167 | + return StreamingResponse(stream_agent_events(query, service), media_type="text/event-stream") |
| 115 | -): | ||
| 116 | - """Run one DataAgent query.""" | ||
| 117 | - if request.stream: | ||
| 118 | - return StreamingResponse(stream_agent_events(request.query, service), media_type="text/event-stream") | ||
| 119 | 168 | ||
| 120 | - result = await service.query(request.query) | 169 | + result = await service.query(query) |
| 121 | payload = agent_error_payload(result) | 170 | payload = agent_error_payload(result) |
| 122 | if payload is not None: | 171 | if payload is not None: |
| 123 | return JSONResponse(status_code=int(payload.get("http_status", 500)), content=result) | 172 | return JSONResponse(status_code=int(payload.get("http_status", 500)), content=result) |
| 124 | return result | 173 | return result |
| 174 | + | ||
| 175 | + | ||
| 176 | +@app.post("/api/agent/query") | ||
| 177 | +async def query_agent( | ||
| 178 | + request: DataAgentQueryRequest, | ||
| 179 | + service: DataAgentService = Depends(get_data_agent_service), | ||
| 180 | +): | ||
| 181 | + """Original query path. Body stays {query, stream}.""" | ||
| 182 | + return await _dispatch_query(request.query, request.stream, service) | ||
| 183 | + | ||
| 184 | + | ||
| 185 | +@app.post("/api/agent/operation") | ||
| 186 | +async def agent_operation( | ||
| 187 | + request: QueryRequest = Depends(get_data_agent_request), | ||
| 188 | + service: DataAgentService = Depends(get_data_agent_service), | ||
| 189 | +): | ||
| 190 | + """New operation path. First wave only implements type=query.""" | ||
| 191 | + if isinstance(request, QueryRequest): | ||
| 192 | + return await _dispatch_query(request.content.query, request.content.stream, service) | ||
| 193 | + raise AssertionError(f"unsupported type: {getattr(request, 'type', request)}") | ||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# REST 操作查询(!429) | ||
| 2 | + | ||
| 3 | +`POST /api/agent/operation`,默认地址 `http://127.0.0.1:8010`。 | ||
| 4 | + | ||
| 5 | +原来的 `POST /api/agent/query` **保留**,请求体仍是原来的 `{query, stream}`,不要改成 `type` + `content`。新结构只给 `/operation`。 | ||
| 6 | + | ||
| 7 | +兼容调用: | ||
| 8 | + | ||
| 9 | +```bash | ||
| 10 | +curl -sS -X POST "http://127.0.0.1:8010/api/agent/query" \ | ||
| 11 | + -H "Content-Type: application/json" \ | ||
| 12 | + -d '{ | ||
| 13 | + "query": "上个月销量最高的产品是什么?", | ||
| 14 | + "stream": false | ||
| 15 | + }' | ||
| 16 | +``` | ||
| 17 | + | ||
| 18 | +`type` 是操作类型(operation)。`query` 只是操作之一;现在只实现 query,其它 type 会 422。后续可加 `update` / `view` 等,字段会不同,不要再包第三层。 | ||
| 19 | + | ||
| 20 | +## 请求体(type=query) | ||
| 21 | + | ||
| 22 | +| 字段 | 类型 | 说明 | | ||
| 23 | +| --- | --- | --- | | ||
| 24 | +| `type` | 字符串 | 操作类型。取值示例:`query`(当前已实现的一种) | | ||
| 25 | +| `content` | 对象 | 该操作的内容。query 时里面只有 `query`、`stream` | | ||
| 26 | +| `content.query` | 字符串 | 提问文本,必填,长度至少 1 | | ||
| 27 | +| `content.stream` | 布尔 | 仅 query 的 content 里有。`false` 一次返回 JSON;`true` 用 SSE | | ||
| 28 | + | ||
| 29 | +```json | ||
| 30 | +{ | ||
| 31 | + "type": "query", | ||
| 32 | + "content": { | ||
| 33 | + "query": "上个月销量最高的产品是什么?", | ||
| 34 | + "stream": false | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## 同步 | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +curl -sS -X POST "http://127.0.0.1:8010/api/agent/operation" \ | ||
| 43 | + -H "Content-Type: application/json" \ | ||
| 44 | + -d '{ | ||
| 45 | + "type": "query", | ||
| 46 | + "content": { | ||
| 47 | + "query": "上个月销量最高的产品是什么?", | ||
| 48 | + "stream": false | ||
| 49 | + } | ||
| 50 | + }' | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +## 流式 | ||
| 54 | + | ||
| 55 | +```bash | ||
| 56 | +curl -sS -N -X POST "http://127.0.0.1:8010/api/agent/operation" \ | ||
| 57 | + -H "Content-Type: application/json" \ | ||
| 58 | + -H "Accept: text/event-stream" \ | ||
| 59 | + -d '{ | ||
| 60 | + "type": "query", | ||
| 61 | + "content": { | ||
| 62 | + "query": "上个月销量最高的产品是什么?", | ||
| 63 | + "stream": true | ||
| 64 | + } | ||
| 65 | + }' | ||
| 66 | +``` | ||
| 67 | + | ||
| 68 | +## 同步返回 | ||
| 69 | + | ||
| 70 | +外层始终是 `{"result": ...}`。 | ||
| 71 | + | ||
| 72 | +```json | ||
| 73 | +{ | ||
| 74 | + "result": { | ||
| 75 | + "success": true, | ||
| 76 | + "message": "SQL generated.", | ||
| 77 | + "sql": "SELECT 1" | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +`result.success` 为 `false` 时,HTTP 状态取 `result.http_status`(缺省 500)。 | ||
| 83 | + | ||
| 84 | +## SSE | ||
| 85 | + | ||
| 86 | +先推若干条 `event: message` 进度,最后一条是结果: | ||
| 87 | + | ||
| 88 | +```text | ||
| 89 | +event: result | ||
| 90 | +data: {"result": {"success": true, "message": "SQL generated.", "sql": "SELECT 1"}} | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +`result` 的 `data` 与同步整包 JSON 相同。未知 `type` 会 422,不会当提问执行。 | ||
| @@ -134,7 +134,7 @@ async def test_business_twin_aprocess_appends_administrative_rules(monkeypatch: | |||
| 134 | monkeypatch.setattr(business_twin_perceptor_module, "schema_to_ddl", lambda *_args: "DDL") | 134 | monkeypatch.setattr(business_twin_perceptor_module, "schema_to_ddl", lambda *_args: "DDL") |
| 135 | 135 | ||
| 136 | async def fake_schema_linking(_question: str): | 136 | async def fake_schema_linking(_question: str): |
| 137 | - return {}, [], {} | 137 | + return {}, [], {}, False |
| 138 | 138 | ||
| 139 | monkeypatch.setattr(node, "_business_twin_schema_linking", fake_schema_linking) | 139 | monkeypatch.setattr(node, "_business_twin_schema_linking", fake_schema_linking) |
| 140 | state = {"question": "查询深圳市南山区流量"} | 140 | state = {"question": "查询深圳市南山区流量"} |
| @@ -19,20 +19,20 @@ def test_business_id_catalog_is_a_packaged_json_resource() -> None: | |||
| 19 | payload = json.loads(catalog_path.read_text(encoding="utf-8")) | 19 | payload = json.loads(catalog_path.read_text(encoding="utf-8")) |
| 20 | 20 | ||
| 21 | assert payload["version"] == 1 | 21 | assert payload["version"] == 1 |
| 22 | - assert len(payload["business_schemas"]) == 19 | 22 | + assert len(payload["business_schemas"]) == 21 |
| 23 | assert payload["business_schemas"]["dw1745159007"]["dimensions"] == [ | 23 | assert payload["business_schemas"]["dw1745159007"]["dimensions"] == [ |
| 24 | - "app_id", | ||
| 25 | - "cell_id", | ||
| 26 | "city", | 24 | "city", |
| 27 | "county", | 25 | "county", |
| 28 | - "custom_group", | ||
| 29 | - "gnb", | ||
| 30 | - "guarantee_group", | ||
| 31 | - "sub_app_id", | ||
| 32 | "tai", | 26 | "tai", |
| 27 | + "gnb", | ||
| 28 | + "cell_id", | ||
| 29 | + "guarantee_group", | ||
| 30 | + "app_id", | ||
| 31 | + "sub_app_id", | ||
| 32 | + "custom_group", | ||
| 33 | + "15min_granularity", | ||
| 33 | "1h_granularity", | 34 | "1h_granularity", |
| 34 | "1d_granularity", | 35 | "1d_granularity", |
| 35 | - "15min_granularity", | ||
| 36 | ] | 36 | ] |
| 37 | 37 | ||
| 38 | 38 | ||
| @@ -70,12 +70,47 @@ def test_known_extra_metric_is_classified_without_dimension_error() -> None: | |||
| 70 | ["assurance_abnormal_release_times_of_nwdaf"], | 70 | ["assurance_abnormal_release_times_of_nwdaf"], |
| 71 | "dw1745159003", | 71 | "dw1745159003", |
| 72 | ), | 72 | ), |
| 73 | - ("查询高铁用户数", ["crh_users"], "dw1745159021"), | 73 | + ( |
| 74 | + "查询高铁用户接入高铁专网次数", | ||
| 75 | + ["de_acc_num_of_rail_usr_of_nwdaf", "ne_name"], | ||
| 76 | + "dw1745159003", | ||
| 77 | + ), | ||
| 78 | + ("查询高铁用户数", ["crh_users"], "dw1745159030"), | ||
| 79 | + ("查询高铁分群用户数", ["crh_users", "crh_group"], "dw1745159030"), | ||
| 74 | ("查询高铁乘坐次数", ["crh_ride_times", "gpsi"], "dw1745159012"), | 80 | ("查询高铁乘坐次数", ["crh_ride_times", "gpsi"], "dw1745159012"), |
| 75 | - ("查询高铁分群用户数", ["crh_users", "crh_group"], "dw1745159010"), | 81 | + ( |
| 82 | + "查询高铁首次N23会话创建上报次数", | ||
| 83 | + ["crh_trigger_first_n23_create_times", "gnb"], | ||
| 84 | + "dw1745159031", | ||
| 85 | + ), | ||
| 86 | + ( | ||
| 87 | + "查询高铁线路段下行流量", | ||
| 88 | + ["downlink_traffic", "crh_section_id"], | ||
| 89 | + "dw1745159032", | ||
| 90 | + ), | ||
| 91 | + ( | ||
| 92 | + "查询高铁线路业务使用次数", | ||
| 93 | + ["service_times", "crh_railway_id"], | ||
| 94 | + "dw1745159033", | ||
| 95 | + ), | ||
| 96 | + ( | ||
| 97 | + "查询高铁线路保障用户数", | ||
| 98 | + ["assurance_users", "crh_railway_id"], | ||
| 99 | + "dw1745159034", | ||
| 100 | + ), | ||
| 76 | ("查询高铁下行流量", ["downlink_traffic"], "dw1745159007"), | 101 | ("查询高铁下行流量", ["downlink_traffic"], "dw1745159007"), |
| 77 | ("查询上行PRB使用量", ["cell_prb_ul_usage"], "dw1745159004"), | 102 | ("查询上行PRB使用量", ["cell_prb_ul_usage"], "dw1745159004"), |
| 78 | ("查询保障次数", ["assurance_times"], "dw1745159008"), | 103 | ("查询保障次数", ["assurance_times"], "dw1745159008"), |
| 104 | + ( | ||
| 105 | + "查询网元维度保障用户数", | ||
| 106 | + ["assurance_users", "ne_name"], | ||
| 107 | + "dw1745159028", | ||
| 108 | + ), | ||
| 109 | + ( | ||
| 110 | + "查询小区维度保障用户数", | ||
| 111 | + ["assurance_users", "cell_id"], | ||
| 112 | + "dw1745159037", | ||
| 113 | + ), | ||
| 79 | ( | 114 | ( |
| 80 | "查询各终端品牌保障次数", | 115 | "查询各终端品牌保障次数", |
| 81 | ["assurance_times", "term_brand"], | 116 | ["assurance_times", "term_brand"], |
| @@ -88,18 +123,18 @@ def test_known_extra_metric_is_classified_without_dimension_error() -> None: | |||
| 88 | ), | 123 | ), |
| 89 | ( | 124 | ( |
| 90 | "查询保障与非保障用户MOS", | 125 | "查询保障与非保障用户MOS", |
| 91 | - ["avg_qoe", "mos_times", "mos4_qds"], | 126 | + ["avg_qoe", "mos_times", "guarantee_group"], |
| 92 | - "dw1745159020", | 127 | + "dw1745159007", |
| 93 | ), | 128 | ), |
| 94 | ( | 129 | ( |
| 95 | "查询各终端品牌保障与非保障用户MOS", | 130 | "查询各终端品牌保障与非保障用户MOS", |
| 96 | - ["avg_qoe", "mos_times", "mos4_qds", "term_brand"], | 131 | + ["avg_qoe", "mos_times", "guarantee_group", "term_brand"], |
| 97 | - "dw1745159018", | 132 | + "dw1745159014", |
| 98 | ), | 133 | ), |
| 99 | ( | 134 | ( |
| 100 | "查询各5QI分群保障与非保障用户MOS", | 135 | "查询各5QI分群保障与非保障用户MOS", |
| 101 | - ["avg_qoe", "mos_times", "mos4_qds", "default5qi_group"], | 136 | + ["avg_qoe", "mos_times", "guarantee_group", "default5qi_group"], |
| 102 | - "dw1745159019", | 137 | + "dw1745159015", |
| 103 | ), | 138 | ), |
| 104 | ("普通查询", [], "dw1745159007"), | 139 | ("普通查询", [], "dw1745159007"), |
| 105 | ], | 140 | ], |
| @@ -111,9 +146,10 @@ def test_column_only_routes(question: str, columns: list[str], expected: str) -> | |||
| 111 | @pytest.mark.parametrize( | 146 | @pytest.mark.parametrize( |
| 112 | ("columns", "expected"), | 147 | ("columns", "expected"), |
| 113 | [ | 148 | [ |
| 114 | - (["mos_sec3_users"], "dw1745159009"), | 149 | + (["mos_sec3_times"], "dw1745159007"), |
| 115 | - (["mos_sec1_users", "term_brand"], "dw1745159018"), | 150 | + (["mos_sec1_times", "term_brand"], "dw1745159014"), |
| 116 | - (["mos_sec2_users", "default5qi_group"], "dw1745159019"), | 151 | + (["mos_sec2_times", "default5qi_group"], "dw1745159015"), |
| 152 | + (["most_resolution1080p_times", "ne_name"], "dw1745159027"), | ||
| 117 | ], | 153 | ], |
| 118 | ) | 154 | ) |
| 119 | def test_normalizes_physical_distribution_metrics(columns: list[str], expected: str) -> None: | 155 | def test_normalizes_physical_distribution_metrics(columns: list[str], expected: str) -> None: |
| @@ -70,7 +70,8 @@ async def test_mentioned_table_is_pinned_without_llm( | |||
| 70 | monkeypatch.setattr(node, "execute_with_llm_json", fail_execute) | 70 | monkeypatch.setattr(node, "execute_with_llm_json", fail_execute) |
| 71 | monkeypatch.setattr(node, "_full_table_catalog", lambda: _catalog()) | 71 | monkeypatch.setattr(node, "_full_table_catalog", lambda: _catalog()) |
| 72 | 72 | ||
| 73 | - assert await node._select_table_by_business_family(question) == expected | 73 | + # Pinning names a table, not an output granularity, so no granularity is claimed. |
| 74 | + assert await node._select_table_by_business_family(question) == (expected, False) | ||
| 74 | 75 | ||
| 75 | 76 | ||
| 76 | @pytest.mark.asyncio | 77 | @pytest.mark.asyncio |
| @@ -103,18 +104,19 @@ async def test_unmentioned_question_excludes_explicit_only_table( | |||
| 103 | async def fake_business_id(question: str) -> str: | 104 | async def fake_business_id(question: str) -> str: |
| 104 | return "dw1745159004" | 105 | return "dw1745159004" |
| 105 | 106 | ||
| 106 | - async def fake_select_family(question: str, families: list[dict[str, Any]]) -> dict[str, str]: | 107 | + async def fake_select_family(question: str, families: list[dict[str, Any]]) -> dict[str, Any]: |
| 107 | seen_families.append(families) | 108 | seen_families.append(families) |
| 108 | - return {"family_name": OTHER_FAMILY, "granularity": "1h"} | 109 | + return {"family_name": OTHER_FAMILY, "granularity": "1h", "explicit_granularity": True} |
| 109 | 110 | ||
| 110 | monkeypatch.setattr(node, "_select_business_id", fake_business_id) | 111 | monkeypatch.setattr(node, "_select_business_id", fake_business_id) |
| 111 | monkeypatch.setattr(node, "_full_table_catalog", lambda: _catalog()) | 112 | monkeypatch.setattr(node, "_full_table_catalog", lambda: _catalog()) |
| 112 | monkeypatch.setattr(node, "_select_table_family", fake_select_family) | 113 | monkeypatch.setattr(node, "_select_table_family", fake_select_family) |
| 113 | 114 | ||
| 114 | question = "查询最近一周按全省(不区分城市)统计的无线小区下行PRB可用数,该指标对应字段为cell_prb_dl_total,单位为个,按1小时粒度展示" | 115 | question = "查询最近一周按全省(不区分城市)统计的无线小区下行PRB可用数,该指标对应字段为cell_prb_dl_total,单位为个,按1小时粒度展示" |
| 115 | - table = await node._select_table_by_business_family(question) | 116 | + table, explicit_granularity = await node._select_table_by_business_family(question) |
| 116 | 117 | ||
| 117 | assert table == OTHER_TABLE | 118 | assert table == OTHER_TABLE |
| 119 | + assert explicit_granularity is True | ||
| 118 | assert len(seen_families) == 1 | 120 | assert len(seen_families) == 1 |
| 119 | family_names = {family["family_name"] for family in seen_families[0]} | 121 | family_names = {family["family_name"] for family in seen_families[0]} |
| 120 | assert EXCLUDED_FAMILY not in family_names | 122 | assert EXCLUDED_FAMILY not in family_names |
| @@ -132,15 +134,15 @@ async def test_plain_question_keeps_normal_flow( | |||
| 132 | called["business_id"] = True | 134 | called["business_id"] = True |
| 133 | return "dw1745159004" | 135 | return "dw1745159004" |
| 134 | 136 | ||
| 135 | - async def fake_select_family(question: str, families: list[dict[str, Any]]) -> dict[str, str]: | 137 | + async def fake_select_family(question: str, families: list[dict[str, Any]]) -> dict[str, Any]: |
| 136 | - return {"family_name": OTHER_FAMILY, "granularity": "1h"} | 138 | + return {"family_name": OTHER_FAMILY, "granularity": "1h", "explicit_granularity": True} |
| 137 | 139 | ||
| 138 | monkeypatch.setattr(node, "_select_business_id", fake_business_id) | 140 | monkeypatch.setattr(node, "_select_business_id", fake_business_id) |
| 139 | monkeypatch.setattr(node, "_full_table_catalog", lambda: _catalog()) | 141 | monkeypatch.setattr(node, "_full_table_catalog", lambda: _catalog()) |
| 140 | monkeypatch.setattr(node, "_select_table_family", fake_select_family) | 142 | monkeypatch.setattr(node, "_select_table_family", fake_select_family) |
| 141 | 143 | ||
| 142 | question = "查询最近一周全省无线小区下行PRB可用数,按1小时粒度展示" | 144 | question = "查询最近一周全省无线小区下行PRB可用数,按1小时粒度展示" |
| 143 | - assert await node._select_table_by_business_family(question) == OTHER_TABLE | 145 | + assert await node._select_table_by_business_family(question) == (OTHER_TABLE, True) |
| 144 | assert called["business_id"] is True | 146 | assert called["business_id"] is True |
| 145 | 147 | ||
| 146 | 148 | ||
| @@ -1,5 +1,6 @@ | |||
| 1 | from __future__ import annotations | 1 | from __future__ import annotations |
| 2 | 2 | ||
| 3 | +import json | ||
| 3 | import re | 4 | import re |
| 4 | from pathlib import Path | 5 | from pathlib import Path |
| 5 | from typing import Any | 6 | from typing import Any |
| @@ -8,6 +9,7 @@ import pytest | |||
| 8 | 9 | ||
| 9 | from dataagent.agents.nl2sql.errors import NL2SQLError | 10 | from dataagent.agents.nl2sql.errors import NL2SQLError |
| 10 | from dataagent.agents.nl2sql.nodes.business_twin_perceptor import BusinessTwinPerceptorNode | 11 | from dataagent.agents.nl2sql.nodes.business_twin_perceptor import BusinessTwinPerceptorNode |
| 12 | +from dataagent.utils.runtime_paths import dataagent_package_path | ||
| 11 | 13 | ||
| 12 | PROMPT_PATH = ( | 14 | PROMPT_PATH = ( |
| 13 | Path(__file__).resolve().parents[4] | 15 | Path(__file__).resolve().parents[4] |
| @@ -19,6 +21,12 @@ PROMPT_PATH = ( | |||
| 19 | / "filter_business_twin_business_id_system.md" | 21 | / "filter_business_twin_business_id_system.md" |
| 20 | ) | 22 | ) |
| 21 | USER_PROMPT_PATH = PROMPT_PATH.with_name("filter_business_twin_business_id_user.md") | 23 | USER_PROMPT_PATH = PROMPT_PATH.with_name("filter_business_twin_business_id_user.md") |
| 24 | +CATALOG_PATH = dataagent_package_path( | ||
| 25 | + "agents", | ||
| 26 | + "nl2sql", | ||
| 27 | + "utils", | ||
| 28 | + "business_twin_business_id_catalog.json", | ||
| 29 | +) | ||
| 22 | 30 | ||
| 23 | 31 | ||
| 24 | class _ConfigManager: | 32 | class _ConfigManager: |
| @@ -29,10 +37,17 @@ class _ConfigManager: | |||
| 29 | def test_production_prompt_embeds_full_catalog_and_requires_bare_array() -> None: | 37 | def test_production_prompt_embeds_full_catalog_and_requires_bare_array() -> None: |
| 30 | text = PROMPT_PATH.read_text(encoding="utf-8") | 38 | text = PROMPT_PATH.read_text(encoding="utf-8") |
| 31 | catalog_names = re.findall(r"(?m)^- ([a-zA-Z0-9_*]+) \|", text) | 39 | catalog_names = re.findall(r"(?m)^- ([a-zA-Z0-9_*]+) \|", text) |
| 40 | + catalog_payload = json.loads(CATALOG_PATH.read_text(encoding="utf-8")) | ||
| 41 | + catalog_fields = { | ||
| 42 | + field | ||
| 43 | + for schema in catalog_payload["business_schemas"].values() | ||
| 44 | + for field in (*schema["metrics"], *schema["dimensions"]) | ||
| 45 | + } | ||
| 32 | 46 | ||
| 33 | assert "{{CATALOG}}" not in text | 47 | assert "{{CATALOG}}" not in text |
| 34 | - assert len(catalog_names) == 104 | 48 | + assert len(catalog_names) == 156 |
| 35 | - assert len(set(catalog_names)) == 104 | 49 | + assert len(set(catalog_names)) == 156 |
| 50 | + assert set(catalog_names) == catalog_fields | ||
| 36 | for granularity_field in ("1h_granularity", "1d_granularity", "15min_granularity"): | 51 | for granularity_field in ("1h_granularity", "1d_granularity", "15min_granularity"): |
| 37 | assert granularity_field in catalog_names | 52 | assert granularity_field in catalog_names |
| 38 | assert not re.findall(r"dw\d+", text) | 53 | assert not re.findall(r"dw\d+", text) |
| @@ -0,0 +1,87 @@ | |||
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); | ||
| 2 | +# you may not use this file except in compliance with the License. | ||
| 3 | +# You may obtain a copy of the License at | ||
| 4 | +# | ||
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 | ||
| 6 | +# | ||
| 7 | +# Unless required by applicable law or agreed to in writing, software | ||
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, | ||
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 10 | +# See the License for the specific language governing permissions and | ||
| 11 | +# limitations under the License. | ||
| 12 | +# ============================================================================ | ||
| 13 | +from typing import Any | ||
| 14 | + | ||
| 15 | +import pytest | ||
| 16 | + | ||
| 17 | +from dataagent.agents.nl2sql.nodes import business_twin_perceptor as business_twin_perceptor_module | ||
| 18 | +from dataagent.agents.nl2sql.nodes.business_twin_perceptor import BusinessTwinPerceptorNode | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class _ConfigManager: | ||
| 22 | + def get(self, key: str, default: Any = None) -> Any: | ||
| 23 | + return default | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _node(monkeypatch: pytest.MonkeyPatch, *, explicit_granularity: bool) -> BusinessTwinPerceptorNode: | ||
| 27 | + node = BusinessTwinPerceptorNode(config_manager=_ConfigManager()) | ||
| 28 | + monkeypatch.setattr(node, "_load_prompt", lambda _name: "existing rule") | ||
| 29 | + monkeypatch.setattr(business_twin_perceptor_module, "schema_to_ddl", lambda *_args: "DDL") | ||
| 30 | + | ||
| 31 | + async def fake_schema_linking(_question: str): | ||
| 32 | + return {}, [], {}, explicit_granularity | ||
| 33 | + | ||
| 34 | + monkeypatch.setattr(node, "_business_twin_schema_linking", fake_schema_linking) | ||
| 35 | + return node | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +@pytest.mark.asyncio | ||
| 39 | +async def test_named_granularity_makes_time_mandatory(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| 40 | + """The selector already tells a named granularity apart, so downstream nodes need not re-read it.""" | ||
| 41 | + node = _node(monkeypatch, explicit_granularity=True) | ||
| 42 | + | ||
| 43 | + result = await node._aprocess({"question": "查询最近一周按全省统计的粒度为1h的MOS分段1次数"}) | ||
| 44 | + | ||
| 45 | + rules = result["sql_rules"] | ||
| 46 | + assert "\n\n## 时间粒度" in rules | ||
| 47 | + assert "`time` 必须出现在 SELECT 和 GROUP BY" in rules | ||
| 48 | + assert "不得把结果压成单行" in rules | ||
| 49 | + assert "任何要求移除 `time` 的意见都应判为无效" in rules | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +@pytest.mark.asyncio | ||
| 53 | +async def test_derived_granularity_leaves_time_optional(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| 54 | + """A granularity the selector derived only picks the table; it must not force a per-bucket output.""" | ||
| 55 | + node = _node(monkeypatch, explicit_granularity=False) | ||
| 56 | + | ||
| 57 | + result = await node._aprocess({"question": "查询最近一周按全省统计的保障失败原因次数"}) | ||
| 58 | + | ||
| 59 | + assert "## 时间粒度" not in result["sql_rules"] | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +@pytest.mark.parametrize( | ||
| 63 | + ("payload", "expected"), | ||
| 64 | + [ | ||
| 65 | + ({"family_name": "fam", "granularity": "1h", "explicit_granularity": True}, True), | ||
| 66 | + ({"family_name": "fam", "granularity": "1h", "explicit_granularity": False}, False), | ||
| 67 | + ({"family_name": "fam", "granularity": "1h"}, False), | ||
| 68 | + ], | ||
| 69 | + ids=["named", "derived", "field-omitted"], | ||
| 70 | +) | ||
| 71 | +@pytest.mark.asyncio | ||
| 72 | +async def test_selector_reports_whether_the_question_named_the_granularity( | ||
| 73 | + monkeypatch: pytest.MonkeyPatch, payload: dict[str, Any], expected: bool | ||
| 74 | +) -> None: | ||
| 75 | + """A missing or non-true value must read as derived rather than forcing `time`.""" | ||
| 76 | + node = BusinessTwinPerceptorNode(config_manager=_ConfigManager()) | ||
| 77 | + | ||
| 78 | + async def fake_llm_json(_context: dict[str, str], action: str = "") -> Any: | ||
| 79 | + return payload | ||
| 80 | + | ||
| 81 | + monkeypatch.setattr(node, "execute_with_llm_json", fake_llm_json) | ||
| 82 | + monkeypatch.setattr(node, "_format_table_family_prompt_context", lambda _families: "") | ||
| 83 | + | ||
| 84 | + selection = await node._select_table_family("question", [{"family_name": "fam"}]) | ||
| 85 | + | ||
| 86 | + assert selection is not None | ||
| 87 | + assert selection["explicit_granularity"] is expected | ||
| @@ -17,7 +17,12 @@ import pytest | |||
| 17 | 17 | ||
| 18 | from dataagent.agents.nl2sql.nodes.generator import GeneratorNode | 18 | from dataagent.agents.nl2sql.nodes.generator import GeneratorNode |
| 19 | from dataagent.agents.nl2sql.security import check_sql | 19 | from dataagent.agents.nl2sql.security import check_sql |
| 20 | -from dataagent.agents.nl2sql.utils.nl2sql_utils import load_dimension_mappings, schema_to_ddl, selected_dimensions | 20 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import ( |
| 21 | + _add_dimension_context, | ||
| 22 | + load_dimension_mappings, | ||
| 23 | + schema_to_ddl, | ||
| 24 | + selected_dimensions, | ||
| 25 | +) | ||
| 21 | from dataagent.agents.nl2sql.workflow.state import get_default_state | 26 | from dataagent.agents.nl2sql.workflow.state import get_default_state |
| 22 | from dataagent.config.config_manager import ConfigManager | 27 | from dataagent.config.config_manager import ConfigManager |
| 23 | from dataagent.core.managers.llm_manager import llm_manager | 28 | from dataagent.core.managers.llm_manager import llm_manager |
| @@ -73,6 +78,8 @@ def test_loads_packaged_scenario_dimension_mapping(scenario: str, dimension: str | |||
| 73 | mappings = load_dimension_mappings(scenario) | 78 | mappings = load_dimension_mappings(scenario) |
| 74 | 79 | ||
| 75 | assert mappings[dimension]["dimension_table"] == table | 80 | assert mappings[dimension]["dimension_table"] == table |
| 81 | + if scenario == "business_twin": | ||
| 82 | + assert "ne_name" not in mappings | ||
| 76 | 83 | ||
| 77 | 84 | ||
| 78 | def test_detects_only_standalone_final_select_dimensions() -> None: | 85 | def test_detects_only_standalone_final_select_dimensions() -> None: |
| @@ -188,3 +195,19 @@ async def test_keeps_original_and_requests_reflection_when_rewrite_fails(rewrite | |||
| 188 | assert candidate.need_ref is True | 195 | assert candidate.need_ref is True |
| 189 | assert "dim_exp_county" in result["schema"] | 196 | assert "dim_exp_county" in result["schema"] |
| 190 | assert "dim_exp_county" in candidate.prompt | 197 | assert "dim_exp_county" in candidate.prompt |
| 198 | + | ||
| 199 | + | ||
| 200 | +def test_add_dimension_context_appends_only_newly_discovered_dimension() -> None: | ||
| 201 | + state = _state() | ||
| 202 | + mappings = load_dimension_mappings("business_twin") | ||
| 203 | + | ||
| 204 | + _add_dimension_context(state, ["county"], mappings) | ||
| 205 | + added = _add_dimension_context(state, ["county", "city"], mappings) | ||
| 206 | + | ||
| 207 | + assert "dim_exp_city" in added | ||
| 208 | + assert "When `city` is projected" in added | ||
| 209 | + assert "When `county` is projected" not in added | ||
| 210 | + assert state["schema_str"].count("CREATE TABLE `dim_exp_county`") == 1 | ||
| 211 | + assert state["schema_str"].count("CREATE TABLE `dim_exp_city`") == 1 | ||
| 212 | + assert state["sql_rules"].count("When `county` is projected") == 1 | ||
| 213 | + assert state["sql_rules"].count("When `city` is projected") == 1 | ||
| @@ -0,0 +1,121 @@ | |||
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); | ||
| 2 | +# you may not use this file except in compliance with the License. | ||
| 3 | +# You may obtain a copy of the License at | ||
| 4 | +# | ||
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 | ||
| 6 | +# | ||
| 7 | +# Unless required by applicable law or agreed to in writing, software | ||
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, | ||
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 10 | +# See the License for the specific language governing permissions and | ||
| 11 | +# limitations under the License. | ||
| 12 | +# ============================================================================ | ||
| 13 | +from types import SimpleNamespace | ||
| 14 | +from unittest.mock import AsyncMock, patch | ||
| 15 | + | ||
| 16 | +import pytest | ||
| 17 | + | ||
| 18 | +from dataagent.agents.nl2sql.nodes.reflector import ReflectorNode | ||
| 19 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import schema_to_ddl | ||
| 20 | +from dataagent.agents.nl2sql.workflow.state import Result, get_default_state | ||
| 21 | +from dataagent.config.config_manager import ConfigManager | ||
| 22 | +from dataagent.core.managers.llm_manager import llm_manager | ||
| 23 | +from dataagent.core.managers.prompt_manager import PromptTemplate | ||
| 24 | + | ||
| 25 | +BARE_SQL = ( | ||
| 26 | + "SELECT time, county, SUM(uplink_traffic) AS uplink_traffic FROM fact_metric " | ||
| 27 | + "WHERE county = 10 GROUP BY time, county" | ||
| 28 | +) | ||
| 29 | +REWRITTEN_SQL = ( | ||
| 30 | + "SELECT f.time, d.county_value, SUM(f.uplink_traffic) AS uplink_traffic FROM fact_metric f " | ||
| 31 | + "INNER JOIN dim_exp_county d ON f.county = d.county_key " | ||
| 32 | + "WHERE f.county = 10 GROUP BY f.time, d.county_value" | ||
| 33 | +) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def _config_manager(scenario: str = "business_twin") -> ConfigManager: | ||
| 37 | + manager = ConfigManager() | ||
| 38 | + manager.settings = { | ||
| 39 | + "DATABASE": { | ||
| 40 | + "dialect": "postgres", | ||
| 41 | + "perceptor_type": scenario, | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + return manager | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def _node() -> ReflectorNode: | ||
| 48 | + return ReflectorNode(config_manager=_config_manager(), threshold=0.9) | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _state() -> dict: | ||
| 52 | + schema = { | ||
| 53 | + "fact_metric": { | ||
| 54 | + "description": "fact", | ||
| 55 | + "columns": { | ||
| 56 | + "time": {"value_type": "bigint"}, | ||
| 57 | + "county": {"value_type": "integer"}, | ||
| 58 | + "uplink_traffic": {"value_type": "numeric"}, | ||
| 59 | + }, | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + state = get_default_state( | ||
| 63 | + "query traffic by county", | ||
| 64 | + schema=schema, | ||
| 65 | + schema_str=schema_to_ddl(schema), | ||
| 66 | + sql_rules="Keep the requested time range.", | ||
| 67 | + ref_retries=1, | ||
| 68 | + ) | ||
| 69 | + state["validation_results"] = [ | ||
| 70 | + Result( | ||
| 71 | + id=0, | ||
| 72 | + sql="SELECT 1", | ||
| 73 | + prompt="original generator prompt", | ||
| 74 | + score=0.1, | ||
| 75 | + need_ref=True, | ||
| 76 | + security_checked=True, | ||
| 77 | + ) | ||
| 78 | + ] | ||
| 79 | + return state | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +@pytest.mark.asyncio | ||
| 83 | +async def test_reflector_dimension_join_loads_generator_prompts_not_reflector() -> None: | ||
| 84 | + node = _node() | ||
| 85 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": BARE_SQL}]) | ||
| 86 | + loaded: list[str] = [] | ||
| 87 | + real_loader = PromptTemplate.from_package_relative | ||
| 88 | + | ||
| 89 | + def tracking_loader(path: str): | ||
| 90 | + loaded.append(path) | ||
| 91 | + return real_loader(path) | ||
| 92 | + | ||
| 93 | + llm = SimpleNamespace(ainvoke=AsyncMock(return_value=SimpleNamespace(content=f"```sql\n{REWRITTEN_SQL}\n```"))) | ||
| 94 | + | ||
| 95 | + with ( | ||
| 96 | + patch.object(PromptTemplate, "from_package_relative", side_effect=tracking_loader), | ||
| 97 | + patch.object(llm_manager, "get_default_llm", return_value=llm), | ||
| 98 | + ): | ||
| 99 | + result = await node._aprocess(_state()) | ||
| 100 | + | ||
| 101 | + assert any("generator/dimension_join_" in path for path in loaded) | ||
| 102 | + assert not any("reflector/dimension_join_" in path for path in loaded) | ||
| 103 | + assert "INNER JOIN dim_exp_county" in result["generation_results"][0].sql | ||
| 104 | + assert llm.ainvoke.await_count == 1 | ||
| 105 | + assert ( | ||
| 106 | + "Keep existing `WHERE` and `HAVING` predicates on the fact key" in llm.ainvoke.await_args.args[0][0]["content"] | ||
| 107 | + ) | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +@pytest.mark.asyncio | ||
| 111 | +async def test_reflector_keeps_reflected_sql_when_dimension_join_fails() -> None: | ||
| 112 | + node = _node() | ||
| 113 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": BARE_SQL}]) | ||
| 114 | + llm = SimpleNamespace(ainvoke=AsyncMock(side_effect=RuntimeError("rewrite unavailable"))) | ||
| 115 | + | ||
| 116 | + with patch.object(llm_manager, "get_default_llm", return_value=llm): | ||
| 117 | + result = await node._aprocess(_state()) | ||
| 118 | + | ||
| 119 | + candidate = result["generation_results"][0] | ||
| 120 | + assert candidate.sql == BARE_SQL | ||
| 121 | + assert candidate.need_ref is True | ||
| @@ -21,7 +21,7 @@ from dataagent.agents.nl2sql.nodes import executor as executor_module | |||
| 21 | from dataagent.agents.nl2sql.nodes import selector as selector_module | 21 | from dataagent.agents.nl2sql.nodes import selector as selector_module |
| 22 | from dataagent.agents.nl2sql.nodes.executor import ExecutorNode | 22 | from dataagent.agents.nl2sql.nodes.executor import ExecutorNode |
| 23 | from dataagent.agents.nl2sql.nodes.selector import SelectorNode | 23 | from dataagent.agents.nl2sql.nodes.selector import SelectorNode |
| 24 | -from dataagent.agents.nl2sql.utils.nl2sql_utils import sql_sha256 | 24 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import normalize_sql, sql_sha256 |
| 25 | from dataagent.agents.nl2sql.workflow.state import Result, get_default_state | 25 | from dataagent.agents.nl2sql.workflow.state import Result, get_default_state |
| 26 | 26 | ||
| 27 | 27 | ||
| @@ -44,6 +44,10 @@ def test_sql_sha256_normalizes_whitespace() -> None: | |||
| 44 | assert sql_sha256(" SELECT secret\nFROM account ") == sql_sha256("SELECT secret FROM account") | 44 | assert sql_sha256(" SELECT secret\nFROM account ") == sql_sha256("SELECT secret FROM account") |
| 45 | 45 | ||
| 46 | 46 | ||
| 47 | +def test_normalize_sql_treats_case_whitespace_and_semicolon_as_equal() -> None: | ||
| 48 | + assert normalize_sql("SELECT time\nFROM t;") == normalize_sql("select time from t") | ||
| 49 | + | ||
| 50 | + | ||
| 47 | @pytest.mark.asyncio | 51 | @pytest.mark.asyncio |
| 48 | async def test_selector_info_logs_only_safe_result_metadata(monkeypatch: pytest.MonkeyPatch) -> None: | 52 | async def test_selector_info_logs_only_safe_result_metadata(monkeypatch: pytest.MonkeyPatch) -> None: |
| 49 | sql_secret = "SELECT private_token FROM customer_secret" | 53 | sql_secret = "SELECT private_token FROM customer_secret" |
| @@ -594,6 +594,25 @@ def test_check_sql_allows_whitelisted_join_types(join_sql: str) -> None: | |||
| 594 | assert result.blocked is False | 594 | assert result.blocked is False |
| 595 | 595 | ||
| 596 | 596 | ||
| 597 | +def test_check_sql_rejects_selected_column_missing_from_group_by() -> None: | ||
| 598 | + """A selected column under GROUP BY must be grouped or aggregated.""" | ||
| 599 | + bare = check_sql( | ||
| 600 | + "SELECT time, crh_unsub_users FROM fact_metric WHERE time > 0 GROUP BY time", | ||
| 601 | + dialect="postgres", | ||
| 602 | + schema={}, | ||
| 603 | + ) | ||
| 604 | + summed = check_sql( | ||
| 605 | + "SELECT time, SUM(crh_unsub_users) AS crh_unsub_users FROM fact_metric WHERE time > 0 GROUP BY time", | ||
| 606 | + dialect="postgres", | ||
| 607 | + schema={"fact_metric": {"columns": {"time": {}, "crh_unsub_users": {}}}}, | ||
| 608 | + ) | ||
| 609 | + | ||
| 610 | + assert bare.blocked is True | ||
| 611 | + assert bare.violations[0].rule_id == "SYNTAX-001" | ||
| 612 | + assert "crh_unsub_users" in bare.violations[0].message | ||
| 613 | + assert summed.blocked is False | ||
| 614 | + | ||
| 615 | + | ||
| 597 | def test_check_sql_allows_whitelisted_query_clauses() -> None: | 616 | def test_check_sql_allows_whitelisted_query_clauses() -> None: |
| 598 | """Security checker should allow the fixed filtering, grouping, sorting, and filter clauses.""" | 617 | """Security checker should allow the fixed filtering, grouping, sorting, and filter clauses.""" |
| 599 | schema = {"orders": {"columns": {"customer_id": {}, "amount": {}, "status": {}}}} | 618 | schema = {"orders": {"columns": {"customer_id": {}, "amount": {}, "status": {}}}} |
| @@ -879,6 +898,25 @@ def test_check_sql_rejects_high_confidence_query_shapes(sql: str, rule_id: str, | |||
| 879 | assert message in result.violations[0].message | 898 | assert message in result.violations[0].message |
| 880 | 899 | ||
| 881 | 900 | ||
| 901 | +def test_check_sql_allows_grouped_aggregate_without_row_filter() -> None: | ||
| 902 | + """Aggregating every selected metric under GROUP BY is not an unfiltered row dump.""" | ||
| 903 | + schema = {"fact_metric": {"columns": {"ne_name": {}, "time": {}, "users": {}}}} | ||
| 904 | + allowed = check_sql( | ||
| 905 | + "SELECT ne_name, time, SUM(users) AS users FROM fact_metric GROUP BY ne_name, time ORDER BY ne_name, time", | ||
| 906 | + dialect="postgres", | ||
| 907 | + schema=schema, | ||
| 908 | + ) | ||
| 909 | + distinct_dump = check_sql( | ||
| 910 | + "SELECT ne_name FROM fact_metric GROUP BY ne_name", | ||
| 911 | + dialect="postgres", | ||
| 912 | + schema=schema, | ||
| 913 | + ) | ||
| 914 | + | ||
| 915 | + assert allowed.blocked is False | ||
| 916 | + assert distinct_dump.blocked is True | ||
| 917 | + assert distinct_dump.violations[0].rule_id == "RESOURCE-009" | ||
| 918 | + | ||
| 919 | + | ||
| 882 | @pytest.mark.parametrize( | 920 | @pytest.mark.parametrize( |
| 883 | "sql", | 921 | "sql", |
| 884 | [ | 922 | [ |
| @@ -179,9 +179,172 @@ async def test_reflector_receives_actionable_security_issue_without_rewriting_it | |||
| 179 | node = ReflectorNode(threshold=0.9) | 179 | node = ReflectorNode(threshold=0.9) |
| 180 | node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": "SELECT orders.id FROM orders"}]) | 180 | node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": "SELECT orders.id FROM orders"}]) |
| 181 | 181 | ||
| 182 | - fixed_sql = await node._fix_sql([candidate]) | 182 | + fixes = await node._fix_sql([candidate]) |
| 183 | 183 | ||
| 184 | context = node.execute_with_llm_json.await_args.args[0] | 184 | context = node.execute_with_llm_json.await_args.args[0] |
| 185 | cases = json.loads(context.get("cases", "[]")) | 185 | cases = json.loads(context.get("cases", "[]")) |
| 186 | assert cases[0].get("issues", []) == [issue] | 186 | assert cases[0].get("issues", []) == [issue] |
| 187 | - assert fixed_sql == ["SELECT orders.id FROM orders"] | 187 | + assert context.get("review_history") == "" |
| 188 | + assert fixes == [{"sql": "SELECT orders.id FROM orders", "unresolved": []}] | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +_PRIOR_ROUND = [{"round": 1, "id": 0, "issues": [], "changed": False, "unresolved": ["cannot be fixed"]}] | ||
| 192 | + | ||
| 193 | + | ||
| 194 | +@pytest.mark.asyncio | ||
| 195 | +async def test_repeated_unchanged_round_ends_the_loop() -> None: | ||
| 196 | + """Once an unchanged round repeats, the Validator has had its chance; stop reflecting.""" | ||
| 197 | + sql = "SELECT time, SUM(metric) AS metric FROM fact_metric GROUP BY time ORDER BY time" | ||
| 198 | + node = ReflectorNode(threshold=0.9) | ||
| 199 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": f" {sql} ;", "unresolved": []}]) | ||
| 200 | + state = get_default_state("question", ref_retries=2, review_history=list(_PRIOR_ROUND)) | ||
| 201 | + state["validation_results"] = [ | ||
| 202 | + Result(id=0, sql=sql, prompt="p", score=0.8, issues=["cannot be applied"], security_checked=True) | ||
| 203 | + ] | ||
| 204 | + | ||
| 205 | + result = await node._aprocess(state) | ||
| 206 | + | ||
| 207 | + assert result["proceed"] is True | ||
| 208 | + assert result["sql"] == sql | ||
| 209 | + assert result["security_sql_approved"] is True | ||
| 210 | + assert result["generation_results"] == [] | ||
| 211 | + assert result["validation_results"][0].sql == sql | ||
| 212 | + # This path produces no SQL of its own, so nothing may be streamed or appended to it. | ||
| 213 | + assert result["stream_message"] == "" | ||
| 214 | + | ||
| 215 | + | ||
| 216 | +@pytest.mark.asyncio | ||
| 217 | +async def test_unchanged_sql_never_approves_a_security_blocked_candidate() -> None: | ||
| 218 | + """The no-op exit must not become a way around the security verdict.""" | ||
| 219 | + blocked_sql = "SELECT current_setting('x')" | ||
| 220 | + node = ReflectorNode(threshold=0.9) | ||
| 221 | + node.execute_with_llm_json = AsyncMock( | ||
| 222 | + return_value=[{"id": 0, "sql": blocked_sql, "unresolved": ["cannot be fixed"]}] | ||
| 223 | + ) | ||
| 224 | + state = get_default_state("question", ref_retries=2, review_history=list(_PRIOR_ROUND)) | ||
| 225 | + state["validation_results"] = [_candidate(0, blocked_sql, 0.0, blocked=True)] | ||
| 226 | + | ||
| 227 | + result = await node._aprocess(state) | ||
| 228 | + | ||
| 229 | + assert result["proceed"] is False | ||
| 230 | + assert result["security_sql_approved"] is False | ||
| 231 | + assert result["sql"] == "" | ||
| 232 | + | ||
| 233 | + | ||
| 234 | +@pytest.mark.asyncio | ||
| 235 | +async def test_failed_repair_round_keeps_retrying_instead_of_approving() -> None: | ||
| 236 | + """A transient Reflector failure is not a decision to leave the SQL as is.""" | ||
| 237 | + sql = "SELECT id FROM orders" | ||
| 238 | + node = ReflectorNode(threshold=0.9, sql_security_enabled=False) | ||
| 239 | + node.execute_with_llm_json = AsyncMock(return_value=[]) | ||
| 240 | + state = get_default_state("question", ref_retries=2, review_history=list(_PRIOR_ROUND)) | ||
| 241 | + state["validation_results"] = [ | ||
| 242 | + Result(id=0, sql=sql, prompt="p", score=0.1, issues=["Missing time filter"], security_checked=True) | ||
| 243 | + ] | ||
| 244 | + | ||
| 245 | + result = await node._aprocess(state) | ||
| 246 | + | ||
| 247 | + assert result["proceed"] is False | ||
| 248 | + assert result["generation_results"][0].sql == sql | ||
| 249 | + assert result["review_history"] == _PRIOR_ROUND | ||
| 250 | + | ||
| 251 | + | ||
| 252 | +@pytest.mark.asyncio | ||
| 253 | +async def test_unchanged_sql_does_not_approve_a_candidate_still_needing_dimension_join() -> None: | ||
| 254 | + """need_ref marks an incomplete rewrite, so the no-op exit must not short-circuit it.""" | ||
| 255 | + sql = "SELECT county, SUM(x) AS x FROM fact GROUP BY county" | ||
| 256 | + node = ReflectorNode(threshold=0.9, sql_security_enabled=False) | ||
| 257 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": sql, "unresolved": []}]) | ||
| 258 | + state = get_default_state("question", ref_retries=2, review_history=list(_PRIOR_ROUND)) | ||
| 259 | + state["validation_results"] = [ | ||
| 260 | + Result(id=0, sql=sql, prompt="p", score=1.0, issues=[], need_ref=True, security_checked=True) | ||
| 261 | + ] | ||
| 262 | + | ||
| 263 | + result = await node._aprocess(state) | ||
| 264 | + | ||
| 265 | + assert result["proceed"] is False | ||
| 266 | + | ||
| 267 | + | ||
| 268 | +@pytest.mark.parametrize( | ||
| 269 | + ("after_sql", "unresolved", "changed"), | ||
| 270 | + [ | ||
| 271 | + ("SELECT fact_orders.id FROM fact_orders INNER JOIN dim_date ON fact_orders.dt = dim_date.dt", [], True), | ||
| 272 | + ("SELECT id FROM fact_orders", ["needs a column the schema does not have"], False), | ||
| 273 | + ], | ||
| 274 | + ids=["repaired", "left-as-is"], | ||
| 275 | +) | ||
| 276 | +@pytest.mark.asyncio | ||
| 277 | +async def test_repair_round_is_recorded_and_sent_back_for_revalidation( | ||
| 278 | + after_sql: str, unresolved: list[str], changed: bool | ||
| 279 | +) -> None: | ||
| 280 | + """Every completed round lands in the ledger, and the first one always re-enters the Validator.""" | ||
| 281 | + before_sql = "SELECT id FROM fact_orders" | ||
| 282 | + issues = ["Missing dimension-table JOIN on dim_date"] | ||
| 283 | + node = ReflectorNode(threshold=0.9) | ||
| 284 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": after_sql, "unresolved": unresolved}]) | ||
| 285 | + state = get_default_state("question", ref_retries=2) | ||
| 286 | + state["validation_results"] = [ | ||
| 287 | + Result(id=0, sql=before_sql, prompt="schema prompt", score=0.1, issues=issues, security_checked=True) | ||
| 288 | + ] | ||
| 289 | + | ||
| 290 | + result = await node._aprocess(state) | ||
| 291 | + | ||
| 292 | + assert result["proceed"] is False | ||
| 293 | + assert result["validation_results"] == [] | ||
| 294 | + assert result["generation_results"][0].sql == after_sql | ||
| 295 | + assert result["review_history"] == [ | ||
| 296 | + { | ||
| 297 | + "round": 1, | ||
| 298 | + "id": 0, | ||
| 299 | + "sql_before": before_sql, | ||
| 300 | + "issues": issues, | ||
| 301 | + "sql_after": after_sql, | ||
| 302 | + "changed": changed, | ||
| 303 | + "unresolved": unresolved, | ||
| 304 | + } | ||
| 305 | + ] | ||
| 306 | + | ||
| 307 | + | ||
| 308 | +@pytest.mark.asyncio | ||
| 309 | +async def test_reflector_ledger_numbers_rounds_and_feeds_the_next_repair() -> None: | ||
| 310 | + """A second round appends to the ledger and injects the first round back into the repair prompt.""" | ||
| 311 | + first_before = "SELECT id FROM fact_orders" | ||
| 312 | + first_after = "SELECT fact_orders.id FROM fact_orders INNER JOIN dim_date ON fact_orders.dt = dim_date.dt" | ||
| 313 | + second_after = "SELECT fact_orders.id FROM fact_orders WHERE fact_orders.dt >= '2024-01-01'" | ||
| 314 | + first_issues = ["Missing dimension-table JOIN on dim_date"] | ||
| 315 | + second_issues = ["Drop unused JOIN on dim_date"] | ||
| 316 | + node = ReflectorNode(threshold=0.9, sql_security_enabled=False) | ||
| 317 | + node.execute_with_llm_json = AsyncMock( | ||
| 318 | + side_effect=[ | ||
| 319 | + [{"id": 0, "sql": first_after, "unresolved": []}], | ||
| 320 | + [{"id": 0, "sql": second_after, "unresolved": ["Render a chart. - SQL cannot draw charts."]}], | ||
| 321 | + ] | ||
| 322 | + ) | ||
| 323 | + state = get_default_state("question", ref_retries=3) | ||
| 324 | + state["validation_results"] = [ | ||
| 325 | + Result(id=0, sql=first_before, prompt="p", score=0.1, issues=first_issues, security_checked=True) | ||
| 326 | + ] | ||
| 327 | + | ||
| 328 | + state = await node._aprocess(state) | ||
| 329 | + state["validation_results"] = [ | ||
| 330 | + Result(id=0, sql=first_after, prompt="p", score=0.2, issues=second_issues, security_checked=True) | ||
| 331 | + ] | ||
| 332 | + state = await node._aprocess(state) | ||
| 333 | + | ||
| 334 | + second_context = node.execute_with_llm_json.await_args_list[1].args[0] | ||
| 335 | + assert json.loads(second_context.get("review_history", "[]")) == [ | ||
| 336 | + { | ||
| 337 | + "round": 1, | ||
| 338 | + "id": 0, | ||
| 339 | + "sql_before": first_before, | ||
| 340 | + "issues": first_issues, | ||
| 341 | + "sql_after": first_after, | ||
| 342 | + "changed": True, | ||
| 343 | + "unresolved": [], | ||
| 344 | + } | ||
| 345 | + ] | ||
| 346 | + assert [(entry["round"], entry["issues"]) for entry in state["review_history"]] == [ | ||
| 347 | + (1, first_issues), | ||
| 348 | + (2, second_issues), | ||
| 349 | + ] | ||
| 350 | + assert state["review_history"][1]["unresolved"] == ["Render a chart. - SQL cannot draw charts."] | ||
| @@ -10,12 +10,13 @@ | |||
| 10 | # See the License for the specific language governing permissions and | 10 | # See the License for the specific language governing permissions and |
| 11 | # limitations under the License. | 11 | # limitations under the License. |
| 12 | # ============================================================================ | 12 | # ============================================================================ |
| 13 | +import json | ||
| 13 | from unittest.mock import AsyncMock | 14 | from unittest.mock import AsyncMock |
| 14 | 15 | ||
| 15 | import pytest | 16 | import pytest |
| 16 | 17 | ||
| 17 | from dataagent.agents.nl2sql.nodes.validator import ValidatorNode | 18 | from dataagent.agents.nl2sql.nodes.validator import ValidatorNode |
| 18 | -from dataagent.agents.nl2sql.workflow.state import Result | 19 | +from dataagent.agents.nl2sql.workflow.state import Result, get_default_state |
| 19 | from dataagent.config.config_manager import ConfigManager | 20 | from dataagent.config.config_manager import ConfigManager |
| 20 | 21 | ||
| 21 | 22 | ||
| @@ -126,3 +127,54 @@ async def test_validator_checks_all_generated_candidates_independently() -> None | |||
| 126 | assert safe.security_violations == [] | 127 | assert safe.security_violations == [] |
| 127 | assert safe.security_checked is True | 128 | assert safe.security_checked is True |
| 128 | assert result[1].get("score", 0) == 1 | 129 | assert result[1].get("score", 0) == 1 |
| 130 | + | ||
| 131 | + | ||
| 132 | +@pytest.mark.parametrize( | ||
| 133 | + ("reported", "expected_score"), | ||
| 134 | + [ | ||
| 135 | + ({"score": 0.8, "issues": []}, 1), | ||
| 136 | + ({"score": 0.8, "issues": ["Missing time filter"]}, 0.8), | ||
| 137 | + ({"score": 0.8}, 1), | ||
| 138 | + ], | ||
| 139 | + ids=["no-issues", "with-issues", "issues-key-omitted"], | ||
| 140 | +) | ||
| 141 | +@pytest.mark.asyncio | ||
| 142 | +async def test_semantic_score_only_drops_when_there_is_something_to_repair( | ||
| 143 | + reported: dict, expected_score: float | ||
| 144 | +) -> None: | ||
| 145 | + """A score below the threshold with an empty issue list leaves the Reflector nothing to do.""" | ||
| 146 | + node = ValidatorNode(config_manager=_config_manager(), db_explain=False, sql_security_enabled=False) | ||
| 147 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, **reported}]) | ||
| 148 | + state = get_default_state("question", generation_results=[Result(id=0, sql="SELECT time FROM fact_metric")]) | ||
| 149 | + | ||
| 150 | + result = await node._aprocess(state) | ||
| 151 | + | ||
| 152 | + assert result["validation_results"][0].score == expected_score | ||
| 153 | + # No prior round here, so the template must not render an empty history block. | ||
| 154 | + assert node.execute_with_llm_json.await_args.args[0]["review_history"] == "" | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +@pytest.mark.asyncio | ||
| 158 | +async def test_validator_passes_prior_review_rounds_to_the_semantic_check() -> None: | ||
| 159 | + """The semantic check must see what earlier rounds raised and what could not be repaired.""" | ||
| 160 | + node = ValidatorNode(config_manager=_config_manager(), db_explain=False, sql_security_enabled=False) | ||
| 161 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "score": 1, "issues": []}]) | ||
| 162 | + entry = { | ||
| 163 | + "round": 1, | ||
| 164 | + "id": 0, | ||
| 165 | + "sql_before": "SELECT time FROM fact_metric", | ||
| 166 | + "issues": ["Aggregate by city as well."], | ||
| 167 | + "sql_after": "SELECT time FROM fact_metric", | ||
| 168 | + "changed": False, | ||
| 169 | + "unresolved": ["Aggregate by city as well. - the schema has no city column."], | ||
| 170 | + } | ||
| 171 | + state = get_default_state( | ||
| 172 | + "question", | ||
| 173 | + generation_results=[Result(id=0, sql="SELECT time FROM fact_metric")], | ||
| 174 | + review_history=[entry], | ||
| 175 | + ) | ||
| 176 | + | ||
| 177 | + await node._aprocess(state) | ||
| 178 | + | ||
| 179 | + context = node.execute_with_llm_json.await_args.args[0] | ||
| 180 | + assert json.loads(context["review_history"]) == [entry] | ||
| @@ -20,6 +20,9 @@ from starlette.testclient import TestClient | |||
| 20 | 20 | ||
| 21 | from dataagent.interface.rest_api.app import app, get_data_agent_service | 21 | from dataagent.interface.rest_api.app import app, get_data_agent_service |
| 22 | 22 | ||
| 23 | +OPERATION_PATH = "/api/agent/operation" | ||
| 24 | +LEGACY_QUERY_PATH = "/api/agent/query" | ||
| 25 | + | ||
| 23 | 26 | ||
| 24 | class _StubDataAgentService: | 27 | class _StubDataAgentService: |
| 25 | """Return the submitted query without invoking the real agent.""" | 28 | """Return the submitted query without invoking the real agent.""" |
| @@ -69,23 +72,126 @@ def client() -> Iterator[TestClient]: | |||
| 69 | app.dependency_overrides.pop(get_data_agent_service, None) | 72 | app.dependency_overrides.pop(get_data_agent_service, None) |
| 70 | 73 | ||
| 71 | 74 | ||
| 75 | +def test_query_endpoint_requires_type_and_content(client: TestClient) -> None: | ||
| 76 | + """type is the discriminator; missing type is rejected.""" | ||
| 77 | + response = client.post(OPERATION_PATH, json={"content": {"query": "hello"}}) | ||
| 78 | + | ||
| 79 | + assert response.status_code == 422 | ||
| 80 | + detail = response.json()["detail"][0] | ||
| 81 | + assert detail["type"] == "union_tag_not_found" | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def test_query_endpoint_accepts_type_query(client: TestClient) -> None: | ||
| 85 | + """Query body is type + content{query, stream}. Output shape stays the same.""" | ||
| 86 | + response = client.post( | ||
| 87 | + OPERATION_PATH, | ||
| 88 | + json={"type": "query", "content": {"query": "hello", "stream": False}}, | ||
| 89 | + ) | ||
| 90 | + | ||
| 91 | + assert response.status_code == 200 | ||
| 92 | + assert response.json() == {"query": "hello"} | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def test_legacy_query_path_keeps_original_body(client: TestClient) -> None: | ||
| 96 | + """POST /api/agent/query keeps the original {query, stream} contract.""" | ||
| 97 | + response = client.post( | ||
| 98 | + LEGACY_QUERY_PATH, | ||
| 99 | + json={"query": "hello", "stream": False}, | ||
| 100 | + ) | ||
| 101 | + | ||
| 102 | + assert response.status_code == 200 | ||
| 103 | + assert response.json() == {"query": "hello"} | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def test_legacy_query_path_rejects_operation_body(client: TestClient) -> None: | ||
| 107 | + """Old query callers must not be required to send type/content.""" | ||
| 108 | + response = client.post( | ||
| 109 | + LEGACY_QUERY_PATH, | ||
| 110 | + json={"type": "query", "content": {"query": "hello", "stream": False}}, | ||
| 111 | + ) | ||
| 112 | + | ||
| 113 | + assert response.status_code == 422 | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def test_query_endpoint_rejects_string_content(client: TestClient) -> None: | ||
| 117 | + """content must be an object for type=query, not a string.""" | ||
| 118 | + response = client.post( | ||
| 119 | + OPERATION_PATH, | ||
| 120 | + json={"type": "query", "content": "hello"}, | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + assert response.status_code == 422 | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def test_query_endpoint_rejects_unknown_type(client: TestClient) -> None: | ||
| 127 | + """Unimplemented operations must not fall through to query.""" | ||
| 128 | + response = client.post( | ||
| 129 | + OPERATION_PATH, | ||
| 130 | + json={"type": "update", "content": {"query": "hello", "stream": False}}, | ||
| 131 | + ) | ||
| 132 | + | ||
| 133 | + assert response.status_code == 422 | ||
| 134 | + detail = response.json()["detail"][0] | ||
| 135 | + assert detail["type"] == "union_tag_invalid" | ||
| 136 | + | ||
| 137 | + | ||
| 138 | +def test_query_endpoint_rejects_legacy_field_names(client: TestClient) -> None: | ||
| 139 | + """Old top-level field names operation/query are not accepted.""" | ||
| 140 | + response = client.post( | ||
| 141 | + OPERATION_PATH, | ||
| 142 | + json={"operation": "query", "query": "hello"}, | ||
| 143 | + ) | ||
| 144 | + | ||
| 145 | + assert response.status_code == 422 | ||
| 146 | + | ||
| 147 | + | ||
| 72 | def test_query_endpoint_rejects_unknown_body_fields(client: TestClient) -> None: | 148 | def test_query_endpoint_rejects_unknown_body_fields(client: TestClient) -> None: |
| 73 | response = client.post( | 149 | response = client.post( |
| 74 | - "/api/agent/query", | 150 | + LEGACY_QUERY_PATH, |
| 75 | json={"query": "hello", "unknown_field": True}, | 151 | json={"query": "hello", "unknown_field": True}, |
| 76 | ) | 152 | ) |
| 77 | 153 | ||
| 78 | assert response.status_code == 422 | 154 | assert response.status_code == 422 |
| 79 | detail = response.json()["detail"][0] | 155 | detail = response.json()["detail"][0] |
| 80 | assert detail["type"] == "extra_forbidden" | 156 | assert detail["type"] == "extra_forbidden" |
| 81 | - assert detail["loc"] == ["body", "unknown_field"] | 157 | + assert detail["loc"][-1] == "unknown_field" |
| 158 | + | ||
| 159 | + | ||
| 160 | +def test_operation_endpoint_rejects_unknown_body_fields(client: TestClient) -> None: | ||
| 161 | + response = client.post( | ||
| 162 | + OPERATION_PATH, | ||
| 163 | + json={"type": "query", "content": {"query": "hello"}, "unknown_field": True}, | ||
| 164 | + ) | ||
| 165 | + | ||
| 166 | + assert response.status_code == 422 | ||
| 167 | + detail = response.json()["detail"][0] | ||
| 168 | + assert detail["type"] == "extra_forbidden" | ||
| 169 | + assert detail["loc"][-1] == "unknown_field" | ||
| 170 | + | ||
| 171 | + | ||
| 172 | +def test_legacy_query_path_returns_detailed_sql_security_error() -> None: | ||
| 173 | + """Original /query body still returns mapped SQL security details.""" | ||
| 174 | + app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService | ||
| 175 | + try: | ||
| 176 | + response = TestClient(app).post( | ||
| 177 | + LEGACY_QUERY_PATH, | ||
| 178 | + json={"query": "show missing column"}, | ||
| 179 | + ) | ||
| 180 | + finally: | ||
| 181 | + app.dependency_overrides.pop(get_data_agent_service, None) | ||
| 182 | + | ||
| 183 | + assert response.status_code == 422 | ||
| 184 | + assert response.json() == _StubSQLSecurityErrorService._result | ||
| 82 | 185 | ||
| 83 | 186 | ||
| 84 | def test_query_endpoint_returns_detailed_sql_security_error() -> None: | 187 | def test_query_endpoint_returns_detailed_sql_security_error() -> None: |
| 85 | """Non-streaming REST responses should preserve mapped SQL security details.""" | 188 | """Non-streaming REST responses should preserve mapped SQL security details.""" |
| 86 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService | 189 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService |
| 87 | try: | 190 | try: |
| 88 | - response = TestClient(app).post("/api/agent/query", json={"query": "show missing column"}) | 191 | + response = TestClient(app).post( |
| 192 | + OPERATION_PATH, | ||
| 193 | + json={"type": "query", "content": {"query": "show missing column"}}, | ||
| 194 | + ) | ||
| 89 | finally: | 195 | finally: |
| 90 | app.dependency_overrides.pop(get_data_agent_service, None) | 196 | app.dependency_overrides.pop(get_data_agent_service, None) |
| 91 | 197 | ||
| @@ -98,8 +204,8 @@ def test_streaming_query_returns_detailed_sql_security_error() -> None: | |||
| 98 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService | 204 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService |
| 99 | try: | 205 | try: |
| 100 | response = TestClient(app).post( | 206 | response = TestClient(app).post( |
| 101 | - "/api/agent/query", | 207 | + OPERATION_PATH, |
| 102 | - json={"query": "show missing column", "stream": True}, | 208 | + json={"type": "query", "content": {"query": "show missing column", "stream": True}}, |
| 103 | ) | 209 | ) |
| 104 | finally: | 210 | finally: |
| 105 | app.dependency_overrides.pop(get_data_agent_service, None) | 211 | app.dependency_overrides.pop(get_data_agent_service, None) |