diff --git a/AGENTS.md b/AGENTS.md index dfd1bfa..1979f04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ - 修复前先写清违反的业务约束、规则来源和适用范围。错误实现不能成为新规则;补一个限制时,同时核对原来允许的动作仍然可达。 - 数据、信号或异步链路按应覆盖名单逐路判收,区分输入新鲜、具备计算资格、已计算未触发、无法计算、发布和消费。顶层成功、总消息数、其他来源正常不能替代本路证据。 +- 超时按各来源的发布周期和交易时段判断,区分服务心跳、原始数据时间及名单生效时间。正常结算、午休和新名单同步等待不报故障;等待须有上限,不能随快照刷新重置,也不能放宽真实数据失效条件。 - 修复须沿实际入口到最终保存或动作检查同一业务的其他调用方、缓存和版本,并以旧故障反例验证预防措施。线上故障定位、重复返工或恢复验收使用[pms-incident-review](.agents/skills/pms-incident-review/SKILL.md);不要求普通文案和研究试验走完整故障流程。 ## 授权边界 diff --git a/DEVLOG.md b/DEVLOG.md index 4b09668..36e5bc1 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -3271,3 +3271,10 @@ a44c994于10:53:29仅发布155的web,镜像pms:proposal-copy-a44c994。开发 10:19至10:35只读检查155模拟PMS、188上游ITD及PMS已连接的信号数据。正式流与PMS一致,14只关注持仓当时仅8条日QRS;实际页面计算函数125组身份与等级对照未发现过滤。14只都有ITD六路状态及MTF当日计算轨迹;10:22四路资金重算未触发,不代表整日上午均未触发。果麦文化相对昨收最低跌11.82%,但独立股价生产者没有发布;同版本同配置历史上有301股票跌约8%及关注股九州一轨跌8.12%的提醒,不能以板块或关注身份解释。生产者代码、名单、逐股输入和去重尚未定位,已询问部署位置。 已归档[核验记录](docs/关注持仓信号过滤核验_2026-11-18.md)和最小证据,明确资金健康不能替代股价覆盖。只改文档、入口与证据,检查内容、JSON及本地链接;没有修改业务代码、参数、容器或访问188真实PMS,股价提醒缺席尚未修复。 + + +## 2026-11-18 资金提示的预期延迟与故障区分 + +12:50只读确认本次提示来自11:52:57午休新增的603087.SH,原14只优先股票及131只原池资金均可用。ITD休市沿11:30数据检查,下一交易分钟才同步新名单;PMS将缺少覆盖回执立即等同数据故障。新增反例复现旧版午休与午后开盘两处误报。修正按交易时段计算等待、固定原始登记时刻、区分等待接入与超时及真实数据异常;健康心跳仍按自然时间,原始资金有效期保持15分钟。内部保留未就绪原因,不将关闭提示当成已恢复。 + +开发机90组隔离禁网全量通过,含20项资金状态及25项关注发布测试。拟定向更新155 web及worker(worker仅传递原始登记时刻),按实际角色镜像构建并继续候选断网验收;此记录时尚未部署。项目规则补充来源周期、交易时段和不可重置的等待上限。 diff --git a/app/core/signal_health.py b/app/core/signal_health.py index 8bd0d1f..0345683 100644 --- a/app/core/signal_health.py +++ b/app/core/signal_health.py @@ -1,32 +1,80 @@ -"""交易员只看到当前提醒能力的异常;历史准备状态保留在内部巡检。""" +"""按来源更新节奏区分正常等待和异常;等待不等于已具备提醒能力。""" from datetime import datetime from zoneinfo import ZoneInfo +TZ = ZoneInfo('Asia/Shanghai') +# 延续既有健康报告三分钟容限;原始资金的15分钟有效期由ITD独立判定。 +REPORT_MAX_AGE = 180 -def funds_warning(doc, codes, now=None, *, trade_day=True): - now = now or datetime.now(ZoneInfo('Asia/Shanghai')) + +def _time(value): + at = datetime.fromisoformat(value) + if at.tzinfo is None: + raise ValueError('missing timezone') + return at.astimezone(TZ) + + +def _trading_seconds(start, end): + """同日只累计交易时段,午休不会消耗接入或分钟计算的等待额度。""" + if start.date() != end.date() or start > end: + return (end-start).total_seconds() + seconds = 0. + for sh, sm, eh, em in ((9, 30, 11, 30), (13, 0, 15, 0)): + left = end.replace(hour=sh, minute=sm, second=0, microsecond=0) + right = end.replace(hour=eh, minute=em, second=0, microsecond=0) + seconds += max(0., (min(end, right)-max(start, left)).total_seconds()) + return seconds + + +def funds_status(doc, codes, now=None, *, trade_day=True, registered_at=None): + now = (now or datetime.now(TZ)).astimezone(TZ) hm = now.strftime('%H:%M') active = trade_day and ('09:45' <= hm <= '11:31' or '13:01' <= hm <= '15:01') - unavailable = '资金异动提醒可能延迟,系统正在重试。' + out = {'state': 'not_due', 'warning': '', 'missing_codes': [], 'unavailable_codes': [], + 'pending_codes': [], 'report_at': None, 'as_of': None} + + def result(state, warning=''): + # 休市无需新提醒,仍保留内部原因,不能把休市当作数据已经恢复。 + out.update(state=state if active else 'not_due', reason=state, + warning=warning if active else '') + return out + + delayed = '资金异动提醒可能延迟,系统正在重试。' try: - at = datetime.fromisoformat(doc['at']) - as_of = datetime.fromisoformat(doc['as_of']) - if at.tzinfo is None or as_of.tzinfo is None: - raise ValueError('missing timezone') - if not 0 <= (now-at).total_seconds() <= 180 or as_of.date() != now.date(): - return unavailable if active else '' - if active and not 0 <= (now-as_of).total_seconds() <= 180: - return unavailable + at, as_of = _time(doc['at']), _time(doc['as_of']) + out.update(report_at=at.isoformat(), as_of=as_of.isoformat()) + if not 0 <= (now-at).total_seconds() <= REPORT_MAX_AGE or as_of.date() != now.date(): + return result('report_unavailable', delayed) + # 心跳按墙上时间检查;计算时刻按交易时段检查,两者不可混用。 + if not 0 <= _trading_seconds(as_of, now) <= REPORT_MAX_AGE: + return result('evaluation_delayed', delayed) rows = doc['priority'] if (not isinstance(rows, dict) or not all(isinstance(row, dict) for row in rows.values()) or doc.get('source') != 'redis_stock_flow_realtime'): raise ValueError('invalid health report') wanted = set(codes) | set(rows) - if not wanted: - return '' - bad = sum(rows.get(c, {}).get('state') != 'available' for c in wanted) + missing = wanted - set(rows) + bad = {code for code in wanted & set(rows) if rows[code].get('state') != 'available'} + out.update(missing_codes=sorted(missing), unavailable_codes=sorted(bad)) + pending = set() + for code in missing: + try: + since = _time((registered_at or {}).get(code)) + if since.date() == now.date() and 0 <= _trading_seconds(since, now) <= REPORT_MAX_AGE: + pending.add(code) + except (TypeError, ValueError): + pass + out['pending_codes'] = sorted(pending) if bad: - return '部分持仓及关注股的资金异动提醒暂不可用,系统正在重试。' - return '' + return result('data_unavailable', '部分持仓及关注股的资金异动提醒暂不可用,系统正在重试。') + if missing - pending: + return result('coverage_delayed', '部分持仓及关注股的资金异动提醒接入延迟,系统正在重试。') + if pending: + return result('pending_coverage') + return result('available') except (KeyError, TypeError, ValueError): - return unavailable if active else '' + return result('report_unavailable', delayed) + + +def funds_warning(doc, codes, now=None, *, trade_day=True, registered_at=None): + return funds_status(doc, codes, now, trade_day=trade_day, registered_at=registered_at)['warning'] diff --git a/app/services/monitor_watch.py b/app/services/monitor_watch.py index a1b68c0..c933156 100644 --- a/app/services/monitor_watch.py +++ b/app/services/monitor_watch.py @@ -77,7 +77,8 @@ def build_snapshot(registry, *, now=None, ttl=600): items = [] # 风险监测与买方评析资格分开。有效关注即参加告警;研究仍等有效评析。 alert_items = [{"ts_code": code_of(row), "watch_id": row.get("id"), - "active": True, "expires_on": row["expires_on"]} + "active": True, "expires_on": row["expires_on"], + "registered_at": row.get("created_at")} for row in registry["rows"] if isinstance(row, dict) and active(row, now)] for row in registry["rows"]: if not isinstance(row, dict) or not active(row, now) or row.get("review_status") != "completed": @@ -98,6 +99,7 @@ def build_snapshot(registry, *, now=None, ttl=600): raise ValueError("已完成的买方评析缺少有效来源或日期") items.append({"ts_code": code_of(row), "watch_id": row["id"], "watch_revision": revision, "active": True, "expires_on": row["expires_on"], "review_status": "ready", + "registered_at": row.get("created_at"), "review_ref": ref, "review_completed_at": completed.isoformat(), "review_data_date": data_date, "review_summary": str(row.get("company_review_text") or review.get("overall") or "")[:2000]}) diff --git a/app/services/upstream_signals.py b/app/services/upstream_signals.py index 3917370..cd14ab0 100644 --- a/app/services/upstream_signals.py +++ b/app/services/upstream_signals.py @@ -27,7 +27,7 @@ logger = logging.getLogger("pms.upstream") _clients = {} _cache = {"at": 0.0, "data": None} -_focus_cache = {'at': 0., 'codes': set(), 'error': None} +_focus_cache = {'at': 0., 'codes': set(), 'error': None, 'registered_at': {}} _focused_streams = {} @@ -51,11 +51,12 @@ def _focus_codes(): return _focus_cache['codes'] from app.repo import pms_repo from app.services import monitor_watch - codes, errors = set(), [] + codes, errors, registered_at = set(), [], {} try: codes.update(_norm_code(r['ts_code']) for r in pms_repo.list_positions(only_open=True)) except Exception: errors.append('持仓名单读取失败') + held = set(codes) try: scope = monitor_watch.scope() if scope: @@ -69,12 +70,16 @@ def _focus_codes(): raise ValueError('关注名单失效') for row in doc.get('items', []): if row.get('active') is True and row.get('review_status') == 'ready' and str(row.get('expires_on') or '') >= at.date().isoformat(): - codes.add(_norm_code(row.get('ts_code'))) + code = _norm_code(row.get('ts_code')) + codes.add(code) + if code not in held: + registered_at[code] = row.get('registered_at') except Exception: errors.append('关注覆盖名单暂不可用') from app.core.command_spec import is_stock_code codes = {c for c in codes if c.endswith(('.SH', '.SZ')) and is_stock_code(c)} - _focus_cache.update(at=time.time(), codes=codes, error=';'.join(errors) or None) + _focus_cache.update(at=time.time(), codes=codes, error=';'.join(errors) or None, + registered_at=registered_at) return codes @@ -348,13 +353,15 @@ def snapshot(force: bool = False) -> dict: _try("sell_actions", lambda: _read_sell_actions(_c208(dba))) _try("mr", lambda: _read_mr(_c214())) # 数据健康与信号流分开:缺失或停更不能解释为没有风险信号。 - from app.core.signal_health import funds_warning + from app.core.signal_health import funds_status from app.core import tradedays try: health = json.loads(_c208(dbi).get('intraday_alerts:fund_health') or 'null') except Exception: health = None - out['fund_warning'] = funds_warning(health, _focus_codes(), trade_day=tradedays.is_trade_day()) + out['fund_health'] = funds_status(health, _focus_codes(), trade_day=tradedays.is_trade_day(), + registered_at=_focus_cache.get('registered_at')) + out['fund_warning'] = out['fund_health']['warning'] out['coverage'] = {key[0]: {k: v[k] for k in ('truncated', 'scanned', 'eligible')} for key, v in _focused_streams.items() if key[1] == _today_start_ms()} diff --git a/scripts/test_monitor_watch_units.py b/scripts/test_monitor_watch_units.py index 14d56b6..03e67b2 100644 --- a/scripts/test_monitor_watch_units.py +++ b/scripts/test_monitor_watch_units.py @@ -58,6 +58,14 @@ class MonitorWatchTests(unittest.TestCase): self.assertNotIn('verdict', result['items'][0]) self.assertEqual(result['expires_at'], '2026-11-04T10:40:00+08:00') + def test_original_registration_survives_snapshot_refresh(self): + since=(NOW-timedelta(seconds=30)).isoformat() + data=registry([row(created_at=since)]) + for seconds in (0,60): + payload=json.loads(json.dumps(mw.build_snapshot(data,now=NOW+timedelta(seconds=seconds)))) + self.assertEqual(payload['alert_items'][0]['registered_at'],since) + self.assertEqual(payload['items'][0]['registered_at'],since) + def test_expired_removed_and_other_exchange_never_published(self): rows = [row(expires_on='2026-11-03'), row(removed_at='2026-11-04T10:00:00+08:00'), row(status='removed'), row(code='BJ920001'), row(code='SH510300')] diff --git a/scripts/test_signal_health.py b/scripts/test_signal_health.py index ef459d2..4ba9e07 100644 --- a/scripts/test_signal_health.py +++ b/scripts/test_signal_health.py @@ -5,7 +5,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import unittest from datetime import datetime, timedelta from zoneinfo import ZoneInfo -from app.core.signal_health import funds_warning +from app.core.signal_health import funds_warning, funds_status class FundsHealthTests(unittest.TestCase): @@ -31,7 +31,7 @@ class FundsHealthTests(unittest.TestCase): self.assertIn('提醒可能延迟',self.check()) def test_missing_focus_detected(self): - self.assertIn('提醒暂不可用',self.check(codes=('300133.SZ','601126.SH'))) + self.assertIn('接入延迟',self.check(codes=('300133.SZ','601126.SH'))) def test_bad_funds_and_baseline_separate(self): self.doc['priority']['300133.SZ']={'state':'stale','money_flow_baseline_ready':False} @@ -56,5 +56,98 @@ class FundsHealthTests(unittest.TestCase): self.doc['at']='2026-11-16T14:10:00' self.assertIn('提醒可能延迟',self.check()) + def test_lunch_new_focus_waits_for_trading_session(self): + now=self.now.replace(hour=12,minute=50) + self.doc.update(at=now.isoformat(),as_of=now.replace(hour=11,minute=30).isoformat()) + self.assertEqual(funds_warning(self.doc,['300133.SZ','603087.SH'],now),'') + + def test_resume_does_not_count_lunch_as_evaluation_delay(self): + now=self.now.replace(hour=13,minute=1) + self.doc.update(at=now.isoformat(),as_of=now.replace(hour=11,minute=30).isoformat()) + self.assertEqual(funds_warning(self.doc,['300133.SZ'],now),'') + + def test_registered_during_lunch_has_bounded_trading_time_wait(self): + since={'603087.SH':self.now.replace(hour=11,minute=52).isoformat()} + for minute, state in [(1,'pending_coverage'),(3,'pending_coverage'),(4,'coverage_delayed')]: + now=self.now.replace(hour=13,minute=minute,second=0) + self.doc.update(at=now.isoformat(),as_of=(now-timedelta(minutes=1)).isoformat()) + result=funds_status(self.doc,['300133.SZ','603087.SH'],now,registered_at=since) + self.assertEqual(result['state'],state) + self.assertEqual(bool(result['warning']),minute==4) + + def test_snapshot_refresh_cannot_restart_registration_wait(self): + since={'603087.SH':(self.now-timedelta(seconds=181)).isoformat()} + self.assertIn('接入延迟',self.check(codes=('603087.SH',),registered_at=since)) + + def test_unknown_old_or_future_registration_has_no_grace(self): + for since in [None,'bad','2026-11-15T14:09:00+08:00', + (self.now+timedelta(seconds=1)).isoformat()]: + self.assertIn('接入延迟',self.check(codes=('603087.SH',),registered_at={'603087.SH':since})) + + def test_real_data_fault_is_not_hidden_by_new_registration(self): + self.doc['priority']['300133.SZ']['state']='invalid_fields' + self.assertIn('提醒暂不可用',self.check(codes=('300133.SZ','603087.SH'), + registered_at={'603087.SH':self.now.isoformat()})) + + def test_closed_status_is_not_reported_as_recovered(self): + now=self.now.replace(hour=12,minute=50) + self.doc.update(at=now.isoformat(),as_of=now.replace(hour=11,minute=30).isoformat()) + self.doc['priority']['300133.SZ']['state']='invalid_fields' + result=funds_status(self.doc,['300133.SZ'],now) + self.assertEqual(result['state'],'not_due');self.assertEqual(result['warning'],'') + self.assertEqual(result['reason'],'data_unavailable') + self.assertEqual(result['unavailable_codes'],['300133.SZ']) + + def test_resume_cannot_hide_frozen_evaluation_or_heartbeat(self): + now=self.now.replace(hour=13,minute=4) + self.doc.update(at=now.isoformat(),as_of=now.replace(hour=11,minute=30).isoformat()) + self.assertIn('提醒可能延迟',funds_warning(self.doc,['300133.SZ'],now)) + self.doc.update(at=now.replace(hour=11,minute=30).isoformat(),as_of=now.isoformat()) + self.assertIn('提醒可能延迟',funds_warning(self.doc,['300133.SZ'],now)) + + def test_expected_raw_source_lag_does_not_become_status_lag(self): + self.doc['priority']['300133.SZ'].update(age_seconds=900, + observed_at=(self.now-timedelta(minutes=16)).isoformat()) + self.assertEqual(self.check(),'') # ITD已按自己的有效期给出available。 + self.doc['priority']['300133.SZ']['state']='stale' + self.assertIn('提醒暂不可用',self.check()) + + def test_first_coverage_receipt_completes_wait(self): + self.doc['priority']['603087.SH']={'state':'available'} + result=funds_status(self.doc,['603087.SH'],self.now, + registered_at={'603087.SH':self.now.isoformat()}) + self.assertEqual(result['state'],'available');self.assertEqual(result['pending_codes'],[]) + + def test_original_registration_survives_publish_and_focus_consumer(self): + import json + from unittest.mock import Mock, patch + from test_wiring import install_fakes + from test_monitor_watch_units import NOW, CODE, registry, row + from app.services import monitor_watch as mw + client=Mock() + from app.services import upstream_signals as up + from app.repo import pms_repo + from app.core.signal_health import funds_status + since=(NOW-timedelta(seconds=30)).isoformat() + data=registry([row(created_at=since)]) + install_fakes(params={'PMS_SIGNAL_FOCUS_ENABLED':True,'PMS_MONITOR_WATCH_SCOPE':mw.SCOPE}) + for seconds in (0,60): + at=NOW+timedelta(seconds=seconds) + payload=json.loads(json.dumps(mw.build_snapshot(data,now=at))) + self.assertEqual(payload['alert_items'][0]['registered_at'],since) + client.get.return_value=json.dumps(payload) + with patch.object(up,'_c208',return_value=client), \ + patch.object(up,'_focus_cache',{'at':0.,'codes':set(),'error':None}), \ + patch.object(up,'datetime',wraps=datetime) as clock, \ + patch.object(pms_repo,'list_positions',return_value=[]): + clock.now.return_value=at + codes=up._focus_codes() + self.assertEqual(codes,{CODE});self.assertEqual(up._focus_cache['registered_at'],{CODE:since}) + health={'at':at.isoformat(),'as_of':(at-timedelta(minutes=1)).isoformat(), + 'source':'redis_stock_flow_realtime','priority':{}} + result=funds_status(health,codes,at,registered_at=up._focus_cache['registered_at']) + self.assertEqual(result['state'],'pending_coverage') + self.assertEqual(result['warning'],'') + if __name__=='__main__': unittest.main()