An @llm_task decorator for the duplicated Celery task preamble (follow-up to #287) #294
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Fix direction 4 from #287, split out so it does not ride along with that issue's semantic changes. #287 is closed; this is the structural half it deliberately deferred.
Why it was deferred, and why it still matters
#287 made the "no LLM configured" policy documented —
settings_servicenow names the four legitimate policies andrequire_llm_configimplements the default one. But documentation is a convention, and conventions drift. The reason eight behaviours appeared in the first place is that each task hand-writes its own preamble, so there is nothing structural stopping a ninth.The decorator is what would make the policy uniform by construction rather than by discipline.
The duplication, measured against current
main(0a8910e)reminder_tasks.pyis 4,676 lines. Within it:asyncio.run(...)sync→async wrappersasync with task_session() as db:blocksuuid.UUID(x)/except ValueError/ log /returnparse guardreminder_tasks.pyandplanning_tasks.pySix tasks share essentially one skeleton end to end:
_generate_lore_entry_summary_asyncrun_lore_entry_draft_generationrun_workbench_generation_core_propose_lore_relationships_async_generate_journal_entry_async_generate_session_title_suggestions_asyncEvery one of them does, in order:
asyncio.runwrapper around an inner_asyncValueErrorasync with task_session() as dbdb.get(Model, id), log and return ifNoneNonetry/except, log, swallowSteps 1–6 are boilerplate. Only step 7's body differs.
Shape
LlmPolicymaps onto the four policies already documented insettings_service's module docstring — so the decorator becomes the enforcement point for a taxonomy that currently exists only in prose.Constraints worth stating up front
process_audiois not a candidate.max_retries=0, its owntry/exceptrecordsaudio_processing_status, and it resolves Whisper and VAD config alongside the LLM. Leave it alone.lore_chunk_extract,lore_deduplicate_extracts,lore_match_category) have a bespokeon_failurerecordinglore_generation_statusand a retry handler that special-casesLlmNotConfiguredError. The decorator must not flatten that — either compose with it or exclude them.Acceptance
@llm_taskexists, with the policy enum tied tosettings_service's documented fourreminder_tasks.py, and adding a new LLM task no longer requires copying a preambleNot in scope
Splitting
reminder_tasks.py(4,676 lines, and no longer only about reminders). Worth doing eventually; a decorator that shrinks it first makes that split easier to reason about.extractingforever #287Picking this up on
feat/v4-deterministic-attribution.Before implementing I read all six tasks as they stand now (
reminder_tasks.pyis 4,930 lines on the branch, not 4,676 — the v4 work grew it). One premise in the issue is wrong in a way that changes the design, so recording that here rather than silently building something else.The six tasks are not uniform in ordering, and that is load-bearing
The issue says every one of them does steps 1–7 "in order". They don't. The LLM resolution sits at a different point in each:
_generate_lore_entry_summary_asyncif not entry.body: return_generate_journal_entry_asyncif not session.summary: return, "public note already exists" guard_generate_session_title_suggestions_async_propose_lore_relationships_asyncrun_workbench_generation_coreif tool is None: mark_failed("Unknown workbench tool")run_lore_entry_draft_generationA decorator that resolves the config at the top and hands the body an
llm_cfgreorders those guards. That is a real behaviour change, not a cosmetic one:LLM not configured, skipping entry …at WARNING. Same for every session with no summary and every session that already has a journal note. On a no-LLM install that inverts the log from "nothing to do" to a standing warning — the exact noise problem #287 set out to fix.tool_idwould start reporting "LLM endpoint not configured" to the GM instead of "Unknown workbench tool". That one is user-visible and simply wrong.Design: the body decides when, the decorator decides what happens on None
So the config is passed as a zero-argument async resolver, not a value:
llm()never returnsNone— it either yields a config or executes the declared policy (log-and-return forSKIP,LlmNotConfiguredErrorforREQUIRE, the row recorder forRECORD_ON_ROW). That is stronger than the original sketch, not weaker: withllm_cfghanded in, a body could still forget to branch onNone. Here there is noNonebranch to get wrong, and ordering is preserved exactly. Uniform by construction, which was the point.Two corrections to scope
Policy 2 (
RECORD_ON_ROW) does not generalise. "The row" and the recording differ per task —draft.status/draft.last_errorversusgeneration_result_service.mark_failed(...)with a task-specific message. And both of those tasks' cores (run_lore_entry_draft_generation,run_workbench_generation_core) are called directly by 20-odd tests asf(db, id), so their signatures are pinned and a decorator cannot reach inside them. The enum keeps the member and takes anon_missingcallback, but for these two the decorator only absorbs the wrapper preamble (parse + session); their policy-2 branch stays where it is. Adding this to the "constraints" list alongsideprocess_audioand the lore pipeline.The net-line-reduction acceptance criterion is unlikely to be met by six tasks alone. The preamble is ~20 lines per task, so six adopters save ~120 lines against a decorator that costs about the same once documented. I'm adopting a seventh (
_update_campaign_storyline_async— same preamble, and it makes the kwargs path real) which helps, but the honest value here is the enforcement point, not the line count.reminder_tasks.pygets meaningfully shorter only when the other ~20task_sessionblocks adopt the preamble half, and most of those take no id at all, so their preamble is a single line and a decorator would not pay. I'd suggest striking that criterion rather than chasing it.planning_tasks.pyis excluded: both of its LLM sites sit inside a Redis lock and return adict, a different skeleton entirely.Done in
bcd5187onfeat/v4-deterministic-attribution.What shipped
app/tasks/llm_task.py(212 lines) —LlmPolicy(REQUIRE/RECORD_ON_ROW/SKIP, with policy 4 deliberately absent and a comment saying why: treatingNoneas data to describe is an endpoint concern, never a task one), plus two layered decorators.task_bodyabsorbs parse-id →task_session()→ optional row load.llm_taskadds the deferred resolver.Seven tasks adopted it — the six from the issue plus
_update_campaign_storyline_async, which has the identical preamble and exercises the**kwargspath (full_regenerate).Three things that would have broken this quietly, recorded for whoever touches it next
task_sessionis imported inside the wrapper, not at module level. Seventeen tests patchapp.database.task_sessionto reuse their transactional session; a module-level import binds the original at import time and every one of them fails somewhere confusing.logging.getLogger(func.__module__), not the decorator's own logger, so records still originate fromapp.tasks.reminder_tasks.except Exception. A body wrapping its LLM work in a broad except would otherwise swallow the policy and never run it — the one failure mode that would make this silently worse than the duplicated code it replaces. There's a regression test for it. None of the seven converted bodies actually had that shape, but the next one might.One design change beyond the issue:
llmis a required keyword with no default. Defaulting it toSKIPwould hand out policy 3 to any call site that omitted the argument, which rebuilds #287's drift one level up with fewer places to look for it. Pinned bytest_omitting_the_policy_is_an_error_rather_than_a_silent_default.Verification: 1,130 passing before → 1,142 after, with 12 new decorator tests and zero edits to existing tests.
ruff format+ruff checkclean. Also importedapp.tasks.reminder_tasksstandalone in Celery's include order — 42 tasks register — to confirm theloads=model imports hoisted to module scope don't create a cycle. They can't:app.models.*import onlyapp.databaseand sqlalchemy. The issue's warning about function-local imports holds for the service imports, which stayed local.Acceptance, honestly
@llm_taskexists, policy enum tied tosettings_service's documented fourreminder_tasks.py4,930 → 4,816 (−114), against 212 lines forllm_task.py. As flagged above, I don't think it's worth chasing: six adopters were never going to pay for a documented module, and the remainingtask_sessionblocks mostly take no id, so their preamble is one line a decorator wouldn't improve. The value delivered is the second half of that criterion — adding a new LLM task no longer means copying a preamble, and the policy has one implementation instead of seven. Ticking the first half would mean either inlining the documentation or converting tasks that don't benefit.Closing. The file split the issue puts out of scope is now easier to reason about, if you want an issue for it.