{"record":{"id":"de4ac466bdd88902","repo":"ZhuLinsen/daily_stock_analysis","slug":"stock-code-is-required","errorCode":null,"errorMessage":"stock_code is required","messagePattern":"stock_code is required","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/agent/events.py","lineNumber":470,"sourceCode":"\n    invalid_indices = [idx for idx, entry in enumerate(parsed) if not isinstance(entry, dict)]\n    if invalid_indices:\n        raise ValueError(\n            \"Event alert rules list must contain only objects; \"\n            f\"invalid entries at positions: {invalid_indices}\"\n        )\n\n    return parsed\n\n\ndef validate_event_alert_rule(rule: Dict[str, Any]) -> None:\n    \"\"\"Validate one serialized EventMonitor rule.\"\"\"\n    if not isinstance(rule, dict):\n        raise ValueError(\"Event alert rule must be an object\")\n\n    stock_code = str(rule.get(\"stock_code\") or \"\").strip()\n    if not stock_code:\n        raise ValueError(\"stock_code is required\")\n\n    try:\n        alert_type = AlertType(rule.get(\"alert_type\", \"\"))\n    except ValueError as exc:\n        raise ValueError(f\"invalid alert_type: {rule.get('alert_type')}\") from exc\n    _ensure_runtime_supported_alert_type(alert_type)\n\n    status = rule.get(\"status\")\n    if status is not None:\n        try:\n            AlertStatus(status)\n        except ValueError as exc:\n            raise ValueError(f\"invalid status: {status}\") from exc\n\n    ttl_hours = rule.get(\"ttl_hours\")\n    if ttl_hours is not None:\n        try:\n            ttl_value = float(ttl_hours)","sourceCodeStart":452,"sourceCodeEnd":488,"githubUrl":"https://github.com/ZhuLinsen/daily_stock_analysis/blob/5159bd72e8373d215492dff122acc9d389e219c9/src/agent/events.py#L452-L488","documentation":"Raised by validate_event_alert_rule in src/agent/events.py when a serialized EventMonitor rule dict has a missing, empty, or whitespace-only 'stock_code' field. stock_code is the mandatory identity key that ties an alert rule to the instrument it monitors, so an empty value makes the rule unusable. This is a pure input-validation error at the rule-parsing boundary, not a runtime market-data failure.","triggerScenarios":"Calling validate_event_alert_rule(rule) (directly or via any API that deserializes persisted/LLM-generated alert rules, e.g. adding rules to EventMonitor) with a dict where rule['stock_code'] is absent, None, '', or '   '. Note str(rule.get(\"stock_code\") or '') coerces non-strings, so 0 or empty containers also become '' and fail.","commonSituations":"Alert rules round-tripped from JSON storage where the key was dropped; LLM-generated rule payloads that omit the ticker; upstream code that stores quote-based rules keyed by name instead of code; a frontend form submitting the field before the user picks a stock.","solutions":["Ensure the rule dict contains a non-empty 'stock_code' string (e.g. '600519', 'hk00700', 'AAPL') before validation.","If rules come from an LLM or user input, add a schema check (presence + non-blank) at the ingestion boundary and reject/repair early with a clearer message.","If a default instrument is intended, populate stock_code explicitly from context instead of relying on an optional field."],"exampleFix":"// before\nrule = {\"alert_type\": \"price_cross\", \"price\": 100}\nvalidate_event_alert_rule(rule)  # ValueError: stock_code is required\n\n// after\nrule = {\"stock_code\": \"600519\", \"alert_type\": \"price_cross\", \"price\": 100}\nvalidate_event_alert_rule(rule)","handlingStrategy":"validation","validationCode":"def has_stock_code(rule: dict) -> bool:\n    return bool(str(rule.get(\"stock_code\") or \"\").strip())","typeGuard":"def is_valid_rule_shell(rule: object) -> bool:\n    return isinstance(rule, dict) and has_stock_code(rule)","tryCatchPattern":"try:\n    validate_event_alert_rule(rule)\nexcept ValueError as e:\n    logger.warning(\"rejected alert rule: %s\", e)\n    # drop or send back for repair; do not add to EventMonitor","preventionTips":["Validate rules at the ingestion boundary (API/LLM extractor) before persisting.","Make stock_code a required field in any form or schema that creates alert rules.","Round-trip test persisted rules through validate_event_alert_rule in CI."],"tags":["validation","event-monitor","stock-code","input"],"backgroundTag":null,"analyzedSha":"5159bd72e8373d215492dff122acc9d389e219c9","analyzedAt":"2026-08-15T01:59:36.292Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}