Repository navigation
v0.9.0 feat!: find jobs by type and payload, delete only jobs finished a while ago - #16
Merged
Merged
Conversation
…ob deletion Add Service methods to replace direct worker.job SQL in domonda-service: - GetJobsWithTypeAndPayload / HasJobWithTypeAndPayload match jobs by type and jsonb-equal payload, filtered by stopped state; HasJob is the existence-only SELECT EXISTS companion that fetches no rows. - DeleteFinishedJobs now takes a finishedFor duration: >0 deletes only jobs whose stopped_at is older than the cutoff, evaluated with the DB clock (now() - make_interval) for clock-skew immunity. Export the strict payload conversion as MarshalJobPayload, the canonical payload->jsonb conversion shared by job creation and payload matching, and sanitize the lookup payload like AddJob does before storing it, so the payload a job was added with finds that job instead of failing the jsonb cast on an unstorable \u0000 escape. Add TODO.md tracking the remaining dashboard/debounce extensions.
…lters Lookups with a nil, null, empty or invalid payload fail with ErrInvalidPayload instead of reporting no match. HasJobWithTypeAndPayload ignores a job of another type. DeleteFinishedJobs(ctx, finishedFor) keeps jobs inside the window, errored, unstopped and bundled jobs, and the test uses its own job IDs instead of reusing TestDeleteJobsFromOrigin's.
Payload lookups match their payload verbatim again: a payload that sanitizing would change returns ErrInvalidPayload, because a sanitized lookup key could collapse onto another payload (e.g. a tenant_id\u0000 key onto tenant_id) and read that payload's jobs. DeleteFinishedJobs rejects a negative finishedFor instead of deleting every finished job. Document the per-type scan cost of the payload lookups and fix a stale SQL comment. Review-Finding: jobworkerdb/jobworkerdb.go:524:stale-comment reader=core Review-Finding: p1/batched#1 reader=security Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/batched#3 reader=qa Review-Finding: p1/red-team#3 reader=red-team
The payload lookups passed the caller's payload to errs.WrapWithFuncParams and as a plain SQL argument, so every lookup error, including go-sqldb's query text on a database error, quoted the payload into logs. Wrap it with errs.KeepSecret and sqldb.KeepSecret; the value still reaches PostgreSQL. TODO.md keeps the job-query API roadmap and drops the details of private callers. Review-Finding: p2/codex-adversarial#1 reader=outside-voice
…README example DeleteFinishedJobs docs state that bundled jobs are never deleted and that the cutoff uses the database clock. The lookup docs say a payload with characters PostgreSQL can't store is rejected while AddJob stores it sanitized. The README example uses the new DeleteFinishedJobs signature and shows HasJobWithTypeAndPayload.
Errors from AddJob, AddJobBundle, insertJob and the worker's DoJob wrap the job with errs.WrapWithFuncParams, which pretty-printed the whole Job, payload included, into logged errors. Job now implements pretty.Printable and prints every field except the payload, shown as its length. The insert also passes the payload through sqldb.KeepSecret so database errors don't quote it in the query text.
Add worker_job_unstopped_payload_idx, a partial hash index on payload where stopped_at is null, and give GetJobsWithTypeAndPayload and HasJobWithTypeAndPayload a static stopped_at predicate per state so the planner uses it even with a cached generic plan (the boolean parameter form fell back to a parallel seq scan). Measured at 200k jobs with 20k unstopped: 7 ms before, 0.02 ms after. Existing databases need the index applied; the CHANGELOG has the statement.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You can now look up jobs by type and payload (
GetJobsWithTypeAndPayload,HasJobWithTypeAndPayload) and delete only jobs that finished at least a given time ago (DeleteFinishedJobs(ctx, finishedFor)).Callers that queried
worker.jobwith their own SQL for these can use thejobqueueAPI instead, with clock-skew-immune cutoffs and no payload in error messages.Breaking: pass
0toDeleteFinishedJobsfor the old behavior, and add the two new methods to any customjobqueue.Serviceimplementation or mock.What changed
Applications kept reaching into the
worker.jobtable with raw SQL to answer "is a job for this payload already queued?" and to prune finished jobs older than an hour. This release adds those queries tojobqueue.Service:GetJobsWithTypeAndPayload/HasJobWithTypeAndPayloadmatch jobs of a type whose payload equals the given one, compared as PostgreSQLjsonb(key order and whitespace don't matter), filtered by stopped state. The payload goes through the newly exportedjobqueue.MarshalJobPayload, the same conversionNewJobuses. A payloadNewJobwould reject, or one with characters PostgreSQL can't store, fails withErrInvalidPayload. Lookups match verbatim instead of sanitizing, because sanitizing can merge JSON keys (tenant_id\^@ontotenant_id) and match another payload's jobs.DeleteFinishedJobs(ctx, finishedFor):0deletes every finished standalone job without errors as before; a positive duration only deletes jobs that finished at least that long ago by the database clock; a negative duration returns an error instead of deleting everything.errs.KeepSecret) and go-sqldb's query text (sqldb.KeepSecret), since errors get logged and payloads can carry personal data.Job(fromAddJob,AddJobBundleand failed workers) printPayload: ***REDACTED*** (N bytes)instead of the payload:Jobimplements go-pretty'sPrintable, and the insert passes the payload throughsqldb.KeepSecret.worker_job_unstopped_payload_idxmakes the duplicate check (stopped=false) an index probe: 7 ms → 0.02 ms at 200k jobs with 20k unstopped. Existing databases need it applied (statement in the CHANGELOG).TODO.mdlists the next job-query methods (filtered job list, status counts, debounced add) as a roadmap.Blast radius
Every caller of
DeleteFinishedJobsand every type implementingjobqueue.Servicemust change; inside this repo that isjobworkerdb,doNothingServiceanderrService, all updated, andgo build ./...plus the full test suite pass (script ran). The lookups are read-only. The new index changes the schema: databases created from an olderschema/worker/job.sqlneed thecreate indexstatement from the CHANGELOG (the claim index in #8 shipped the same way); verified withEXPLAIN ANALYZEunder a forced generic plan.Test Coverage
Tests: 20 → 20 test files (tests added inside existing files).
Coverage: 76% of changed paths at the Step 7 audit (68% value-weighted); the gaps it found are closed by this PR's tests, each proven to fail with the defect reintroduced (mutation runs: type filter removed from Has,
Seconds()→Minutes(),error_msg is nulldropped,KeepSecretremoved, sanitizing reintroduced).Test value: 4 tests written, 0 rejected by the authoring gate, 2 existing tests extended, 0 paths weakly covered.
Value: protects=lookups fail with ErrInvalidPayload on nil/null/empty/invalid payloads; fails_when=the marshal error is ignored and nil binds as SQL NULL, so a dedupe check enqueues a duplicate; why_new=no test passed an invalid payload to a lookup; seam=none; no_claim=json.Marshal failure kinds (job_test.go)
Value: protects=lookup errors don't quote the payload; fails_when=KeepSecret is dropped from WrapWithFuncParams or the SQL argument; why_new=no test read lookup error text; seam=none; no_claim=AddJob's own error formatting (pre-existing)
Value: protects=Has respects the job type; fails_when=type = $1 is dropped from the EXISTS query; why_new=Has test inserted one type only; seam=none; no_claim=none beyond protects
Value: protects=finishedFor window unit and shared filters; fails_when=Seconds() becomes Minutes()/Hours() or the >0 query drops error_msg/bundle_id/stopped filters, or a negative value deletes everything; why_new=old test's recent job stopped at now; seam=none; no_claim=exact-equality boundary at the cutoff
Tests ran: tests count unavailable (
go testwithout-vprints per-packageoklines only)Pre-Landing Review
Review pass 1 (core checklist, batched testing/security/state-machines specialist, Red Team) found 7 issues: 2 fixed automatically (stale SQL comment, lookup-cost doc), 3 fixed after a decision (lookups now reject instead of sanitize unstorable payloads; a raw zero byte case the Red Team found; negative
finishedFornow errors), 2 noted. Adversarial passes (native Claude, Codex adversarial, Codex structured) completed; three sources independently found that lookup errors quoted the payload, which is fixed with redaction plus a test. Codex structured gate: PASS (no P0/P1).The native and Codex adversarial passes reviewed the tree before the redaction fix and the doc-comment repair. Those two later changes were each covered by an owner-granted scoped fix-check (both NO FINDINGS); the doc-comment delta is comments only (empty non-comment Go diff).
Review notes
Below the blocking floor (advisory, informational, test-gap or wording items); recorded here and not fixed in this PR.
jobworkerdb/jobworkerdb.go:1236SQL uses stopped_at < cutoff while the API doc promises deletion of jobs finished for 'at least' finishedFor; a row exactly at the cutoff is keptservice.go:73Doc promises ErrInvalidPayload for any payload that can't be stored, but valid JSON outside PostgreSQL numeric range (1e1000000) fails as a plain database errorjob.go:187Newly exported MarshalJobPayload doesn't name its error result or defer errs.WrapWithFuncParams as the repo convention requires for exported functionsREADME.md:337README example still calls DeleteFinishedJobs(ctx), which no longer compiles; CHANGELOG has no v0.9.0 entry yetTODO.md:20TODO.md in this PUBLIC repo names private domonda-service file paths, functions and their raw SQLservice.go:76HasJobWithTypeAndPayload is pitched as a dedupe check but check-then-AddJob is not atomic; two concurrent callers can both see falsejobworkerdb/jobworkerdb.go:503No payload/state index: every lookup scans the type's retained jobs; Get has no LIMITjob.go:187MarshalJobPayload returns JSON-typed and []byte payloads without copying, so Job.Payload aliases the caller's buffer (pre-existing behavior of the unexported function)jobworkerdb/jobworkerdb.go:517Lookups don't validate jobType (empty returns no match; a NUL byte gives a raw pq error), consistent with DeleteJobsOfTypeResolved since these notes were recorded: the README example and the v0.9.0 CHANGELOG entry (release prep), TODO.md trimmed to a generic roadmap (owner decision), and the
service.go:73doc narrowed to the payloads that actually returnErrInvalidPayload(docs audit); the non-atomic check-then-add is stated in the CHANGELOG. Also noted from the review:doNothingService.DeleteFinishedJobsaccepts a negativefinishedForlike its other stubs accept any input, andAddJobpassing its job (payload included) toWrapWithFuncParamsis fixed in this PR as well (Job.PrettyPrint), as is the missing payload index forstopped=falselookups.Exploratory QA
Functional smoke against an owned temporary database, through a throwaway
go runprogram using the public API (no browser surface):HasJobWithTypeAndPayloadfinds a job added with a struct payload, misses a different payload,GetJobsWithTypeAndPayloadwith an equal map returns 1 job, andDeleteFinishedJobs(ctx, time.Hour)keeps a job that just finished. PASS.DeleteFinishedJobs(ctx, -time.Hour)first deleted a just-finished job without an error (FAIL, fixed in this PR); on the current tree it returns an error and deletes nothing. PASS.Both probes reran on the final code (2/2 pass). Payload redaction and unstorable-payload behavior are covered by tests, not smoke probes.
Scope Drift
Scope Check: CLEAN
Plan Completion
Plan completion audit: not run (no plan is bound to this branch and no docs/designs/ file matches). Fix: add "Plan: " to the PR body, or run /autoplan.
Verification Results
No plan-specific checks (no plan file). Automatic QA smoke: 2 PASS, 0 FAIL, 0 BLOCKED, 0 NOT RUN on the final tree.
Documentation
Status: current. Read-only re-audit found no doc corrections needed; the three
service.godoc-comment fixes and the CHANGELOG wording fix from the first audit (docs-20261117163824, blocked on exactly those) are verified against the code.Scope: committed diff e2dd705..5b046fa plus the release-prep changes to CHANGELOG.md, README.md, VERSION and service.go. Reviewed README.md, AGENTS.md, CLAUDE.md, CHANGELOG.md, TODO.md and the Go package/API doc comments in doc.go, jobworker/doc.go, jobworkerdb/doc.go, service.go and job.go against the implementation, schema and tests.
Debt:
GetJobsWithTypeAndPayloadandMarshalJobPayloadhave no README example (reference docs only); theHasJobWithTypeAndPayloadand package-level lookup docs don't restate theErrInvalidPayloadcases; TODO.md is not linked from README.md or AGENTS.md. No diagrams to drift.Tests
./scripts/run-tests.sh(go vet, revive, gosec, thengo test ./...against a temporary PostgreSQL database): all 4 packagesok, "All tests passed" at the final tree.go build -o /dev/null ./...: ok.Agent notes
DeleteFinishedJobs(ctx, 0); no assertion relaxed.*_test.go,donothingservice.go,errors.go,service.gois a known Go false positive (no.gstack/pregate.jsonon main maps Go packages toscripts/run-tests.sh); the lane itself ran and passed.