Skip to content

feat(chart): add Celery worker and broker - #381

Merged
uniqueg merged 7 commits into
devfrom
feat/chart-celery
Oct 22, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/chart-celery

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adds an optional Celery worker and message broker to the library chart foca-common, following #312. Everything is off by default, and existing values render the same output as before: the four existing snapshots are unchanged.

  • Worker (foca-common.workerDeployment, worker.* values): a Deployment with the app's image, run with worker.command. It gets the app's config overlay, MongoDB credentials, security contexts (non-root, read-only root file system) and /tmp. Further values: replicas, optional readinessProbe/livenessProbe (probe specs, none by default, e.g., celery inspect ping; added for Sourcery's review), terminationGracePeriodSeconds (Celery's warm shutdown), resources, tmpSizeLimit.
  • Bundled broker (foca-common.brokerDeployment, brokerService, brokerNetworkPolicy, broker.* values):
    • RabbitMQ (rabbitmq:4.3), as FOCA's Celery factory defaults to pyamqp:// with the rpc:// result backend.
    • Runs as user 999 with a read-only root file system; the data and home directory are in an emptyDir (dataSizeLimit), and logs go to stdout only (RABBITMQ_LOGS=-).
    • The Recreate strategy keeps one broker at a time.
    • A config file (foca-common.brokerConfigMap, mounted into /etc/rabbitmq/conf.d) permits transient non-exclusive queues. RabbitMQ 4.3 denies them by default (deprecated feature transient_nonexcl_queues), but Celery declares them for the rpc:// result backend (FOCA's default) and for remote control. The first kind run failed on exactly this. The docs give the setting for external RabbitMQ brokers.
    • The user is created from the Secret's username and password.
  • Broker settings come from a Secret (broker.existingSecret), never from plain values:
    • CELERY_BROKER_URL is read from the key broker-url.
    • CELERY_RESULT_BACKEND is read from the optional key result-backend (optional: true, falling back to jobs.backend).
    • Both go to the app and the worker.
    • With only the Secret set, the app uses an external broker.
    • Rendering fails if the worker or the bundled broker is enabled without the Secret.
  • NetworkPolicies: the broker's policy (enabled by default) admits only the app's and the worker's pods of the release, on port 5672. MongoDB's policy also admits the worker when it is enabled.
  • Names, labels, schema:
    • Resource names are <fullname>-worker and <fullname>-broker, truncated like -mongodb, with collision checks.
    • The worker and broker resources carry the component labels worker and broker.
    • New top-level worker and broker sections in app-values.schema.json, copied to the petstore schema.
    • App charts without these values render as before (tested).
  • Petstore example:
    • New worker.py (Celery entry point via Foca.create_celery_app()) and a jobs section in config.yaml.
    • The thin chart gets the four templates and the disabled values, documented like the existing ones.
    • New ci/celery-values.yaml.
  • CI (charts.yml):
    • Lints the petstore chart with each ci/*-values.yaml.
    • The kind job installs the chart a second time with the worker and the bundled broker. It creates the Secret with a random password and checks that the worker logs "ready." (connected to the broker) without errors.
    • The worker's connection retries while the broker starts are not counted as errors.
  • Docs: docs/helm-chart.md covers the templates, values, deployment notes (Secret layout with an example, Service name, persistence) and the CI install. docs/configuration/jobs.md links to it.
  • Version: stays 0.1.0, as chart-v0.1.0 hasn't been released yet (no chart-v* tags).

Closes #351

Design choice for review: the bundled RabbitMQ keeps queued tasks in an emptyDir, so they are lost when its pod is replaced. This is documented in values.yaml and the docs, with an external broker recommended for durable queues. A PVC would also need a stable RabbitMQ node name (e.g., RABBITMQ_NODENAME=rabbit@localhost). Adding it later is backwards compatible, e.g., as broker.persistence.

Verification

  • pytest charts/foca-common/tests (Helm 3.22.1, as in CI): 119 passed. That is 93 before, plus 23 new template tests, a celery snapshot and lints with both CI values files. The existing four snapshots are unchanged.

  • helm lint --strict for the library, and for the petstore chart with both ci/*-values.yaml: pass. helm dependency build: Chart.lock unchanged.

  • ruff check, ruff format --check, mypy, mkdocs build --strict: pass. The nested code block in the docs was checked in the rendered HTML.

  • actionlint 1.7.12 with shellcheck 0.11.0 on charts.yml: pass.

  • worker.py imported locally with an overlay pointing to MongoDB on port 12345: it creates the Celery app with the broker URL from CELERY_BROKER_URL. python -m celery --app worker:celery_app resolves.

  • CI: all checks pass. In the kind job, both releases install and their helm test passes.

    • The bundled RabbitMQ (non-root, read-only root file system) starts.
    • The worker retries while the broker boots (filtered), then logs celery@petstore-celery-worker-... ready.
    • The first run (before the broker config file) failed with INTERNAL_ERROR - Feature transient_nonexcl_queues is deprecated.
  • Sourcery: three threads, all fixed and resolved: optional worker probes, full selector labels in the NetworkPolicy tests, and the Celery render keeping all default resources.

Declined review findings

  • Quality review: extract a helper shared by the app's and the worker's env, volumes and mounts. Declined, because it would change the app Deployment's template. Instead, _worker.tpl notes that the two must stay in line, and a test compares the worker's env (minus Gunicorn), mounts, volumes and security contexts with the app's.
  • Adversarial review: CI doesn't prove that the worker connects to MongoDB, since the petstore example creates no indexes. Declined beyond correcting the comment: the worker branch of MongoDB's NetworkPolicy is covered by template and snapshot tests, and helm test checks the app's MongoDB access.
  • Quality review: worker.command has no minItems in the schema. Declined, as it's consistent with the other values: "required if enabled" is checked by the template with a clear message.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 22, 2026 04:03
Add optional templates to the library chart foca-common, all off by
default, so the output of existing values stays the same:

- workerDeployment: Celery worker with the app's image, config overlay,
  MongoDB credentials and security contexts, run with worker.command
- brokerDeployment, brokerService, brokerNetworkPolicy: bundled
  RabbitMQ 4.3 (non-root, read-only root file system, data in an
  emptyDir), reachable only from the app's and the worker's pods
- CELERY_BROKER_URL and CELERY_RESULT_BACKEND (optional) for the app
  and the worker from the Secret broker.existingSecret, which also
  works for external brokers; MongoDB's NetworkPolicy admits the worker

The values schema, the petstore example (values, templates, a worker
entry point and values for CI), tests, a snapshot and the docs cover
them. App charts without worker and broker values render as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Install the petstore chart a second time on kind, with the Celery
worker and the bundled broker (ci/celery-values.yaml). CI creates the
Secret with the broker URL, lints the chart with each CI values file
and checks that the worker logs that it is ready, without errors.

Closes #351

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- CI: ignore Celery's connection retries while the broker starts, keep
  polling if kubectl logs fails, and correct the step's comment
- Docs and values: the broker's Service is named like the app's
  resources with the suffix -broker; fix the wrapping and indentation
- Worker template: same conditional env form as the app's, and a note
  to keep it in line with the app's Deployment
- Tests: broker settings and required image, worker following the
  app's image values, explicit labels and names (incl. truncation)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adds opt-in Celery worker and RabbitMQ support to the foca-common Helm library, wires broker configuration securely through Kubernetes Secrets, updates the petstore example and documentation, and adds comprehensive template and kind-cluster CI coverage while retaining backward-compatible default output.

Sequence diagram for worker startup and broker connection

sequenceDiagram
    participant Worker as CeleryWorker
    participant Secret as KubernetesSecret
    participant Broker as RabbitMQ

    Worker->>Secret: Read CELERY_BROKER_URL
    Worker->>Broker: Connect to AMQP 5672
    alt broker is starting
        Broker-->>Worker: Connection refused
        Worker->>Broker: Retry connection
    else broker is ready
        Broker-->>Worker: AMQP connection accepted
        Worker->>Broker: Declare Celery queues
        Broker-->>Worker: Queues declared
        Worker-->>Worker: Log ready
    end
Loading

Flow diagram for secure broker configuration modes

flowchart TD
    Secret[broker.existingSecret]
    Enabled{Worker or bundled broker enabled?}
    Fail[Helm rendering fails]
    App[App receives CELERY_BROKER_URL]
    Worker[Worker receives broker settings]
    Bundled{broker.enabled?}
    External[Use external broker]
    RabbitMQ[Deploy RabbitMQ and Service]

    Secret --> Enabled
    Enabled -->|No| App
    Enabled -->|Yes, Secret missing| Fail
    Enabled -->|Yes, Secret present| App
    App --> Bundled
    Bundled -->|No| External
    Bundled -->|Yes| RabbitMQ
    Secret -->|username and password| RabbitMQ
    Secret -->|broker URL and optional result backend| Worker
    RabbitMQ --> Worker
Loading

File-Level Changes

Change Details Files
Adds optional Celery worker and bundled RabbitMQ resources to the library chart while preserving existing default rendering.
  • Introduces worker and broker Deployments with configurable images, commands, replicas, resources, storage limits, probes, security contexts, and termination behavior.
  • Adds RabbitMQ Service, ConfigMap workaround for Celery transient queues, Recreate strategy, and release-scoped NetworkPolicies.
  • Adds resource naming, component labels, schema validation, required-secret checks, and collision detection.
  • Injects broker and optional result-backend settings from a Kubernetes Secret into both app and worker; supports external brokers without deploying bundled RabbitMQ.
charts/foca-common/templates/_worker.tpl
charts/foca-common/templates/_broker.tpl
charts/foca-common/templates/_helpers.tpl
charts/foca-common/templates/_deployment.tpl
charts/foca-common/templates/_mongodb.tpl
charts/foca-common/app-values.schema.json
Extends the petstore example to demonstrate and exercise Celery deployment.
  • Adds a Celery application entry point and jobs configuration.
  • Adds thin-chart worker and broker templates, disabled-by-default values, schema entries, and CI-specific Celery values.
  • Documents the Secret layout, broker naming, non-persistent bundled queues, RabbitMQ compatibility setting, and external broker option.
examples/petstore/worker.py
examples/petstore/config.yaml
examples/petstore/chart/values.yaml
examples/petstore/chart/values.schema.json
examples/petstore/chart/templates/worker-deployment.yaml
examples/petstore/chart/templates/broker-deployment.yaml
examples/petstore/chart/templates/broker-configmap.yaml
examples/petstore/chart/templates/broker-networkpolicy.yaml
examples/petstore/chart/templates/broker-service.yaml
examples/petstore/chart/ci/celery-values.yaml
docs/helm-chart.md
docs/configuration/jobs.md
Expands automated validation for the new chart behavior and runtime integration.
  • Adds Celery rendering snapshot coverage and template tests for defaults, settings, secrets, resources, policies, labels, names, security contexts, and validation failures.
  • Keeps existing snapshots unchanged and verifies charts without new values render as before.
  • Updates CI to lint all values files, install the Celery-enabled release, and verify the worker reaches broker-connected readiness without unexpected errors.
charts/foca-common/tests/test_templates.py
charts/foca-common/tests/test_snapshots.py
charts/foca-common/tests/__snapshots__/celery.yaml
.github/workflows/charts.yml

Possibly linked issues

  • #unknown: The PR adds the issue’s requested optional Celery worker and broker templates, Secret wiring, network policies, tests, and documentation.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (be98454) to head (7dc353e).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #381   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           26        26           
  Lines         2337      2337           
=========================================
  Hits          2337      2337           
Flag Coverage Δ
test_unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

The kind installation showed that RabbitMQ 4.3 denies transient
non-exclusive queues by default (deprecated feature
transient_nonexcl_queues), which Celery declares for the rpc:// result
backend (FOCA's default) and for remote control, so the worker failed
to start. Permit them in a config file of the bundled broker (new
template brokerConfigMap, mounted into /etc/rabbitmq/conf.d, with a
checksum annotation), and document the setting for external brokers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 22, 2026 02:31

@sourcery-ai sourcery-ai 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.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="charts/foca-common/templates/_worker.tpl" line_range="52-69" />
<code_context>
+      - image: {{ include "foca-common.image" . | quote }}
</code_context>
<issue_to_address>
**Disconnected workers report ready**

When the broker is unavailable or unreachable and Celery keeps retrying without exiting, celery retries its broker connection while the worker container stays running, and with no readiness probe Kubernetes marks the pod Ready and the Deployment available. Rollouts and health checks therefore report success while queued tasks are not processed.

Add a readiness check that reflects successful broker connectivity, or otherwise expose worker readiness so Kubernetes does not treat a disconnected worker as available.
</issue_to_address>

### Comment 2
<location path="charts/foca-common/tests/test_templates.py" line_range="1056-1061" />
<code_context>
+        "broker"
+    )
+    (rule,) = policy["ingress"]
+    peers = [peer["podSelector"]["matchLabels"] for peer in rule["from"]]
+    assert [labels["app.kubernetes.io/component"] for labels in peers] == [
+        "app",
+        "worker",
+    ]
+    assert {labels["app.kubernetes.io/instance"] for labels in peers} == {"petstore"}
+    assert rule["ports"] == [{"port": 5672, "protocol": "TCP"}]
+    docs = render(*CELERY, "--set", "broker.networkPolicy.enabled=false")
</code_context>
<issue_to_address>
**Network policy tests miss app identity**

When a policy selector retains component and instance labels but drops `app.kubernetes.io/name`, `test_broker_network_policy` at lines 1056–1061 checks peer components and instances, and `test_mongodb_network_policy_admits_worker` at lines 1070–1074 checks only components. Both pass if selectors omit `app.kubernetes.io/name`, allowing unrelated pods with matching labels to connect.

Assert the complete expected selector labels for each allowed peer.

Also at `charts/foca-common/tests/test_templates.py:1070-1074`.
</issue_to_address>

### Comment 3
<location path="charts/foca-common/tests/test_templates.py" line_range="879" />
<code_context>
+
+def test_celery_resources(render: Callable[..., Docs]) -> None:
+    """The worker and the broker add their resources."""
+    assert set(render(*CELERY)) - set(render()) == {
+        ("Deployment", WORKER),
+        ("Deployment", BROKER),
</code_context>
<issue_to_address>
**Celery resource removals go unnoticed**

When a regression removes an existing resource only when Celery is enabled, `test_celery_resources` at line 879 subtracts the default resources from the Celery render, so any default resources removed by that render are never checked and the test still passes as long as the new resources appear.

Assert that the Celery render contains the complete default resource set as well as the new resources.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and the bundled broker stores queued tasks in an emptyDir, so replacing its pod permanently loses any tasks still queued there; reverting the chart cannot restore them. The loss is limited to tasks in that broker’s queue, and the bundled broker is opt-in.

Blocking findings: charts/foca-common/templates/_worker.tpl:69, charts/foca-common/tests/test_templates.py:1061, charts/foca-common/tests/test_templates.py:879


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

uniqueg and others added 2 commits October 22, 2026 04:35
Address Sourcery's review: worker.readinessProbe and
worker.livenessProbe (Kubernetes probe specs, none by default) let
deployments check the worker's broker connection, e.g., with celery
inspect ping. The tests now compare the NetworkPolicies' peer selectors
in full and check that the Celery render keeps all default resources.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 760314e into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the feat/chart-celery branch October 22, 2026 02:44
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