人工候选仅向显式取用的计划调用方开放
This commit is contained in:
parent
a9fc789c86
commit
04339be2b0
25
api.py
25
api.py
|
|
@ -180,12 +180,13 @@ _PLAN_CACHE_MAX = 8 # 不同参数组合最多留几份,防内存慢
|
||||||
_PLAN_BUILD_LOCKS: dict = {} # 每个缓存键一把「正在算」的锁,见 _plan_cached 里的说明
|
_PLAN_BUILD_LOCKS: dict = {} # 每个缓存键一把「正在算」的锁,见 _plan_cached 里的说明
|
||||||
|
|
||||||
|
|
||||||
def _plan_build(date, top, obs_top, theme_cap, decision_id=None) -> dict:
|
def _plan_build(date, top, obs_top, theme_cap, decision_id=None, include_user_candidates=False) -> dict:
|
||||||
"""只读已发布版本。缺档明确报错,禁止用当前研究重构历史。"""
|
"""只读已发布版本。缺档明确报错,禁止用当前研究重构历史。"""
|
||||||
return plan.from_snapshot(date, top, obs_top, theme_cap, decision_id=decision_id)
|
return plan.from_snapshot(date, top, obs_top, theme_cap, decision_id=decision_id,
|
||||||
|
include_user_candidates=include_user_candidates)
|
||||||
|
|
||||||
|
|
||||||
def _plan_cached(date, top, obs_top, theme_cap, nocache: bool, decision_id=None):
|
def _plan_cached(date, top, obs_top, theme_cap, nocache: bool, decision_id=None, include_user_candidates=False):
|
||||||
"""返回 (data, 命中与否)。data 是 plan.collect 的结果(已去掉 _full)。
|
"""返回 (data, 命中与否)。data 是 plan.collect 的结果(已去掉 _full)。
|
||||||
|
|
||||||
键里放**真实数据日**而不是请求里的 date:不传 date 时数据日随构建更新,明早换日后
|
键里放**真实数据日**而不是请求里的 date:不传 date 时数据日随构建更新,明早换日后
|
||||||
|
|
@ -198,7 +199,7 @@ def _plan_cached(date, top, obs_top, theme_cap, nocache: bool, decision_id=None)
|
||||||
if not decision_id and not date:
|
if not decision_id and not date:
|
||||||
import user_candidates as uc
|
import user_candidates as uc
|
||||||
state = dict(state, pending_codes=sorted(set(state.get('pending_codes') or []) | set(uc.live_pending(config.PLAN_SNAPSHOT_DIR, published))))
|
state = dict(state, pending_codes=sorted(set(state.get('pending_codes') or []) | set(uc.live_pending(config.PLAN_SNAPSHOT_DIR, published))))
|
||||||
key = (pinned or pv.digest(published), pv.digest(state), int(top), int(obs_top), int(theme_cap))
|
key = (pinned or pv.digest(published), pv.digest(state), int(top), int(obs_top), int(theme_cap), bool(include_user_candidates))
|
||||||
now = time.time()
|
now = time.time()
|
||||||
if not nocache and PLAN_CACHE_SEC > 0:
|
if not nocache and PLAN_CACHE_SEC > 0:
|
||||||
with _PLAN_CACHE_LOCK:
|
with _PLAN_CACHE_LOCK:
|
||||||
|
|
@ -222,7 +223,8 @@ def _plan_cached(date, top, obs_top, theme_cap, nocache: bool, decision_id=None)
|
||||||
hit = _PLAN_CACHE.get(key)
|
hit = _PLAN_CACHE.get(key)
|
||||||
if hit and time.time() - hit[0] < PLAN_CACHE_SEC:
|
if hit and time.time() - hit[0] < PLAN_CACHE_SEC:
|
||||||
return hit[1], True
|
return hit[1], True
|
||||||
data = _plan_build(ds_key, top, obs_top, theme_cap, pinned)
|
data = _plan_build(ds_key, top, obs_top, theme_cap, pinned,
|
||||||
|
**({'include_user_candidates': True} if include_user_candidates else {}))
|
||||||
data['refresh_status'] = state
|
data['refresh_status'] = state
|
||||||
if PLAN_CACHE_SEC > 0:
|
if PLAN_CACHE_SEC > 0:
|
||||||
with _PLAN_CACHE_LOCK:
|
with _PLAN_CACHE_LOCK:
|
||||||
|
|
@ -239,14 +241,14 @@ def _plan_cached(date, top, obs_top, theme_cap, nocache: bool, decision_id=None)
|
||||||
@app.get("/plan")
|
@app.get("/plan")
|
||||||
def get_plan(request: Request, date: str | None = None, format: str = "json",
|
def get_plan(request: Request, date: str | None = None, format: str = "json",
|
||||||
top: int = 20, obs_top: int = 10, theme_cap: int = 5, nocache: int = 0,
|
top: int = 20, obs_top: int = 10, theme_cap: int = 5, nocache: int = 0,
|
||||||
decision_id: str | None = None):
|
decision_id: str | None = None, include_user_candidates: bool = False):
|
||||||
"""向下兼容承诺(2026-09-02 方案 2.7):main / observe 的装配、排序、裁剪与既有字段
|
"""向下兼容承诺(2026-09-02 方案 2.7):main / observe 的装配、排序、裁剪与既有字段
|
||||||
一字不动,每行只多联入判决类字段;顶层只新增 generated_at、plan_version、regime、
|
一字不动,每行只多联入判决类字段;顶层只新增 generated_at、plan_version、regime、
|
||||||
card_counts、candidates、watch、segments_pointed、snapshot,2026-09-03 再加 market
|
card_counts、candidates、watch、segments_pointed、snapshot,2026-09-03 再加 market
|
||||||
(环境段市场四项,与 regime 一样只从当日快照读,快照缺失为空字典)。PMS 按字段名取值、忽略未知键。"""
|
(环境段市场四项,与 regime 一样只从当日快照读,快照缺失为空字典)。PMS 按字段名取值、忽略未知键。"""
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
try:
|
try:
|
||||||
data, cached = _plan_cached(date, top, obs_top, theme_cap, bool(nocache), decision_id)
|
data, cached = _plan_cached(date, top, obs_top, theme_cap, bool(nocache), decision_id, include_user_candidates)
|
||||||
except (RuntimeError, ValueError, OSError) as e:
|
except (RuntimeError, ValueError, OSError) as e:
|
||||||
raise HTTPException(status_code=404, detail=str(e))
|
raise HTTPException(status_code=404, detail=str(e))
|
||||||
data = dict(data) # 下面几个键按请求写,不污染缓存里那一份
|
data = dict(data) # 下面几个键按请求写,不污染缓存里那一份
|
||||||
|
|
@ -271,11 +273,12 @@ def get_plan(request: Request, date: str | None = None, format: str = "json",
|
||||||
|
|
||||||
|
|
||||||
@app.get('/plan/check')
|
@app.get('/plan/check')
|
||||||
def check_plan_stock(code: str):
|
def check_plan_stock(code: str, include_user_candidates: bool = False):
|
||||||
"""采纳专用逐票读取。只读已发布计划,不装配、不查研究库。"""
|
"""采纳专用逐票读取。只读已发布计划,不装配、不查研究库。"""
|
||||||
from common import to_prefix
|
from common import to_prefix
|
||||||
try:
|
try:
|
||||||
return JSONResponse(content=plan_versions.stock_check(config.PLAN_SNAPSHOT_DIR, to_prefix(code)))
|
return JSONResponse(content=plan_versions.stock_check(config.PLAN_SNAPSHOT_DIR, to_prefix(code),
|
||||||
|
include_user_candidates=include_user_candidates))
|
||||||
except (OSError, ValueError, RuntimeError) as e:
|
except (OSError, ValueError, RuntimeError) as e:
|
||||||
raise HTTPException(status_code=503, detail=str(e))
|
raise HTTPException(status_code=503, detail=str(e))
|
||||||
|
|
||||||
|
|
@ -287,13 +290,15 @@ def refresh(date: str | None = None, key: str | None = None):
|
||||||
key=key, x_job_key=None)
|
key=key, x_job_key=None)
|
||||||
|
|
||||||
|
|
||||||
def _published_stock_rows(want, date, decision_id):
|
def _published_stock_rows(want, date, decision_id, include_user_candidates=False):
|
||||||
try:
|
try:
|
||||||
published = plan_versions.load(config.PLAN_SNAPSHOT_DIR, date, decision_id)
|
published = plan_versions.load(config.PLAN_SNAPSHOT_DIR, date, decision_id)
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
if decision_id or date:
|
if decision_id or date:
|
||||||
raise HTTPException(status_code=404, detail='指定计划版本不可用')
|
raise HTTPException(status_code=404, detail='指定计划版本不可用')
|
||||||
return {}, {}
|
return {}, {}
|
||||||
|
import user_candidates as uc
|
||||||
|
published = uc.consumer_view(published, include_user_candidates)
|
||||||
rows = {r['code']: dict(r, decision=bucket, source='published',
|
rows = {r['code']: dict(r, decision=bucket, source='published',
|
||||||
traceability=published.get('traceability') or 'legacy_unverified',
|
traceability=published.get('traceability') or 'legacy_unverified',
|
||||||
decision_version=published.get('decision'), date=published['date'],
|
decision_version=published.get('decision'), date=published['date'],
|
||||||
|
|
|
||||||
4
plan.py
4
plan.py
|
|
@ -1064,7 +1064,7 @@ def pick_rows(rows, n: int, theme_cap: int, uncapped_no_theme=None) -> list:
|
||||||
|
|
||||||
|
|
||||||
def from_snapshot(date: str | None = None, top: int = 20, obs_top: int = 10,
|
def from_snapshot(date: str | None = None, top: int = 20, obs_top: int = 10,
|
||||||
theme_cap: int = 5, decision_id=None) -> dict:
|
theme_cap: int = 5, decision_id=None, include_user_candidates=False) -> dict:
|
||||||
"""从当日 JSON 快照读计划,按请求参数截取。**不做任何装配、不查任何库。**
|
"""从当日 JSON 快照读计划,按请求参数截取。**不做任何装配、不查任何库。**
|
||||||
|
|
||||||
为什么要这条路(2026-09-10,台账 057): collect 每次请求都现场装配整池,实测三十三秒,
|
为什么要这条路(2026-09-10,台账 057): collect 每次请求都现场装配整池,实测三十三秒,
|
||||||
|
|
@ -1081,6 +1081,8 @@ def from_snapshot(date: str | None = None, top: int = 20, obs_top: int = 10,
|
||||||
ds = date or (decision_id[:10] if decision_id else plan_versions.latest_date(config.PLAN_SNAPSHOT_DIR))
|
ds = date or (decision_id[:10] if decision_id else plan_versions.latest_date(config.PLAN_SNAPSHOT_DIR))
|
||||||
path = os.path.join(config.PLAN_SNAPSHOT_DIR, f"plan_{ds}.json")
|
path = os.path.join(config.PLAN_SNAPSHOT_DIR, f"plan_{ds}.json")
|
||||||
snap = plan_versions.load(config.PLAN_SNAPSHOT_DIR, ds, decision_id)
|
snap = plan_versions.load(config.PLAN_SNAPSHOT_DIR, ds, decision_id)
|
||||||
|
import user_candidates as uc
|
||||||
|
snap = uc.consumer_view(snap, include_user_candidates)
|
||||||
if str(snap.get("date") or "") != str(ds):
|
if str(snap.get("date") or "") != str(ds):
|
||||||
raise RuntimeError(f"快照里的数据日 {snap.get('date')} 与请求的 {ds} 对不上: {path}")
|
raise RuntimeError(f"快照里的数据日 {snap.get('date')} 与请求的 {ds} 对不上: {path}")
|
||||||
full_main, full_obs = snap.get("main"), snap.get("observe")
|
full_main, full_obs = snap.get("main"), snap.get("observe")
|
||||||
|
|
|
||||||
|
|
@ -233,7 +233,7 @@ def publish(root, plan, inputs, params, *, cutoff_at, reason):
|
||||||
return p
|
return p
|
||||||
|
|
||||||
|
|
||||||
def stock_check(root, code):
|
def stock_check(root, code, include_user_candidates=False):
|
||||||
"""只读完整发布文件的一只股票。不存在与取数失败严格区分;不按展示名次裁剪。"""
|
"""只读完整发布文件的一只股票。不存在与取数失败严格区分;不按展示名次裁剪。"""
|
||||||
if not re.fullmatch(r'(SH|SZ|BJ)\d{6}', code):
|
if not re.fullmatch(r'(SH|SZ|BJ)\d{6}', code):
|
||||||
raise ValueError('股票代码无效')
|
raise ValueError('股票代码无效')
|
||||||
|
|
@ -260,6 +260,7 @@ def stock_check(root, code):
|
||||||
if (published.get('date') != day or not (published.get('decision') or {}).get('id')
|
if (published.get('date') != day or not (published.get('decision') or {}).get('id')
|
||||||
or not all(isinstance(published.get(b), list) for b in ('main', 'observe'))):
|
or not all(isinstance(published.get(b), list) for b in ('main', 'observe'))):
|
||||||
raise ValueError('完整发布计划不可核验')
|
raise ValueError('完整发布计划不可核验')
|
||||||
|
published = uc.consumer_view(published, include_user_candidates)
|
||||||
rows = {b: [r for r in published[b] if r.get('code') == code] for b in ('main', 'observe')}
|
rows = {b: [r for r in published[b] if r.get('code') == code] for b in ('main', 'observe')}
|
||||||
count = sum(map(len, rows.values()))
|
count = sum(map(len, rows.values()))
|
||||||
if count > 1:
|
if count > 1:
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,29 @@ class CandidateTests(unittest.TestCase):
|
||||||
api.add_user_candidates(None, PAYLOAD, x_job_key='bad')
|
api.add_user_candidates(None, PAYLOAD, x_job_key='bad')
|
||||||
self.assertFalse(Path(self.root, 'user_candidates.json').exists())
|
self.assertFalse(Path(self.root, 'user_candidates.json').exists())
|
||||||
|
|
||||||
|
def test_old_consumers_exclude_user_source_before_top_and_cache_is_separate(self):
|
||||||
|
import api
|
||||||
|
source={'id':'a'*32,'code':'SH600001'}
|
||||||
|
row={'code':'SH600001','score':250,'rank':1,'research_rank':1,'evidence':{},
|
||||||
|
'user_candidate':source,'user_required':True,'verdict':'候选'}
|
||||||
|
ordinary={'code':'SH600002','score':240,'rank':2,'research_rank':2,'evidence':{},'verdict':'候选'}
|
||||||
|
published={'date':DAY,'decision':{'id':'v-opt-in'},'main':[row,ordinary],'observe':[],
|
||||||
|
'user_candidates':[source],'candidates':[row,ordinary],'watch':[],
|
||||||
|
'counts':{'main':2,'observe':0}}
|
||||||
|
original=copy.deepcopy(published)
|
||||||
|
with patch.object(config,'PLAN_SNAPSHOT_DIR',self.root),patch.object(pv,'load',return_value=published):
|
||||||
|
default,_=api._plan_cached(DAY,1,0,0,True)
|
||||||
|
opted,_=api._plan_cached(DAY,1,0,0,True,include_user_candidates=True)
|
||||||
|
again,hit=api._plan_cached(DAY,1,0,0,False)
|
||||||
|
self.assertEqual(default['main'][0]['code'],'SH600002')
|
||||||
|
self.assertEqual(opted['main'][0]['code'],'SH600001')
|
||||||
|
self.assertEqual(default,again)
|
||||||
|
self.assertTrue(hit)
|
||||||
|
self.assertNotIn('user_candidates',default)
|
||||||
|
self.assertEqual(default['counts']['main'],1)
|
||||||
|
self.assertEqual(len(default['candidates']),1)
|
||||||
|
self.assertEqual(original,published)
|
||||||
|
|
||||||
def test_revision_add_remove_replay_and_frozen_morning(self):
|
def test_revision_add_remove_replay_and_frozen_morning(self):
|
||||||
codes = ['SH600001', 'SH600002']
|
codes = ['SH600001', 'SH600002']
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
|
|
@ -109,6 +132,8 @@ class CandidateTests(unittest.TestCase):
|
||||||
self.assertEqual(rows['SH600001']['score'],240.)
|
self.assertEqual(rows['SH600001']['score'],240.)
|
||||||
self.assertIsNone(rows['SH600003']['score'])
|
self.assertIsNone(rows['SH600003']['score'])
|
||||||
self.assertNotIn('tier',rows['SH600003'])
|
self.assertNotIn('tier',rows['SH600003'])
|
||||||
|
self.assertFalse(pv.stock_check(self.root,'SH600003')['found'])
|
||||||
|
self.assertTrue(pv.stock_check(self.root,'SH600003',include_user_candidates=True)['found'])
|
||||||
json.dumps(published,allow_nan=False)
|
json.dumps(published,allow_nan=False)
|
||||||
self.assertIn('SH600003', Path(self.root, f'plan_{DAY}.md').read_text())
|
self.assertIn('SH600003', Path(self.root, f'plan_{DAY}.md').read_text())
|
||||||
self.assertEqual(pv.load(self.root,DAY,morning=True),frozen)
|
self.assertEqual(pv.load(self.root,DAY,morning=True),frozen)
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,24 @@ import plan_versions as pv
|
||||||
BJ = ZoneInfo('Asia/Shanghai')
|
BJ = ZoneInfo('Asia/Shanghai')
|
||||||
|
|
||||||
|
|
||||||
|
def consumer_view(published, include_user_candidates=False):
|
||||||
|
"""旧调用方只取系统来源;显式声明支持新来源后才返回人工候选。"""
|
||||||
|
if include_user_candidates or not published.get('user_candidates'):
|
||||||
|
return published
|
||||||
|
out = dict(published)
|
||||||
|
out.pop('user_candidates', None)
|
||||||
|
for bucket in ('main', 'observe', 'main_shown', 'observe_shown', 'candidates', 'watch'):
|
||||||
|
if bucket in out:
|
||||||
|
out[bucket] = [{k: v for k, v in r.items() if k not in ('user_candidate', 'user_required')}
|
||||||
|
for r in out[bucket] if not r.get('user_required')]
|
||||||
|
if 'counts' in out:
|
||||||
|
out['counts'] = dict(out['counts'], main=len(out.get('main', [])), observe=len(out.get('observe', [])))
|
||||||
|
if 'card_counts' in out:
|
||||||
|
rows = out.get('main', []) + out.get('observe', [])
|
||||||
|
out['card_counts'] = {v: sum(r.get('verdict') == v for r in rows) for v in out['card_counts']}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def normalize(value):
|
def normalize(value):
|
||||||
value = str(value or '').strip().upper()
|
value = str(value or '').strip().upper()
|
||||||
if re.fullmatch(r'\d{6}\.(SH|SZ)', value):
|
if re.fullmatch(r'\d{6}\.(SH|SZ)', value):
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue