Skip to content

Add OpenTelemetry observability to custom background tasks#812

Draft
2chanhaeng wants to merge 3 commits into
fedify-dev:feat/custom-workerfrom
2chanhaeng:issue/799
Draft

Add OpenTelemetry observability to custom background tasks#812
2chanhaeng wants to merge 3 commits into
fedify-dev:feat/custom-workerfrom
2chanhaeng:issue/799

Conversation

@2chanhaeng

Copy link
Copy Markdown
Member

Resolves #799, the third and final sub-issue of #206 (custom background tasks). Once this lands, #206 is fully resolved.

Background

The core task API (#797/#803) shipped task dispatch behavior and structured logging, but the task worker carries no span and no metrics: of the message variants handled in processQueuedTask, every other branch (fanout/outbox/inbox) is dispatched with instrumentation, but task.

This PR closes that gap by layering task-specific telemetry onto the decision points the core already established. It reuses the queue-task metric pattern introduced in #759 and mirrors the existing http_signatures.failure_reason enum in metrics.ts. It changes no drop/retry behavior: telemetry is observed, never enforced.

What changes

Span

Each dequeued task now runs inside a fedify.task consumer span. The name is namespaced under fedify. rather than activitypub. because tasks are not part of ActivityPub, paralleling the existing activitypub.inbox/outbox/fanout spans. The span:

  • Inherits the enqueue site's trace context, so a task is a child of whatever requested it.
  • Carries fedify.task.name and fedify.task.attempt (the zero-based attempt number).
  • Carries fedify.task.failure_reason and sets its status to ERROR on a terminal failure, so trace backends surface failed tasks without re-deriving the reason from logs.

Failure attribution

#listenTaskMessage now returns the failure reason (or undefined on success) so the span/metric wrapper can attribute it. To distinguish a deserialization failure from a validation failure, the former combined codec.decode(...) call is split into its existing deserialize then validate phases. This is behavior-preserving—decode is literally validate(schema, await deserialize(raw))—and TaskCodec gains a thin instance validate() wrapper so the dispatch site can split the two phases without importing the class.

The four bounded fedify.task.failure_reason values map one-to-one to the worker's dispatch decision points:

  • deserialization — the wire payload could not be deserialized.
  • validation — the deserialized payload failed schema validation.
  • unknown_task — the task name has no registered handler.
  • handler — the registered handler threw.

A worker shutdown is the one exception: an interrupted attempt is reported as an aborted outcome with no fedify.task.failure_reason, never as a handler failure.

Metrics surface

Tasks reuse the fedify.queue.task.* metric family under a new task role:

  • QueueTaskRole gains "task".
  • QueueTaskCommonAttributes gains taskName, emitted as fedify.task.name.
  • New bounded QueueTaskFailureReason type, mirroring HttpSignatureMetricFailureReason.
  • recordQueueTaskOutcome() gains an optional trailing failureReason parameter (non-breaking); it is emitted as fedify.task.failure_reason only on a failed result.
  • recordQueueTaskEnqueued records role: "task" at both the enqueue site (after a genuine dispatch, never on a dedup skip or a failed enqueue) and the retry re-enqueue site.

fedify.queue.backend reports the resolved queue—the one actually used after routing, which may be the outbox queue under the fallback mode—so the metric stays accurate regardless of routing.

Cardinality

Bounded by construction: task names are a registered, known-at-startup set (never derived from message content), and failure_reason is a four-value bounded enum. Combined cardinality is taskName × |failure_reason| × queue.backend, within OTel attribute safety. The process-local in_flight UpDownCounter omits fedify.task.name so its series stays drained.

Out of scope

  • A management UI / inspection RPC.
  • Per-task custom metric attributes beyond taskName (would risk unbounded cardinality).
  • Refining the four-value QueueTaskFailureReason set—explicitly open to later refinement as long as it stays a small bounded set.
  • Any change to drop/retry semantics.

Tests

packages/fedify/src/federation/tasks/tasks.test.ts gains a telemetry block with one assertion per acceptance criterion, using TestSpanExporter / createTestTracerProvider / createTestMeterProvider from @fedify/fixture. Coverage:

  • A fedify.task span exists with fedify.task.name and fedify.task.attempt.
  • Parent context is inherited from the enqueue site.
  • Each failure path records the correct fedify.task.failure_reason.
  • fedify.queue.backend reflects the resolved queue, including the outbox fallback.
  • recordQueueTaskEnqueued / recordQueueTaskOutcome carry role: "task".

Verified across Deno, Node.js, and Bun.

Documentation

  • docs/manual/tasks.md: a new "Observability" section covering the span, its attributes, the metric family, and the bounded failure-reason set; the stale "ships without OpenTelemetry spans and metrics" note removed from "Limitations".
  • docs/manual/opentelemetry.md: the fedify.task span row, the task value added to the fedify.queue.role enumeration, a widened failed-result definition covering acked task drops, and the fedify.task.name / fedify.task.attempt / fedify.task.failure_reason attribute rows.
  • CHANGES.md: the existing task-feature entry extended with the observability additions and the Custom background tasks: observability #799 reference link.

AI disclosure

Assisted-by: Claude Code:claude-opus-4-8

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5a83fa82-394f-40f6-9b07-5815058c2d97

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a custom background task API to Fedify, allowing developers to define, enqueue, and process arbitrary background jobs with type-safe payload validation via Standard Schema. The implementation supports robust serialization of complex types and Activity Vocabulary objects using devalue, customizable retry policies, queue routing, best-effort or native deduplication, and OpenTelemetry instrumentation. Feedback on the changes highlights a compatibility issue with Node.js 20 due to the use of Array.fromAsync in codec.ts, suggesting standard for...of loops instead, and recommends implementing a recursion depth limit during deserialization to prevent potential Denial of Service (DoS) attacks from deeply nested payloads.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread packages/fedify/src/federation/tasks/codec.ts
Comment thread packages/fedify/src/federation/tasks/codec.ts
Comment thread packages/fedify/src/federation/tasks/codec.ts
@codecov

codecov Bot commented Jun 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

Files with missing lines Coverage Δ
packages/fedify/src/federation/metrics.ts 99.35% <100.00%> (+<0.01%) ⬆️
packages/fedify/src/federation/middleware.ts 90.27% <100.00%> (+0.18%) ⬆️
packages/fedify/src/federation/tasks/codec.ts 99.13% <100.00%> (+0.03%) ⬆️
packages/fedify/src/federation/tasks/enqueue.ts 97.22% <100.00%> (+0.11%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Context.enqueueTask() and enqueueTaskMany() now accept a
deduplicationKey requesting at-most-once enqueue for tasks that share
it (new TaskEnqueueOptions.deduplicationKey).

Resolution follows the queue and key-value store capabilities:

 -  A queue declaring the new MessageQueue.nativeDeduplication owns the
    check; the key is forwarded through the new
    MessageQueueEnqueueOptions.deduplicationKey.
 -  Otherwise Fedify applies a best-effort guard through the optional
    KvStore.cas primitive under a new taskDeduplication key prefix,
    tunable with the new FederationOptions.taskDeduplicationTtl and
    taskDeduplicationFallback options.

For enqueueTaskMany(), a single key governs the whole batch.  A native
queue that does not implement enqueueMany() cannot express batch-level
at-most-once with a per-message key, so such a multi-item enqueue is
rejected with a TypeError instead of silently leaking duplicates.

Configuration errors that are decidable without a payload (a native
queue lacking enqueueMany, or a closed fallback without cas) are
checked before payloads are validated and encoded, so they reject
before any user schema runs or any key is reserved.

fedify-dev#798

Assisted-by: Claude Code:claude-opus-4-8
Layer task-specific telemetry onto the custom background task
dispatch path, reusing the queue-task metric pattern and mirroring
the existing `http_signatures.failure_reason` enum in metrics.ts.

Each dequeued task now runs in a `fedify.task` span that inherits
the enqueue site's trace context and carries `fedify.task.name`,
`fedify.task.attempt`, and, on a terminal failure,
`fedify.task.failure_reason`.  The `fedify.queue.task.*` metrics
report task runs under the new `"task"` role with the task name and,
on failure, a bounded `fedify.task.failure_reason`.

To tell the failure reasons apart, `#listenTaskMessage` splits the
former `decode()` call into its deserialize and validate phases and
returns the decision point that failed: `deserialization`,
`validation`, `unknown_task`, or `handler`.  A swallowed abort is
reported as a graceful interruption, not a failure.  The reported
`fedify.queue.backend` reflects the resolved queue so it stays
accurate under the outbox fallback.

Public surface: `QueueTaskRole` gains `"task"`,
`QueueTaskCommonAttributes` gains `taskName`, and a new
`QueueTaskFailureReason` type plus an optional trailing
`failureReason` parameter on `recordQueueTaskOutcome()` carry the
reason.  `TaskCodec` exposes an instance `validate()` wrapper so the
dispatch site can split decoding without importing the class.

fedify-dev#799

Assisted-by: Claude Code:claude-opus-4-8
Deno executes the TypeScript sources directly, so
`test:deno` spent most of its time on a `build` it
never needed: with no dist/ output present, the
whole Deno suite passes except the npm packaging
regression tests added for fedify-dev#655,
which assert that the built package.json entry
points of `@fedify/cli`, `@fedify/create`, and
`@fedify/init` exist.  Those checks guard the npm
artifacts, not the Deno runtime, and still run
under `test:node` and `test:bun`, which build
first—so skip them under Deno and drop the `build`
dependency from `test:deno`. `@fedify/lint`'s
oxlint integration test already skips itself
when *dist/oxlint.js* is absent.

Update AGENTS.md to match: document
`mise run build`/`prepare-each` for building,
`check-each` and `test-each` for scoping work to
specific packages, recommend the now build-free
`test:deno` as the default test loop during
development, and add a section directing agents
to consult `mise tasks`.

Assisted-by: Claude Code:claude-opus-4-8
Assisted-by: Claude Code:claude-fable-5
@2chanhaeng

Copy link
Copy Markdown
Member Author

@codex review
@claude review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a2788986f1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

);
}
// A swallowed abort is a graceful interruption, not a task failure.
return isAbortError(error) ? undefined : "handler";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not mark retried task attempts as failed

When a handler throws on a non-native queue and the retry policy returns a delay, the branch above successfully re-enqueues the retry but this return value still reports "handler" to the wrapper. That wrapper then records fedify.queue.task.failed and sets the span to ERROR for every transient task error that is being retried, even though the attempt was folded into a retry (matching the existing inbox/outbox internal-retry convention and the docs' “terminal failure” wording). This will inflate failed-task alerts for workloads with normal retries; only the give-up path should return the handler failure reason.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/fedify/src/federation/tasks/enqueue.ts (1)

98-113: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Enqueue metrics can undercount partial fan-out successes.
When dispatch() falls back to Promise.all(queue.enqueue(...)), one rejected enqueue aborts the whole batch before recordQueueTaskEnqueued() runs, so messages that already reached the backend never get counted. Consider recording per-message success in the fan-out path or switching that branch to Promise.allSettled().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/fedify/src/federation/tasks/enqueue.ts` around lines 98 - 113, The
enqueue metrics in enqueue() can miss partially successful fan-out enqueues
because Promise.all aborts before recordQueueTaskEnqueued() runs. Update the
dispatch flow so each message’s successful enqueue is recorded individually in
the Promise.all(queue.enqueue(...)) path, or change that branch to
Promise.allSettled() and count only the fulfilled enqueues while preserving the
existing rollback/error handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@CHANGES.md`:
- Line 48: The changelog entry in CHANGES.md has malformed issue references
because two adjacent links are missing a separator, causing them to render
together. Update the existing contributor entry that contains the references
near `#799` and `#803` so it keeps the same [[`#123`] by Name] style while adding the
missing comma separator between those two references, and leave the rest of the
reference formatting unchanged.

In `@packages/fedify/src/federation/tasks/tasks.test.ts`:
- Around line 1524-1552: The retry-path test in tasks.test.ts only checks the
re-enqueue metric and misses the paired failure metric. Update the test around
processQueuedTask to also assert that `#listenTaskMessage` emits
fedify.queue.task.failed with fedify.task.failure_reason set to "handler" when
the handler throws and retryPolicy schedules a retry. Use the existing recorder
assertions alongside fedify.queue.task.enqueued so the test covers both
measurements for the retry flow.

---

Outside diff comments:
In `@packages/fedify/src/federation/tasks/enqueue.ts`:
- Around line 98-113: The enqueue metrics in enqueue() can miss partially
successful fan-out enqueues because Promise.all aborts before
recordQueueTaskEnqueued() runs. Update the dispatch flow so each message’s
successful enqueue is recorded individually in the
Promise.all(queue.enqueue(...)) path, or change that branch to
Promise.allSettled() and count only the fulfilled enqueues while preserving the
existing rollback/error handling.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2c06364a-9cde-4035-a0db-fa9658e132f4

📥 Commits

Reviewing files that changed from the base of the PR and between 68519bf and a278898.

📒 Files selected for processing (13)
  • AGENTS.md
  • CHANGES.md
  • docs/manual/opentelemetry.md
  • docs/manual/tasks.md
  • mise.toml
  • packages/cli/src/startup.test.ts
  • packages/create/src/package.test.ts
  • packages/fedify/src/federation/metrics.ts
  • packages/fedify/src/federation/middleware.ts
  • packages/fedify/src/federation/tasks/codec.ts
  • packages/fedify/src/federation/tasks/enqueue.ts
  • packages/fedify/src/federation/tasks/tasks.test.ts
  • packages/init/src/package.test.ts

Comment thread CHANGES.md
`FederationOptions.taskDeduplicationFallback` options.

[[#206], [#797], [#798], [#803], [#806] by ChanHaeng Lee]
[[#206], [#797], [#798], [#799] [#803], [#806], [#812] by ChanHaeng Lee]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fix the malformed changelog references.

[#799] [#803] is missing a separator, so the rendered changelog will merge those references. Please change it to [#799], [#803] and keep the existing [[#123] by Name] style intact.

As per coding guidelines, CHANGES.md external-contributor entries should use [[#123] by Name] reference formatting.

Suggested fix
- [[`#206`], [`#797`], [`#798`], [`#799`] [`#803`], [`#806`], [`#812`] by ChanHaeng Lee]
+ [[`#206`], [`#797`], [`#798`], [`#799`], [`#803`], [`#806`], [`#812`] by ChanHaeng Lee]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[[#206], [#797], [#798], [#799] [#803], [#806], [#812] by ChanHaeng Lee]
[[`#206`], [`#797`], [`#798`], [`#799`], [`#803`], [`#806`], [`#812`] by ChanHaeng Lee]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CHANGES.md` at line 48, The changelog entry in CHANGES.md has malformed issue
references because two adjacent links are missing a separator, causing them to
render together. Update the existing contributor entry that contains the
references near `#799` and `#803` so it keeps the same [[`#123`] by Name] style while
adding the missing comma separator between those two references, and leave the
rest of the reference formatting unchanged.

Source: Coding guidelines

Comment on lines +1524 to +1552
await t.step(
"records the retry re-enqueue with role task and a bumped attempt",
async () => {
const queue = new MockQueue();
const { federation, recorder } = instrument({
...baseOptions,
queue: { task: queue },
});
federation.defineTask("retry-me", {
schema: stringSchema,
handler: () => {
throw new Error("boom");
},
retryPolicy: () => Temporal.Duration.from({ milliseconds: 1 }),
});
await federation.processQueuedTask(
undefined,
await makeTaskMessage("retry-me", "payload"),
);

strictEqual(queue.enqueued.length, 1);
strictEqual(queue.enqueued[0].message.attempt, 1);
const enqueued = recorder.getMeasurements("fedify.queue.task.enqueued");
strictEqual(enqueued.length, 1);
strictEqual(enqueued[0].attributes["fedify.queue.role"], "task");
strictEqual(enqueued[0].attributes["fedify.task.name"], "retry-me");
strictEqual(enqueued[0].attributes["fedify.queue.task.attempt"], 1);
},
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider asserting fedify.queue.task.failed on the retry path too.

This test confirms the enqueued re-enqueue metric but doesn't assert that the same attempt also records fedify.queue.task.failed with fedify.task.failure_reason: "handler". Per #listenTaskMessage (middleware.ts), a scheduled retry and a terminal give-up both return "handler", so both should emit a failed measurement — this is the more surprising half of the task-vs-inbox/outbox distinction called out in docs/manual/opentelemetry.md. Adding this assertion would close a coverage gap on that documented behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/fedify/src/federation/tasks/tasks.test.ts` around lines 1524 - 1552,
The retry-path test in tasks.test.ts only checks the re-enqueue metric and
misses the paired failure metric. Update the test around processQueuedTask to
also assert that `#listenTaskMessage` emits fedify.queue.task.failed with
fedify.task.failure_reason set to "handler" when the handler throws and
retryPolicy schedules a retry. Use the existing recorder assertions alongside
fedify.queue.task.enqueued so the test covers both measurements for the retry
flow.

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