Skip to content

v0.9.0 feat!: find jobs by type and payload, delete only jobs finished a while ago - #16

Merged
ungerik merged 8 commits into
mainfrom
ungerik/get-job-by-type-payload
Nov 17, 2026
Merged

ungerik merged 8 commits into
mainfrom
ungerik/get-job-by-type-payload

Conversation

@ungerik

@ungerik ungerik commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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.job with their own SQL for these can use the jobqueue API instead, with clock-skew-immune cutoffs and no payload in error messages.
Breaking: pass 0 to DeleteFinishedJobs for the old behavior, and add the two new methods to any custom jobqueue.Service implementation or mock.

What changed

Applications kept reaching into the worker.job table 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 to jobqueue.Service:

  • GetJobsWithTypeAndPayload / HasJobWithTypeAndPayload match jobs of a type whose payload equals the given one, compared as PostgreSQL jsonb (key order and whitespace don't matter), filtered by stopped state. The payload goes through the newly exported jobqueue.MarshalJobPayload, the same conversion NewJob uses. A payload NewJob would reject, or one with characters PostgreSQL can't store, fails with ErrInvalidPayload. Lookups match verbatim instead of sanitizing, because sanitizing can merge JSON keys (tenant_id\^@ onto tenant_id) and match another payload's jobs.
  • DeleteFinishedJobs(ctx, finishedFor): 0 deletes 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.
  • Lookup errors redact the payload in both the error call stack (errs.KeepSecret) and go-sqldb's query text (sqldb.KeepSecret), since errors get logged and payloads can carry personal data.
  • Errors that wrap a Job (from AddJob, AddJobBundle and failed workers) print Payload: ***REDACTED*** (N bytes) instead of the payload: Job implements go-pretty's Printable, and the insert passes the payload through sqldb.KeepSecret.
  • New partial hash index worker_job_unstopped_payload_idx makes 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.md lists the next job-query methods (filtered job list, status counts, debounced add) as a roadmap.
Blast radius

Every caller of DeleteFinishedJobs and every type implementing jobqueue.Service must change; inside this repo that is jobworkerdb, doNothingService and errService, all updated, and go build ./... plus the full test suite pass (script ran). The lookups are read-only. The new index changes the schema: databases created from an older schema/worker/job.sql need the create index statement from the CHANGELOG (the claim index in #8 shipped the same way); verified with EXPLAIN ANALYZE under a forced generic plan.

Test Coverage
CODE PATH COVERAGE (git diff origin/main), after the tests added in this PR
[+] jobworkerdb.GetJobsWithTypeAndPayload / HasJobWithTypeAndPayload
    ├── closed → ErrClosed                              [★★ TESTED]  closed_service_test.go
    ├── invalid payload (nil, nil ptr, null, "", "{")   [★★★ TESTED] TestPayloadLookupsRejectInvalidPayload
    ├── unstorable payload → ErrInvalidPayload          [★★★ TESTED] TestHasJobWithTypeAndPayload
    ├── payload redacted from errors (2 paths)          [★★★ TESTED] TestPayloadLookupErrorsRedactPayload
    ├── type filter (Get and Has)                       [★★★ TESTED] TestGet…/TestHasJobWithTypeAndPayload
    ├── jsonb equality, key order independent           [★★★ TESTED]
    └── stopped=false / stopped=true                    [★★★ TESTED]
[+] jobworkerdb.DeleteFinishedJobs(ctx, finishedFor)
    ├── closed → ErrClosed                              [★★ TESTED]  closed_service_test.go
    ├── finishedFor == 0: finished standalone only      [★★★ TESTED] TestDeleteFinishedJobs
    ├── finishedFor > 0: window in seconds, old deleted [★★★ TESTED] TestDeleteFinishedJobsFinishedFor
    ├── finishedFor > 0: errored/unstopped/bundled kept [★★★ TESTED] TestDeleteFinishedJobsFinishedFor
    └── finishedFor < 0: error, nothing deleted         [★★★ TESTED] TestDeleteFinishedJobsFinishedFor
[+] job.go MarshalJobPayload                            [★★★ TESTED] job_test.go (via NewJob)
[+] doNothingService / errService stubs                 [GAP] one-line stubs, compiler-checked

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 null dropped, KeepSecret removed, 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 test without -v prints per-package ok lines 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 finishedFor now 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.

  • INFORMATIONAL jobworkerdb/jobworkerdb.go:1236 SQL uses stopped_at < cutoff while the API doc promises deletion of jobs finished for 'at least' finishedFor; a row exactly at the cutoff is kept
  • INFORMATIONAL service.go:73 Doc promises ErrInvalidPayload for any payload that can't be stored, but valid JSON outside PostgreSQL numeric range (1e1000000) fails as a plain database error
  • INFORMATIONAL job.go:187 Newly exported MarshalJobPayload doesn't name its error result or defer errs.WrapWithFuncParams as the repo convention requires for exported functions
  • INFORMATIONAL README.md:337 README example still calls DeleteFinishedJobs(ctx), which no longer compiles; CHANGELOG has no v0.9.0 entry yet
  • INFORMATIONAL TODO.md:20 TODO.md in this PUBLIC repo names private domonda-service file paths, functions and their raw SQL
  • INFORMATIONAL service.go:76 HasJobWithTypeAndPayload is pitched as a dedupe check but check-then-AddJob is not atomic; two concurrent callers can both see false
  • INFORMATIONAL jobworkerdb/jobworkerdb.go:503 No payload/state index: every lookup scans the type's retained jobs; Get has no LIMIT
  • INFORMATIONAL job.go:187 MarshalJobPayload returns JSON-typed and []byte payloads without copying, so Job.Payload aliases the caller's buffer (pre-existing behavior of the unexported function)
  • INFORMATIONAL jobworkerdb/jobworkerdb.go:517 Lookups don't validate jobType (empty returns no match; a NUL byte gives a raw pq error), consistent with DeleteJobsOfType

Resolved 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:73 doc narrowed to the payloads that actually return ErrInvalidPayload (docs audit); the non-atomic check-then-add is stated in the CHANGELOG. Also noted from the review: doNothingService.DeleteFinishedJobs accepts a negative finishedFor like its other stubs accept any input, and AddJob passing its job (payload included) to WrapWithFuncParams is fixed in this PR as well (Job.PrettyPrint), as is the missing payload index for stopped=false lookups.

Exploratory QA

Functional smoke against an owned temporary database, through a throwaway go run program using the public API (no browser surface):

  • Probe 001, success: HasJobWithTypeAndPayload finds a job added with a struct payload, misses a different payload, GetJobsWithTypeAndPayload with an equal map returns 1 job, and DeleteFinishedJobs(ctx, time.Hour) keeps a job that just finished. PASS.
  • Probe 002, riskiest edge: 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.go doc-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: GetJobsWithTypeAndPayload and MarshalJobPayload have no README example (reference docs only); the HasJobWithTypeAndPayload and package-level lookup docs don't restate the ErrInvalidPayload cases; TODO.md is not linked from README.md or AGENTS.md. No diagrams to drift.

Tests
  • ./scripts/run-tests.sh (go vet, revive, gosec, then go test ./... against a temporary PostgreSQL database): all 4 packages ok, "All tests passed" at the final tree.
  • go build -o /dev/null ./...: ok.
  • Mutation checks in a scratch copy: each new test fails with its defect reintroduced.
Agent notes
  • REVIEW_LOOP: passes=1 blocking_found=1 deferred=0 noted=3 fixed=6 scope=frozen fix_checks=3 dispatches=4
  • Gate edits: none detected (6 listed, 2 read; patterns: RH-1,RH-3,RH-4,RH-12,RH-13,RH-14,RH-15,RH-16; unlisted idioms: none). The 2 read hunks adapt existing test calls to DeleteFinishedJobs(ctx, 0); no assertion relaxed.
  • Pregate: "no test lane" for *_test.go, donothingservice.go, errors.go, service.go is a known Go false positive (no .gstack/pregate.json on main maps Go packages to scripts/run-tests.sh); the lane itself ran and passed.
  • Review rounds over the frozen cap were granted by the owner: one scoped fix round for the payload-redaction finding, and one scoped fix-check for the post-review doc-comment delta (comments only).
  • Outside review: Codex adversarial completed (findings, all addressed or noted); Codex structured completed, gate PASS.

…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.
@ungerik
ungerik merged commit 2301dff into main Nov 17, 2026
2 checks passed
@ungerik
ungerik deleted the ungerik/get-job-by-type-payload branch November 17, 2026 16:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant