From ffc282652b19793755369861ed3b24edd51ce8f6 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Tue, 1 Dec 2026 21:53:06 +0800 Subject: [PATCH 01/11] docs: add pstack performance and engineering skills to AGENTS.md --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index fd55ba2..75fda76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ Stock analysis, screening, and backtesting live in the shared Python CLIs under 3. **Work in verifiable units.** For multi-step work, set the dependency order and verification check for each unit before editing, and verify each unit before building on it. Follow [ponytail](https://github.com/DietrichGebert/ponytail) by reusing [scripts/tool-calls.mjs](scripts/tool-calls.mjs), [scripts/venv-python.mjs](scripts/venv-python.mjs), [tools/_subproc.py](tools/_subproc.py), and [tests/conftest.py](tests/conftest.py) instead of adding parallel helpers or dependencies. 4. **Prove the change.** Rerun the failing reproduction and exercise the real affected entry point. Report the exact commands, observed results, and the host, OS, install mode, or artifact checked. When a target such as Windows, macOS, or an installed host is unavailable, run the nearest local check and state what remains unverified. -When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. Keep specs, review notes, and external skill files out of commits. +When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. When the [pstack skills](https://github.com/cursor/plugins/tree/main/pstack/) are installed locally, use `benchmark-checklist` and `principle-explain-the-number` before trusting or reporting performance measurements (name the limiter from profiles or counters, verify outputs and error counts, and report run count, median, and range), and use `blast-radius` for cross-cutting changes alongside `principle-fix-root-causes`, `principle-subtract-before-you-add`, and `principle-prove-it-works`. Keep specs, review notes, and external skill files out of commits. ## Local setup and verification From 342937607423f1e80fc33ec9ac3271b705d8de99 Mon Sep 17 00:00:00 2001 From: Weaxs <459312872@qq.com> Date: Tue, 1 Dec 2026 21:53:06 +0800 Subject: [PATCH 02/11] perf: batch quotes/calendar, pool HTTP connections, parallelize I/O, and speed up hot paths --- dsh/dashboard.ts | 97 ++++++++++-- dsh/web/app.ts | 3 + tests/test_dsh_dashboard.ts | 29 +++- tests/test_market_review.py | 13 ++ tests/test_risk_screening.py | 29 ++++ tests/test_search_intel.py | 25 +++ tests/test_signal_tracker.py | 10 ++ tests/test_stock_data.py | 116 ++++++++++++++ tests/test_subproc.py | 26 +++ tests/test_trading_calendar.py | 35 +++++ tools/_cache.py | 15 +- tools/_subproc.py | 36 +++++ tools/backtest.py | 74 ++++++--- tools/credit_data.py | 14 +- tools/gather.py | 5 +- tools/market_regime.py | 14 +- tools/market_review.py | 10 +- tools/risk_screening.py | 109 ++++++++----- tools/screener.py | 6 +- tools/search_intel.py | 107 ++++++++----- tools/sec_edgar.py | 6 +- tools/signal_tracker.py | 25 ++- tools/stateless_analysis.py | 112 +++++++++++-- tools/stock_data.py | 280 ++++++++++++++++++++++----------- tools/technical.py | 23 ++- tools/trading_calendar.py | 100 +++++++++--- tools/value_data.py | 34 ++-- tools/watchlist_context.py | 25 ++- 28 files changed, 1068 insertions(+), 310 deletions(-) diff --git a/dsh/dashboard.ts b/dsh/dashboard.ts index b935889..dc0ad7d 100644 --- a/dsh/dashboard.ts +++ b/dsh/dashboard.ts @@ -357,10 +357,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand } function quoteJob(symbol: string, priority: number): Job { + const region = watchRegion(symbol); return { - key: `quote:${symbol}`, kind: "quote", region: watchRegion(symbol), priority, batched: true, + key: `quote:${symbol}`, kind: "quote", region, priority, batched: true, + // Per-region batches: slow overseas/fund/advisor quotes must not hold up A-share quotes. run: async () => { - const value = await batched("quotes", "all", symbol, priority) as Record | null; + const value = await batched("quotes", region, symbol, priority) as Record | null; if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("报价数据格式不正确"); if (value.error) throw new Error(safeError(value.error, "报价暂不可用")); return { ...value, symbol }; @@ -382,16 +384,43 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand }; } + const pendingPhases: Array<{ market: string; resolve: (value: unknown) => void; reject: (error: unknown) => void }> = []; + let phasesScheduled = false; + function batchedPhase(region: Region): Promise { + const market = region.toUpperCase(); + return new Promise((resolve, reject) => { + pendingPhases.push({ market, resolve, reject }); + if (!phasesScheduled) { + phasesScheduled = true; + queueMicrotask(flushPhases); + } + }); + } + function flushPhases() { + phasesScheduled = false; + const batch = pendingPhases.splice(0); + const markets = batch.map(item => item.market).join(","); + limiter.run(0, () => py("trading_calendar.py", ["phases", markets], 10_000)).then( + map => { + if (!map || typeof map !== "object" || Array.isArray(map) || "error" in map) { + throw new Error("交易阶段暂不可用"); + } + const record = map as Record; + for (const item of batch) { + const value = record[item.market] as Record | undefined; + if (!value || typeof value !== "object" || value.error) item.reject(new Error("交易阶段暂不可用")); + else item.resolve(value); + } + }, + ).catch(error => batch.forEach(item => item.reject(error))); + } + function jobs(symbols: string[]): Job[] { const list: Job[] = []; for (const region of REGIONS) { list.push({ - key: `phase:${region}`, kind: "phase", region, priority: 0, - run: async () => { - const value = await py("trading_calendar.py", ["phase", region.toUpperCase()], 10_000) as Record; - if (!value || typeof value !== "object" || value.error) throw new Error("交易阶段暂不可用"); - return value; - }, + key: `phase:${region}`, kind: "phase", region, priority: 0, batched: true, + run: () => batchedPhase(region), }); } for (const symbol of symbols) list.push(quoteJob(symbol, 1)); @@ -482,8 +511,32 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand return task; } + const assetCache = new Map(); + let watchlistCache: { ino: bigint; mtimeNs: bigint; size: bigint; symbols: string[] } | null = null; + function cachedWatchlist(): string[] { + let st; + try { + st = statSync(watchlistFile, { bigint: true }); + } catch (error) { + watchlistCache = null; + if ((error as { code?: string }).code === "ENOENT") return []; + throw new Error("无法读取自选股文件"); + } + if (watchlistCache && watchlistCache.ino === st.ino && watchlistCache.mtimeNs === st.mtimeNs && watchlistCache.size === st.size) { + return watchlistCache.symbols; + } + try { + const symbols = readWatchlist(watchlistFile); + watchlistCache = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, symbols }; + return symbols; + } catch (error) { + watchlistCache = null; + throw error; + } + } + function currentSymbols(): string[] { - try { return readWatchlist(watchlistFile); } catch { return []; } + try { return cachedWatchlist(); } catch { return []; } } /** Start every due job; resolves when the jobs started by this tick finish. */ @@ -548,7 +601,7 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand function snapshot(region: Region) { lastSeen = Date.now(); viewedRegion = region; - const symbols = readWatchlist(watchlistFile); + const symbols = cachedWatchlist(); kick(); void checkLatest(); return { @@ -616,11 +669,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand return sendJson(res, 202, { ok: true, pending: limiter.queued }); } if (rest === "/api/watchlist") { - if (req.method === "GET") return sendJson(res, 200, { symbols: readWatchlist(watchlistFile) }); + if (req.method === "GET") return sendJson(res, 200, { symbols: cachedWatchlist() }); if (req.method === "POST") { const body = await readJson(req); if (!body?.op) throw new HttpError(400, "必须指定 add 或 remove 操作"); const saved = await updateWatchlist(watchlistFile, body.op, body.symbols); + watchlistCache = null; kick(); return sendJson(res, 200, { symbols: saved }); } @@ -653,19 +707,32 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand const asset = STATIC_FILES.get(rest as "/" | "/app.js" | "/style.css"); if (!asset) return sendJson(res, 404, { error: "Not found" }); const [file, contentType] = asset; - let body: Buffer; + const assetPath = join(webDir, file); + let entry = assetCache.get(file); try { - body = readFileSync(join(webDir, file)); + const st = statSync(assetPath, { bigint: true }); + if (!entry || entry.ino !== st.ino || entry.mtimeNs !== st.mtimeNs || entry.size !== st.size) { + const body = readFileSync(assetPath); + entry = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, body, etag: `"${st.ino}-${st.mtimeNs}-${st.size}"` }; + assetCache.set(file, entry); + } } catch { + assetCache.delete(file); return sendJson(res, 404, { error: "Not found" }); } + if (req.headers["if-none-match"] === entry.etag) { + res.writeHead(304, { etag: entry.etag, "cache-control": "no-cache" }); + res.end(); + return; + } res.writeHead(200, { "content-type": contentType, - "content-length": body.length, + "content-length": entry.body.length, + etag: entry.etag, "cache-control": "no-cache", "x-content-type-options": "nosniff", }); - res.end(req.method === "HEAD" ? undefined : body); + res.end(req.method === "HEAD" ? undefined : entry.body); } catch (error) { if (error instanceof HttpError) return sendJson(res, error.status, { error: error.message }); const message = error instanceof Error && !/[/\\]/.test(error.message) ? error.message : "仪表盘服务暂时不可用"; diff --git a/dsh/web/app.ts b/dsh/web/app.ts index 7ac27c3..206e0d5 100644 --- a/dsh/web/app.ts +++ b/dsh/web/app.ts @@ -743,9 +743,12 @@ function renderRows(flash: Map) { return; } if (!state.snap.watchlist.length) { + for (const key of sparkCache.keys()) if (key.startsWith("watch:")) sparkCache.delete(key); body.append(emptyRow()); return; } + const activeWatchKeys = new Set(state.snap.watchlist.map(item => `watch:${item.symbol}`)); + for (const key of sparkCache.keys()) if (key.startsWith("watch:") && !activeWatchKeys.has(key)) sparkCache.delete(key); for (const item of items!) { const quote = item.quote; const price = watchPrice(item); diff --git a/tests/test_dsh_dashboard.ts b/tests/test_dsh_dashboard.ts index 9607aca..d211fee 100644 --- a/tests/test_dsh_dashboard.ts +++ b/tests/test_dsh_dashboard.ts @@ -97,7 +97,14 @@ function fakePython(options: { phase?: string; fail?: (script: string, args: str ? { error: "secret stderr at /private/provider.py" } : [{ date: "2026-01-01", close: 10, open: 9 }, { date: "2026-01-02", close: 11 }, { date: "2026-01-03", close: "bad" }])); } - if (script === "trading_calendar.py") return JSON.stringify({ market: args[1], phase: options.phase ?? "post_market", phase_label: "盘后" }); + if (script === "trading_calendar.py") { + if (args[0] === "phases") { + return JSON.stringify(Object.fromEntries( + args[1].split(",").map(market => [market, { market, phase: options.phase ?? "post_market", phase_label: "盘后" }]), + )); + } + return JSON.stringify({ market: args[1], phase: options.phase ?? "post_market", phase_label: "盘后" }); + } if (args[0] === "quote") return JSON.stringify({ symbol: args[1], name: `Name ${args[1]}`, price: 100, change_pct: 1.2, high: 101, low: 99 }); if (args[0] === "market_indices") return JSON.stringify([{ code: "^HSI", name: "恒生指数", price: 20000, change_pct: -0.5 }]); if (args[0] === "sector_rankings") return JSON.stringify({ top: [{ name: "元件", change_pct: 5 }], bottom: [{ name: "白酒", change_pct: -3 }] }); @@ -310,18 +317,22 @@ try { await handler.tick(); await handler.settle(); assert(py.maxActive() <= 4, `python concurrency ${py.maxActive()} exceeded four`); - assert.equal(py.calls.filter(call => call.startsWith("stock_data.py:quotes ")).length, 1, "one process serves every due quote"); - assert(py.calls.some(call => call.startsWith("stock_data.py:quotes ") && call.endsWith(" --watchlist"))); + const quoteBatches = py.calls.filter(call => call.startsWith("stock_data.py:quotes ")); + assert.equal(quoteBatches.length, 3, "one quote process per active watchlist region (cn, us, hk)"); + assert(quoteBatches.every(call => call.endsWith(" --watchlist"))); + const cnQuoteBatch = quoteBatches.find(call => call.includes("600519")); + assert(cnQuoteBatch && cnQuoteBatch.includes("sh000001") && !cnQuoteBatch.includes("AAPL"), "CN stock and indices share one batch separate from overseas symbols"); for (const symbol of ["600519", "AAPL", "00700.HK", "sh000001"]) assert.equal(quoted(py.calls, symbol), 1, `missing quote ${symbol}`); - assert.equal(py.timeouts.get(py.calls.find(call => call.startsWith("stock_data.py:quotes "))!), 40_000, "the batch outlives the CLI's own 30 s per-row deadline"); + assert(quoteBatches.every(call => py.timeouts.get(call) === 40_000), "the batch outlives the CLI's own 30 s per-row deadline"); for (const expected of [ "stock_data.py:market_indices --region hk", "stock_data.py:sector_rankings --top 5 --direction both --board-type industry", "stock_data.py:market_stats --market A", "stock_data.py:market_stats --market HK", "stock_data.py:market_stats --market US", - "trading_calendar.py:phase JP", + "trading_calendar.py:phases CN,HK,US,JP,KR,TW", ]) assert(py.calls.includes(expected), `missing ${expected}`); + assert.equal(py.calls.filter(call => call.startsWith("trading_calendar.py:")).length, 1, "one process serves every due market phase"); assert(!py.calls.includes("stock_data.py:market_indices --region cn"), "A-share indices use direct quotes"); assert.equal(py.timeouts.get("stock_data.py:market_stats --market US"), 60_000); const klines = py.calls.filter(call => call.startsWith("stock_data.py:klines ")); @@ -412,7 +423,7 @@ try { const failFile = join(temp, "fail", "watchlist.json"); writeWatchlist(failFile, ["AAPL"]); let failing = false; - const flaky = fakePython({ fail: (_script, args) => failing && args[1] === "AAPL" }); + const flaky = fakePython({ fail: (_script, args) => failing && (args[0] === "quote" || args[0] === "kline") && args[1] === "AAPL" }); const failHandler = createDashboardHandler({ runPy: flaky.runPy, watchlistFile: failFile, webDir }); await failHandler.tick(); await failHandler.settle(); @@ -558,6 +569,12 @@ try { assert.equal(page.status(), 200); assert.match(page.body(), /股票仪表盘/); assert.match(page.headers()["content-type"] as string, /text\/html/); + assert(typeof page.headers().etag === "string", "static assets emit an ETag"); + const cachedReq = get("/stock-analysis/"); + cachedReq.headers["if-none-match"] = page.headers().etag as string; + const notModified = await call(handler, cachedReq); + assert.equal(notModified.status(), 304, "matching If-None-Match returns 304 without body"); + assert.equal(notModified.body(), ""); assert.match(page.body(), /