AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
docs(solutions): compound three verified learnings from the PR #816 discovery rebuild
Matt Van Horn4b027919c76e
diff --git a/CONCEPTS.md b/CONCEPTS.mdindex 62b3c59a..e386c5fd 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -39,3 +39,29 @@ The research flow available with no API keys: source data is gathered by scrapin### Comment-enrichment slotsThe small, depth-dependent budget of Reddit posts whose comments get fetched in the Keyless path. Slot selection is relevance-aware: posts that pass Entity grounding claim slots first, so the budget is not spent on high-engagement posts that final ranking will demote anyway.++## Discovery++### Discovery++The topic-less research mode: instead of researching a named topic, it finds what is worth researching. Runs in two stages - a listing sweep Nominates candidate topics, then each Nomination gets an Enrichment pass - and every surviving topic must clear the Confidence floor before it is shown. Global Discovery (no domain given) sweeps every river feed's own hot list with no keyword gate; domain Discovery scopes and keyword-gates the sweep.++### Nomination++A named candidate topic produced by Discovery's listing sweep: clustered items from the river feeds, given a concise name and a cheap seed-velocity rank. A Nomination is only a candidate - its seed rank decides which topics deserve an Enrichment pass and the display order of survivors; the Confidence floor judgment and the displayed velocity score are computed from the enriched evidence, never the seed score.++### Enrichment pass++A full research-pipeline run executed on one Nomination's topic name during Discovery. This is what gives a trend card the whole multi-source corpus (community comments, prediction markets, keyword-driven sources that have no hot-list of their own) instead of thin listing evidence. Enrichment passes run in parallel against a wall-clock budget; a pass that fails or outruns the budget downgrades its topic to nomination-only evidence, never fails the run.++### Confidence floor++The absolute evidence bar every Discovery topic must clear before it may rank: an engagement junk-gate first, then either independent cross-source corroboration or a genuinely strong single-source spike. The floor is absolute, not relative to the current pool - a relative bar would degrade with the pool, which is the failure it exists to prevent. Its thresholds are deliberately tunable; the behavior contract is only that sub-floor evidence never ranks.++### Nothing-solid++The honest empty outcome of a Discovery run in which zero topics cleared the Confidence floor. A first-class result, not an error: the run reports that nothing in the window was strong enough to call a trend, and names the closest sub-floor candidate (the weak signal) so the user knows where the signal petered out. Rendering junk instead of Nothing-solid is the named failure this outcome replaced.++## Flagged ambiguities++- "Enrichment" is used for two distinct things: Comment-enrichment slots (fetching comments for already-ranked Reddit posts in the Keyless path) and Discovery's Enrichment pass (a full research run per Nomination). Context disambiguates; prefer the full term when writing.diff --git a/docs/solutions/conventions/argparse-optional-value-flag-dispatch-truthiness.md b/docs/solutions/conventions/argparse-optional-value-flag-dispatch-truthiness.mdnew file mode 100644index 00000000..8d42a1d9--- /dev/null+++ b/docs/solutions/conventions/argparse-optional-value-flag-dispatch-truthiness.md@@ -0,0 +1,185 @@+---+title: "Optional-value argparse flags: dispatch on 'is not None', never truthiness"+date: 2026-07-12+category: conventions+module: last30days-cli+problem_type: convention+component: tooling+severity: medium+applies_when:+ - "Retrofitting an optional value onto an existing flag (nargs='?' + const), where old dispatch sites were written for a two-state flag"+ - "Any flag or config key where a falsy value ('', 0, []) is a meaningful present-value distinct from absence"+ - "Dependent/modifier flags whose behavior only applies when an anchor flag is present"+tags:+ - argparse+ - nargs-optional+ - truthiness+ - cli-flags+ - dispatch+ - dependent-flags+ - silent-failure+ - sentinel-values+related_components:+ - testing_framework+---++# Optional-value argparse flags: dispatch on `is not None`, never truthiness++## Context++PR #816 retrofitted an optional value onto the `--discover` flag in `skills/last30days/scripts/last30days.py`:++```python+parser.add_argument(+ "--discover",+ metavar="DOMAIN",+ nargs="?",+ const="",+ default=None,+ help=(+ "Sweep river listings and rank the topics accelerating in a domain; "+ "each survivor gets a full research pass. Bare --discover (no domain) "+ "runs global trending across every feed's hot list"+ ),+)+```++With `nargs="?"` plus `const=""` plus `default=None`, the flag is deliberately three-state:++- flag absent -> `args.discover is None` -> normal research run+- bare `--discover` -> `args.discover == ""` -> global trending sweep (empty domain)+- `--discover X` -> `args.discover == "X"` -> domain-scoped discovery++The near-miss: the pre-existing dispatch was `if args.discover:`. Under Python truthiness, `""` and `None` are both falsy, so bare `--discover` would have been indistinguishable from no flag at all. The headline new mode of the PR (global trending) would simply never fire - the run would silently route into the normal-research path with no error, no warning, and no failing test unless a test exercised the bare form specifically. This was caught during development and the dispatch was changed to key on flag presence.++A second, related trap was caught in PR review (Greptile P2): the dependent flag `--discover-shallow` was accepted without `--discover` and silently no-opped into a full research run - the user asked for a fast, thin sweep and got a slow, full one. It was fixed with an explicit guard that errors loudly (exit 2).++## Guidance++1. With `nargs="?"` + `const`, the None/const/value trichotomy IS the contract: absent = `None`, bare flag = the `const` value, valued = the user's string. Dispatch on `args.flag is not None` (flag present), never on truthiness. When retrofitting optionality onto an existing flag, grep EVERY existing reference to `args.<flag>` - the old references were written when the flag was two-state and any `if args.flag:` among them is now a latent misroute.++2. Put a comment at the dispatch site explaining why it uses `is not None`. `if args.flag:` looks like the idiomatic form, and a future "simplification" pass will happily rewrite the correct check back into the bug. The repo's dispatch carries exactly this comment (`skills/last30days/scripts/last30days.py`):++ ```python+ # Bare --discover (no domain) is global trending, so the dispatch keys on+ # "flag present" (is not None), never on the domain string's truthiness.+ if args.discover is not None:+ ```++3. Dependent/modifier flags (`--x-modifier` that only applies with `--x`) must error loudly when their anchor flag is absent - never silently no-op. A silent no-op means the user asked for one mode and got another with zero feedback. Reject with a clear message and a nonzero exit:++ ```python+ if args.discover_shallow:+ # Without --discover this flag would silently no-op into a full+ # research run - reject it instead of ignoring the requested mode.+ sys.stderr.write(+ "[last30days] --discover-shallow only applies to --discover runs; "+ "add --discover [domain] or drop the flag.\n"+ )+ return 2+ ```++4. Pin both behaviors with CLI-level subprocess tests. Unit tests of the parser alone would not have caught the misroute, because parsing was correct - the bug lived in dispatch. The tests must run the real entry point end to end: one asserting the bare form reaches the new mode, one asserting the orphaned dependent flag is rejected (see Examples).++## Why This Matters++The failure mode is silent misrouting, which is the worst kind: the feature ships, `--help` documents the bare form, and every invocation of it quietly runs the wrong mode. There is no exception, no error message, no test failure - the output is a plausible-looking result from the wrong pipeline. Nothing surfaces the bug unless a test (or an alert user) exercises the bare form specifically and checks which mode actually ran. The same is true of the dependent-flag no-op: `--discover-shallow` without `--discover` produced a valid full research run, just not the one the user asked for.++## When to Apply++- Retrofitting an optional value onto an existing flag (`action="store_true"` or a plain valued option becoming `nargs="?"`): audit every dispatch site that reads the flag.+- Any flag where a falsy value (`""`, `0`, `[]`) is a MEANINGFUL present-value distinct from absence - the sentinel-vs-truthiness distinction applies beyond argparse (env vars, config keys, JSON fields).+- Dependent/modifier flags whose behavior only applies when an anchor flag is present.++## Examples++Before (the near-miss - conflates bare flag with no flag):++```python+if args.discover: # '' and None are both falsy: bare --discover falls through+ return _run_discover(args, config)+```++After (`skills/last30days/scripts/last30days.py`, with the drift-guard comment):++```python+# Bare --discover (no domain) is global trending, so the dispatch keys on+# "flag present" (is not None), never on the domain string's truthiness.+if args.discover is not None:+ if topic:+ sys.stderr.write(+ "[last30days] --discover supplies the domain and cannot be combined "+ "with a positional topic.\n"+ )+ return 2+ if args.drill:+ sys.stderr.write("[last30days] --discover and --drill are mutually exclusive.\n")+ return 2+ return _run_discover(args, config)+```++The dependent-flag guard immediately below the dispatch:++```python+if args.discover_shallow:+ # Without --discover this flag would silently no-op into a full+ # research run - reject it instead of ignoring the requested mode.+ sys.stderr.write(+ "[last30days] --discover-shallow only applies to --discover runs; "+ "add --discover [domain] or drop the flag.\n"+ )+ return 2+```++The two pinning tests in `tests/test_discover_mode.py`, both running the real CLI via subprocess:++```python+def test_discovery_cli_bare_discover_is_global_trending():+ """Bare --discover (no domain) must run global trending, not error."""+ result = subprocess.run(+ [+ sys.executable,+ "skills/last30days/scripts/last30days.py",+ "--discover",+ "--mock",+ "--emit=json",+ ],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, result.stderr+ payload = json.loads(result.stdout)+ assert payload["kind"] == "discovery"+ assert payload["domain"] == ""+ assert payload["outcome"] in {"ok", "nothing-solid"}+++def test_discovery_cli_rejects_shallow_without_discover():+ """--discover-shallow on a normal topic run must error, not silently no-op+ into a full research pass (P2 from PR #816 review)."""+ result = subprocess.run(+ [+ sys.executable,+ "skills/last30days/scripts/last30days.py",+ "AI agents",+ "--discover-shallow",+ "--mock",+ ],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 2+ assert "--discover-shallow only applies to --discover runs" in result.stderr+```++The first test asserts not just exit 0 but that the discovery pipeline actually ran (`payload["kind"] == "discovery"`, `payload["domain"] == ""`) - the exact property the truthiness bug would have violated. Source: PR #816 (last30days-skill).++## Related++- [Ranked-output confidence floor + honest empty state](../design-patterns/ranked-output-confidence-floor-honest-empty-state.md) - sibling lesson from the same PR #816 discover rebuild (ranking quality).+- [Non-daemon executor threads defeat wall-clock budgets](../logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.md) - sibling lesson from PR #816, same lesson class: a discover-mode defect that result-oriented unit tests structurally cannot catch (process lifetime there, bare-flag vs flag-absent conflation here).+- [PR #816](https://github.com/mvanhorn/last30days-skill/pull/816) - the discovery rebuild that introduced the three-state `--discover` flag (released v3.14.0).diff --git a/docs/solutions/design-patterns/ranked-output-confidence-floor-honest-empty-state.md b/docs/solutions/design-patterns/ranked-output-confidence-floor-honest-empty-state.mdnew file mode 100644index 00000000..c3f53e87--- /dev/null+++ b/docs/solutions/design-patterns/ranked-output-confidence-floor-honest-empty-state.md@@ -0,0 +1,179 @@+---+title: "Ranked-output features need an explicit confidence floor with an honest empty state"+date: 2026-07-12+category: design-patterns+module: discover-trending+problem_type: design_pattern+component: tooling+severity: medium+applies_when:+ - "Any feature that ranks and displays top-N results from variable-quality inputs (search, trending, recommendations, discovery)"+ - "Quiet or over-broad query domains where feeds return thin or noisy data"+symptoms:+ - "Top-N ranker emits near-zero-engagement items (e.g., five 1-like tweets) as a trend list because top-N has no notion of 'none of this is good enough'"+resolution_type: code_fix+tags:+ - ranking+ - confidence-floor+ - empty-state+ - top-n+ - discovery+ - trending+ - signal-quality+ - corroboration+related_components:+ - "skills/last30days/scripts/lib/rerank.py"+---++# Ranked-output features need an explicit confidence floor with an honest empty state++## Context++The `--discover` trending feature sweeps listing feeds (r/all, Hacker News front page, Digg, X), clusters what it finds into candidate topics, and emits the top topics by an engagement-velocity score. The selection was purely relative: `run_discover()` in `skills/last30days/scripts/lib/pipeline.py` computed `topic_limit = max(5, min(10, limit))` and took the top N clusters by score, regardless of whether the Nth-best (or even the 1st-best) was any good.++On quiet or overly broad domains the feeds return thin, noisy data, and a relative ranker has no way to say so. The named failure (2026-07-12): `/last30days --discover "sports"` returned five single-source tweets with 1 like each - a Wii Sports nostalgia thread, a kids-travel-sports burnout post, a manga review that mentioned sports - presented with straight-faced ranks 1 through 5 as a "trend list". Every stage worked as designed. The sweep ran, the clusterer clustered, the scorer scored. The problem is structural: a top-N ranker ranks noise against noise when inputs are thin. Relative ranking cannot express "nothing here is good enough to show a user"; that requires an absolute gate the pipeline did not have.++## Guidance++The pattern shipped in PR #816 (merged, v3.14.0) has four parts. Apply all four when building any ranked-output surface.++### 1. Put an absolute floor in front of the relative ranker++Before a candidate is allowed to compete on relative score, it must clear an absolute evidence bar. The floor lives in `skills/last30days/scripts/lib/rerank.py`:++```python+FLOOR_MIN_ENGAGEMENT = 25.0+FLOOR_MIN_SOURCES = 2+FLOOR_SINGLE_SOURCE_ENGAGEMENT = 200.0+++def passes_discovery_floor(+ *,+ source_count: int,+ engagement_total: float,+ item_count: int,+) -> bool:+ """Whether a discovery topic's evidence is strong enough to show a user.++ Below this floor the honest output is "nothing solid this window", not a+ ranked list of whatever survived the sweep.+ """+ if item_count <= 0 or engagement_total < FLOOR_MIN_ENGAGEMENT:+ return False+ if source_count >= FLOOR_MIN_SOURCES:+ return True+ return engagement_total >= FLOOR_SINGLE_SOURCE_ENGAGEMENT+```++The first check is the junk gate: `FLOOR_MIN_ENGAGEMENT = 25.0` means a 1-like tweet can never rank, no matter how empty the field is. The floor is judged per topic inside `run_discover()` (`skills/last30days/scripts/lib/pipeline.py`), before the topic is appended and before `topic_limit` is consulted - sub-floor evidence never enters the ranked list at all.++### 2. Make the clearing criteria composite: corroboration OR a genuinely strong spike++A single threshold is either too strict (kills real single-source stories) or too loose (lets corroborated-but-tiny noise through). The floor uses two independent ways to clear, after the junk gate:++- Cross-source corroboration: appearing on `FLOOR_MIN_SOURCES = 2` or more independent feeds clears with only modest engagement. Two feeds independently surfacing the same story is signal in itself.+- A strong single-source spike: `FLOOR_SINGLE_SOURCE_ENGAGEMENT = 200.0`. A 1,600-point single-source HN thread is a real story; a 30-upvote single-source meme is not.++The regression tests in `tests/test_discover_floor.py` pin both edges of this policy directly (`test_passes_discovery_floor_policy`): `floor(source_count=2, engagement_total=30, item_count=2)` clears, `floor(source_count=1, engagement_total=100, item_count=3)` does not, `floor(source_count=1, engagement_total=1600, item_count=1)` does.++### 3. Make honest emptiness a first-class outcome, and name the nearest miss++When zero topics survive the floor, the pipeline does not error, does not pad, and does not lower the bar. `run_discover()` sets `outcome = "ok" if topics else "nothing-solid"` on the `DiscoveryReport`, and while filtering it remembers the highest-scoring sub-floor candidate as `weak_signal` so the empty result can still say what came closest:++```python+if not rerank.passes_discovery_floor(+ source_count=len(sources),+ engagement_total=native_total,+ item_count=len(evidence_items),+):+ # Sub-floor evidence never ranks; remember what came closest so a+ # nothing-solid brief can still name the strongest weak signal.+ if weak_signal is None or score > weak_signal[0]:+ weak_signal = (score, entry.nomination.name)+ continue+```++The renderer (`render_discovery()` in `skills/last30days/scripts/lib/render.py`) presents this as a deliberate answer, not a failure:++```python+if report.outcome == "nothing-solid":+ lines.extend([+ "**Nothing solid this window.** No topic cleared the confidence "+ "floor - not enough cross-source confirmation or engagement to "+ "call anything a trend, and ranked noise would be worse than an "+ "honest empty result.",+ "",+ ])+ if report.weak_signal:+ lines.extend([+ f"Closest weak signal: {report.weak_signal} (sub-floor; "+ "single-source or too little engagement).",+ "",+ ])+```++Naming the weak signal matters: it tells the user the sweep actually ran and looked at real data, and it gives them a thread to pull ("closest weak signal: X" often suggests the narrower query that would work). There is also a soft middle state - if some topics clear but fewer than five, `run_discover()` emits a warning ("Fewer than five topic clusters cleared the confidence floor this window") rather than padding the list to the minimum.++### 4. Pin the failing corpus as a regression test++The exact junk corpus that produced the bad output is frozen in `test_junk_corpus_returns_nothing_solid_not_ranked_noise` in `tests/test_discover_floor.py`: five single-source 1-like tweets on the "sports" domain, asserting `report.topics == []`, `report.outcome == "nothing-solid"`, a non-None `weak_signal`, and a "confidence floor" warning. Sibling tests pin the other side so the floor cannot silently become a wall: a 1,084-point HN thread ranks (`test_strong_single_source_spike_clears_floor`), a mixed corpus keeps the strong story and drops the junk (`test_mixed_corpus_emits_only_floor_clearing_topics`), and enriched topics are judged on their enriched evidence, not their thin seed (`test_enriched_evidence_is_judged_not_seed_evidence`).++## Why This Matters++Trust in a ranked surface is asymmetric. Users cannot see the corpus behind the ranking; they can only judge the output. One junk trend list - five 1-like tweets dressed up with ranks, velocity scores, and momentum labels - teaches a user that the feature is garbage, and they generalize instantly: if it confidently ranked noise once, every future list is suspect. The presentation makes it worse, because ranking machinery (rank numbers, scores, "why spiking" prose) signals confidence the evidence never had.++Honest emptiness does the opposite. "Nothing solid this window" plus a named weak signal tells the user three things at once: the sweep ran, the bar is real, and here is roughly where the signal petered out. That preserves trust in every future non-empty list (topics that do appear are known to have cleared an absolute bar - the renderer even badges cross-source topics with "confirmed across N sources") and it invites a narrower, more productive follow-up query instead of a shrug. The empty state is a feature, not an apology.++## When to Apply++Any top-N surface over variable-quality inputs, where the input pool can be thin, noisy, or empty and the ranker will still dutifully order whatever it gets:++- Search and retrieval results ("no good matches" beats ten irrelevant hits)+- Trending / discovery feeds (this case)+- Recommendation lists ("nothing new worth recommending" beats recycled filler)+- Leaderboards and "top contributors" style rankings over sparse activity+- LLM-generated shortlists, digests, and "best of" summaries, where the model will fill N slots on request regardless of evidence quality++The tell that you need this pattern: the code computes `top N by score` with no branch that can produce an empty result from a non-empty input. If the only way to get an empty list is an empty corpus, the ranker cannot say "nothing here is good enough" - and someday the corpus will be five 1-like tweets.++Design notes when applying it:++- The floor must be absolute (engagement counts, source counts, item counts), not relative (percentile of the current pool). A relative floor degrades with the pool, which is exactly the failure being prevented.+- Prefer composite clearing criteria over a single threshold: independent corroboration OR a strong single-signal spike. Tune the constants to the domain and keep them named and commented as deliberately tunable (see the comment block above the constants in `skills/last30days/scripts/lib/rerank.py`).+- The empty state must name the nearest miss. A bare "no results" reads as breakage; "nothing cleared the bar, closest was X" reads as judgment.++## Examples++Before (v3.13.x behavior, reconstructed from the pinned regression corpus): `--discover "sports"` on a quiet window returned a ranked list built from this corpus -++```+x: "Wii Sports nostalgia thread about sports" 1 like, single source+x: "kids travel sports burnout post" 1 like, single source+x: "motorsports vs stick and ball sports" 1 like, single source+x: "midjourney skateboarder sports prompt" 1 like, single source+x: "manga review mentioning sports matches" 1 like, single source+```++- rendered as topics 1-5 with velocity scores, because `topic_limit = max(5, min(10, limit))` took the top N unconditionally.++After (v3.14.0, PR #816): the same corpus produces `outcome="nothing-solid"`, an empty `topics` list, and the renderer's explicit empty state ("**Nothing solid this window.** No topic cleared the confidence floor ... Closest weak signal: ... (sub-floor; single-source or too little engagement)."). Verified live in the implementing session: `--discover "sports"` returned nothing-solid, while global trending (no domain) returned six real cross-source topics with community quotes - the floor removed the junk without starving the healthy path.++The strong-corpus side, from `tests/test_discover_floor.py`: a single 1,084-point, 577-comment HN thread clears the floor alone via the single-source-spike branch (`engagement_total >= FLOOR_SINGLE_SOURCE_ENGAGEMENT`) and ranks as a real topic; a 25-upvote single-source Reddit post stays buried. The decision logic, in full, is small enough to quote:++```python+if item_count <= 0 or engagement_total < FLOOR_MIN_ENGAGEMENT:+ return False+if source_count >= FLOOR_MIN_SOURCES:+ return True+return engagement_total >= FLOOR_SINGLE_SOURCE_ENGAGEMENT+```++Three lines of gate, placed before the ranker, are the difference between a feature that fills five slots no matter what and one whose non-empty answers can be believed.++## Related++- [Entity grounding: full-phrase false demotion](../logic-errors/entity-grounding-full-phrase-false-demotion.md) - sibling ranking-quality fix in the same rerank module, opposite failure direction (false demotion of good signal vs. junk promotion). Together they bracket the two ways a ranker fails.+- [Search-quality eval: manual by default](../architecture/search-quality-eval-manual-by-default-2026-05-10.md) - how to validate a ranking-threshold change like this floor: manual eval run plus deterministic regression tests, not CI-gated quality scoring.+- [Non-daemon executor threads defeat wall-clock budgets](../logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.md) - sibling learning from the same PR #816 rebuild: the process-lifetime half (enrichment budget enforcement) vs this doc's ranking-quality half.+- [argparse optional-value flag dispatch](../conventions/argparse-optional-value-flag-dispatch-truthiness.md) - third lesson from the same PR #816: the CLI flag semantics that route into this feature.+- [PR #816](https://github.com/mvanhorn/last30days-skill/pull/816) - the discovery rebuild that introduced `passes_discovery_floor()` and the nothing-solid empty state (released v3.14.0).diff --git a/docs/solutions/logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.md b/docs/solutions/logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.mdnew file mode 100644index 00000000..c4d54052--- /dev/null+++ b/docs/solutions/logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.md@@ -0,0 +1,137 @@+---+title: "Wall-clock budget over ThreadPoolExecutor is illusory - non-daemon workers are joined at interpreter shutdown"+category: logic-errors+module: discover-enrichment+date: 2026-07-12+problem_type: logic_error+component: background_job+severity: high+symptoms:+ - "CLI process stayed alive after the enrichment budget expired, even though the hung topic had already been dropped"+ - "as_completed(futures, timeout=budget) returned control on time, but one still-running sub-run kept the interpreter from exiting"+ - "shutdown(wait=False, cancel_futures=True) cancelled unstarted futures but could not stop an already-running worker thread"+root_cause: thread_violation+resolution_type: code_fix+tags:+ - threadpoolexecutor+ - daemon-threads+ - wall-clock-budget+ - interpreter-shutdown+ - semaphore+ - concurrency+ - timeout+ - python+related_components:+ - testing_framework+---++# Wall-clock budget over ThreadPoolExecutor is illusory - non-daemon workers are joined at interpreter shutdown++## Problem++Discovery enrichment fans out one research sub-run per nominated topic under a wall-clock batch budget (`ENRICH_BUDGET_SECONDS`, `skills/last30days/scripts/lib/pipeline.py`), but the first implementation built the budget on `ThreadPoolExecutor` - whose worker threads are non-daemon and joined at interpreter shutdown - so the budget bounded the answer without bounding the process. One hung sub-run could keep the whole CLI alive indefinitely after its topic had already been downgraded to nomination-only.++## Symptoms++- The CLI process stays alive past the enrichment budget - potentially indefinitely - whenever one sub-run hangs (e.g. a network fetch that stalls without tripping a timeout). The batch "finishes", results are assembled, but the process will not exit because Python joins the executor's non-daemon threads at interpreter shutdown.+- Only visible under a genuinely hung worker. All unit tests passed: the slow-topic test observed exactly what `as_completed(timeout=...)` guarantees - the fast topic returned, the slow one was dropped from results - and the test process exited fine because the "slow" worker was merely sleeping a few seconds, not hung. The defect lives entirely in process-lifetime behavior that a result-oriented test never touches.+- Caught by code review on PR #816 (Greptile P1 "Enrichment Budget Keeps Running") before release; shipped fixed in v3.14.0.++## What Didn't Work++The first version of `enrich_nominations()`:++```python+executor = ThreadPoolExecutor(max_workers=max_workers)+futures = {executor.submit(_run_one, n): n for n in nominations}+try:+ for future in as_completed(futures, timeout=budget_seconds):+ ...collect result...+finally:+ executor.shutdown(wait=False, cancel_futures=True)+```++This looks like budget enforcement, and every knob in it does something real - just not the thing needed. Precisely why each one fails to stop a thread that is already running:++- `as_completed(futures, timeout=budget)` bounds only the consumer. When the timeout expires it raises `TimeoutError` in the collecting loop; it sends nothing to the workers. Python threads cannot be killed from outside, so a running sub-run keeps running.+- `cancel_futures=True` cancels only futures still sitting in the executor's queue - futures whose callable has not started. A future in the RUNNING state is not cancellable (`Future.cancel()` returns False for it); the worker executing it is untouched.+- `shutdown(wait=False)` merely skips joining the threads at shutdown-call time. It does not detach them. CPython's `ThreadPoolExecutor` creates its worker threads non-daemon and (since Python 3.9) registers a `threading._register_atexit` hook that joins every worker at interpreter shutdown. So even after `shutdown(wait=False)`, interpreter exit blocks until the hung worker returns - which for a stalled fetch may be never.++Net effect: the budget expired, the slow topic was correctly reported as nomination-only, and the process then sat there anyway, held open by the very thread the budget had supposedly abandoned.++## Solution++Replace the executor with plain daemon threads, a semaphore for the concurrency cap, a queue for results, and a monotonic deadline in the consumer. From `skills/last30days/scripts/lib/pipeline.py`, `enrich_nominations()`:++```python+# Daemon threads + a semaphore instead of ThreadPoolExecutor: executor+# threads are non-daemon and joined at interpreter shutdown, so one hung+# sub-run could keep the whole process alive long after its topic was+# downgraded to nomination-only. Daemon workers make the wall-clock budget+# real - stragglers cannot delay process exit. Abandonment is safe because+# internal_subrun passes write nothing to disk (no save, no library sync,+# no store), and every fetch layer inside run() carries its own timeout.+enriched: dict[str, EnrichedTopic] = {}+results_queue: queue.Queue[tuple[Nomination, schema.Report | None, Exception | None]] = queue.Queue()+slots = threading.Semaphore(max(1, max_workers))++def _worker(nomination: Nomination) -> None:+ with slots:+ try:+ results_queue.put((nomination, _run_one(nomination), None))+ except Exception as exc: # noqa: BLE001 - containment is the contract+ results_queue.put((nomination, None, exc))++for nomination in nominations:+ threading.Thread(+ target=_worker,+ args=(nomination,),+ name=f"discover-enrich-{nomination.name[:32]}",+ daemon=True,+ ).start()++deadline = time.monotonic() + max(1.0, budget_seconds)+pending = len(nominations)+while pending and (remaining := deadline - time.monotonic()) > 0:+ try:+ nomination, report, exc = results_queue.get(timeout=min(remaining, 0.5))+ except queue.Empty:+ continue+ pending -= 1+ ...record EnrichedTopic success or error...+# Budget expired (or all done): unfinished topics fall through below as+# nomination-only; their daemon workers are abandoned and cannot block exit.+```++Topics still unfinished when the loop exits fall through with `error="enrichment budget exhausted"` and survive as nomination-only entries; the batch preserves nomination order and never raises. Defaults live beside the function: `ENRICH_MAX_WORKERS = 3`, `ENRICH_BUDGET_SECONDS = 240.0`.++Three tests in `tests/test_discover_enrich.py` pin the contract:++- `test_enrich_workers_are_daemon_threads` asserts `threading.current_thread().daemon` from inside every worker - the daemon property is tested directly, not inferred from process behavior.+- `test_enrich_concurrency_capped_by_semaphore` runs 6 nominations with `max_workers=2` and asserts peak in-flight workers never exceeds 2.+- `test_enrich_budget_expiry_drops_slow_topic_to_nomination_only` runs a fast and a 5-second topic under `budget_seconds=1.0` and asserts the fast one returns enriched while the slow one drops to nomination-only with a budget error.++## Why This Works++- Daemon threads are not joined at interpreter exit. CPython's shutdown sequence waits only for non-daemon threads; a daemon worker mid-fetch simply dies with the process. That is what makes the wall-clock budget real: expiry means the process can exit now, not "after the straggler finishes".+- The monotonic deadline bounds the consumer independently of worker behavior. `results_queue.get(timeout=min(remaining, 0.5))` wakes at least twice a second to re-check the deadline, so the collecting loop exits within ~0.5s of budget expiry no matter what any worker is doing.+- The semaphore preserves the executor's one useful property. `threading.Semaphore(max(1, max_workers))` acquired inside each worker caps in-flight sub-runs at `max_workers`, so upstream APIs see the same low parallelism as before; threads beyond the cap exist but block on the semaphore, costing almost nothing.+- The write-free precondition is what makes abandonment safe, and it is documented in the code comment where the next editor will see it: enrichment sub-runs are `internal_subrun=True` passes that write nothing to disk - no save, no library sync, no store - and every fetch layer inside `run()` carries its own timeout. Killing such a worker at process exit can corrupt nothing. A worker that mutates shared state (files, databases, caches) must not be abandoned this way; it needs cooperative cancellation instead.++The general lesson: `as_completed(timeout=...)` plus `shutdown(wait=False, cancel_futures=True)` is answer-bounding, not process-bounding. If the requirement is "this batch may not extend the life of the process", non-daemon executor threads cannot deliver it (CPython behavior since 3.9, when executor threads moved from atexit-daemon handling to `threading._register_atexit` joining), and no combination of executor knobs changes that.++## Prevention++- Any "budget" or "timeout" over threaded work must state what happens to a RUNNING straggler. If the design doc or comment only says what happens to the result, the process-lifetime question is unanswered - and the default answer (non-daemon threads joined at exit) is usually wrong for a CLI.+- Prefer explicit daemon threads for abandonable work. When stragglers are safe to drop, `threading.Thread(daemon=True)` + semaphore + queue + monotonic deadline is barely more code than an executor and actually enforces the budget. Reserve `ThreadPoolExecutor` for work you intend to wait for.+- Require the write-free precondition in a comment next to the daemon flag. Daemon abandonment is only safe for workers that mutate no shared state and hold no resources needing cleanup. State the precondition where the code is (as `enrich_nominations()` does), so a future change that adds a disk write inside the worker trips over the warning.+- Test daemon-ness explicitly. Process-hang bugs are invisible to result-oriented unit tests - the passing slow-topic test proved the wrong thing. Assert `threading.current_thread().daemon` inside the worker (see `test_enrich_workers_are_daemon_threads` in `tests/test_discover_enrich.py`); it is a one-line assertion that pins the property the budget depends on.+- Per-request timeouts inside workers remain the first line of defense. Daemon abandonment is the backstop for the pathological case; every network call inside a worker should still carry its own timeout so hung workers are rare, not routine.+- In review, treat `shutdown(wait=False, cancel_futures=True)` in a `finally` as a signal to ask the straggler question. It is the idiom people reach for when they want abandonment, and it does not provide it.++## Related Issues++- [Ranked-output confidence floor + honest empty state](../design-patterns/ranked-output-confidence-floor-honest-empty-state.md) - sibling learning from the same PR #816 discovery rebuild: the ranking-quality half vs this doc's process-lifetime half. Both live in `skills/last30days/scripts/lib/pipeline.py`.+- [argparse optional-value flag dispatch](../conventions/argparse-optional-value-flag-dispatch-truthiness.md) - third lesson from the same PR #816: bare-flag vs flag-absent conflation, another defect class invisible to result-oriented tests.+- [PR #816](https://github.com/mvanhorn/last30days-skill/pull/816) - the discovery rebuild that replaced the executor with daemon threads + semaphore + result queue + monotonic deadline in `enrich_nominations()` (released v3.14.0).+- Note: `skills/last30days/scripts/lib/pipeline.py` still uses `ThreadPoolExecutor` at other call sites where work is genuinely waited for; the daemon-thread pattern was applied only to `enrich_nominations()`, whose stragglers are abandonable. Apply the straggler question, not the pattern, when touching those.