Skip to content

Python: injected clock for runtime cadence + ctx.clock handler time (bound to engine clock) #258

Closed

Description

@jwulf

Part of the cross-SDK injected-clock contract: camunda/orchestration-cluster-api-js#450.

Goal

Resolve client-runtime cadence and handler-facing time through an injected clock (async sleep + now) bound to the engine clock under test.

Wall-clock call sites (current main, generated/camunda_orchestration_sdk/runtime/)

  • job_worker.py:806 asyncio.sleep(jitter); :904 asyncio.sleep(1) poll interval
  • eventual.py:139,153,171,240,254 time.monotonic(); :163,179,189 time.sleep(...) (sync path); async path uses asyncio.sleep
  • typed_variables.py:350,362,364,426,438,440 time.monotonic() + time.sleep/asyncio.sleep
  • backpressure.py:428 asyncio.sleep(backoff)
  • auth.py:257,496 time.time()

Deliverables

  • A Clock protocol (now() -> float, async sleep(seconds, cancel?), and a sync variant where needed); live impl wraps asyncio.sleep/time.monotonic; test/embedded impl bound to the engine clock.
  • Thread the injected clock through job_worker/eventual/typed_variables/backpressure/auth instead of ambient asyncio.sleep/time.*.
  • Expose ctx.clock (now() + await sleep(), no interval helper) on the job-handler context.
  • Ruff lint (flake8-forbidden/custom) banning asyncio.sleep/time.sleep/time.monotonic/time.time in runtime + handler code, single exception = the live clock module.
  • Note: runtime/ is under generated/ — confirm whether these are hand-maintained or code-generated, and put the fix at the generator/template layer if generated so it survives regeneration.
  • Document: ctx.clock.sleep = short in-handler coordination; long/business waits = BPMN timers.

Activity

  1. emilyoram commented on Aug 26, 2026

    @emilyoram
    Collaborator

    Current-state audit for this slice

    Inventory against the contract in camunda/orchestration-cluster-api-js#450. Taken against the source runtime at runtime/, not the generated copy under generated/camunda_orchestration_sdk/runtime/ (hooks/post_gen/0300_copy_runtime.py copies it). Read-only pass, no code changed.

    Wall-clock call sites

    Job worker — runtime/job_worker.py L800 startup-jitter asyncio.sleep, L898 poll-interval asyncio.sleep, L792 random.uniform jitter

    Eventual poller — runtime/eventual.py, both paths:

    • sync: L139, L153, L171 time.monotonic; L163, L179, L189 time.sleep
    • async: L240, L254, L272 time.monotonic; L264, L280, L290 asyncio.sleep

    Backpressure backoff — runtime/backpressure.py L170 (sync), L428 (async)

    Auth — runtime/auth.py L258 (sync), L491 (async) time.time via _now; L325, L562 strftime/gmtime in tarpit metadata

    Typed variables — runtime/typed_variables.py L350, L362, L364 (sync); L426, L438, L440 (async)

    No asyncio.wait_for, asyncio.timeout, loop.call_later, time.perf_counter, datetime.now, or datetime.utcnow anywhere in runtime/ or hooks/.

    What already exists — this is the seed for the whole contract

    runtime/backpressure.py already has the cleanest injected clock of any of the five SDKs:

    • Clock Protocol + default live impl at L36, L42
    • injected in the sync manager constructor at L119
    • injected in the async manager constructor at L378
    • exercised by a deterministic fake clock in tests: tests/acceptance/test_backpressure.py L31, L114, L299

    Recommend generalising this Protocol rather than designing a new one. Everything else calls ambient primitives directly and tests on real time (test_eventual_consistency.py L157, L292; test_job_worker.py L202).

    Auth has _now wrappers but no constructor-level injection point.

    The distinguishing cost here: sync + async duplication

    Four subsystems are duplicated across sync and async paths:

    Subsystem Sync Async
    Eventual poller eventual_poll eventual_poll_async
    Backpressure BackpressureManager AsyncBackpressureManager
    Typed variables search_variables_as_dto_sync ..._async
    Auth validity/cooldown sync provider async provider

    Only the job-worker poll loop is async-only.

    So this slice needs either one Protocol exposing both sleep/asleep, or two Protocols — and roughly double the wiring of any other language. Worth reflecting in the estimate; Python is the most expensive of the five, C# the cheapest.

    Separately: the worker's thread/process handler execution strategies mean a virtual clock will not reach handlers running off the event loop. #450 doesn't address this. Either scope it out or specify the marshalling.

    Handler context: additive path available

    • runtime/job_worker.py L53 JobContext (attrs), L80 ConnectedJobContext, L117 SyncJobContext; worker at L428.
    • These are attrs, not pydantic. An optional field with a default is source-compatible for handler call sites, though still a public shape change. A required field would break the factory paths that construct them.

    Recommend the optional-with-default route, and adding clock to all three context classes together so sync and async handlers get the same surface.

    Lint guard: needs a new rule family

    • Ruff is configured at pyproject.toml L72; selected families at L84 are B, RUF, ASYNC, S; per-file ignores at L94.
    • ASYNC alone is not sufficient — it catches blocking calls inside async contexts, not sync time primitives generally.
    • Need to enable TID (flake8-tidy-imports) and configure banned-api (TID251) for the time / asyncio symbols.
    • Single live-clock module exception is expressible via the existing per-file-ignores block at L94.
    • The guard must target runtime/ (source of truth), not generated/ — otherwise it flags the copied output and the fix location is wrong.

    auth.py L325/L562 are observational formatting, not cadence, and will need exempting.

    Engine endpoints

    Present as pin_clock / reset_clock on both clients — stubs/camunda_orchestration_sdk/client.pyi L766-767 (sync), L2058-2059 (async); mapped at examples/operation-map.json L1024, L1038.

  2. emilyoram commented on Aug 26, 2026

    @emilyoram
    Collaborator

    Contract settled — deltas for this slice

    The contract questions are resolved on camunda/orchestration-cluster-api-js#450 (amendment). Three rulings: client clock drives the engine, wall-clock time only, recurring loops coalesce missed ticks. What changes for Python relative to my audit above:

    The eventual poller needs converting. Ruling 2 is wall-clock only, so runtime/eventual.py moves off time.monotonic — L139/L153/L171 (sync) and L240/L254/L272 (async) — onto the injected clock's epoch-ms now(). Same for runtime/typed_variables.py L350/L362 and L426/L438. Auth already uses time.time and conforms.

    Python and Rust are the only two SDKs needing this conversion; JS, Go, and C# were already wall-clock.

    The backpressure Protocol is the shape. runtime/backpressure.py L36/L42 already matches the agreed interface, with injection points at L119 and L378 and a working fake clock at tests/acceptance/test_backpressure.py L31. Promote it rather than defining a new one — it is the best-formed seam of the five SDKs and the amendment names it as such.

    The interface gained a third operation. A deadline primitive (clock.timeout(d)) is required alongside now() and sleep().

    Ruling 3 replaces the naive loop. The job-worker poll loop (job_worker.py L898) and both eventual paths compute the next deadline as max(previous + interval, now()). Required test: advance 25h across a 5s poller, assert exactly one poll.

    Thread/process execution strategies are out of scope for v1. Decided — a virtual clock cannot cross a thread or process boundary. The worker's own poll cadence is still in scope; handler-facing time inside an off-loop handler is not. Exempt those entry points in the Ruff guard deliberately.

    The sync/async duplication is unchanged and still the defining cost here. Four subsystems doubled (eventual, backpressure, typed variables, auth validity). The Protocol should expose both sync and async sleep variants rather than splitting into two Protocols, so context classes carry one attribute.

    Jitter is deferred. random.uniform at job_worker.py L792 stays ambient; seeded-RNG is a follow-up.

    auth.py L325/L562 are exempt by category (observational strftime/gmtime formatting). Declare in the per-file-ignores rather than suppressing inline.

    The Ruff guard from my audit is unchanged: enable TID and configure banned-api (TID251) — ASYNC alone is insufficient — and point it at runtime/, not generated/.

  3. emilyoram commented on Aug 28, 2026

    @emilyoram
    Collaborator

    Implementation plan

    Groundwork verified against main, not assumed.

    The open question in the issue is settled

    runtime/ at the repo root is hand-written, copied verbatim into generated/camunda_orchestration_sdk/runtime/ by hooks/post_gen/0300_copy_runtime.py. The work goes at the top level; no generator or template changes, and regeneration will not overwrite it.

    Actual inventory — 25 sites

    File asyncio.sleep time.sleep time.monotonic time.time
    eventual.py 3 3 6 —
    typed_variables.py 1 1 6 —
    auth.py — — — 2
    job_worker.py 2 — — —
    backpressure.py 1 — — —

    Note backpressure.py imports as import time as _time_module, so any name-based approach has to resolve aliases.


    Correction: a single wall-clock source, not monotonic + wall

    I initially proposed monotonic() for durations and a separate wall-clock read for token expiry. That is wrong for this contract, and the two completed slices both went the other way.

    C# bans monotonic timing outright in BannedSymbols.txt:

    T:System.Diagnostics.Stopwatch — Monotonic timing. Ruling 2 is wall-clock only: subtract two timeProvider.GetUtcNow() readings.

    with Environment.TickCount, TimeProvider.GetTimestamp() and GetElapsedTime banned for the same reason. JS's createLiveClock reads Date.now(). Both then apply a 1/16 slew so a backward wall-clock correction is absorbed rather than moving readings backwards.

    The reason is decisive here: the engine clock is wall time (PUT /clock takes epoch milliseconds). Cadence measured on a monotonic source cannot follow a pinned engine, so deliverable 4 of the contract would be unreachable. Python's 12 time.monotonic() sites have to become wall-clock reads through the clock.

    This simplifies the protocol rather than complicating it: one time source, not two.


    The protocol

    class Clock(Protocol):
        def now(self) -> float:
            """Wall-clock seconds since the epoch. Never decreases."""
    
        async def sleep(self, seconds: float) -> None:
            """Async cadence. Must not resolve synchronously."""
    
        def sleep_sync(self, seconds: float) -> None:
            """Blocking cadence, for the sync client and thread handlers."""

    Both sleep forms are needed: eventual.py and typed_variables.py each have a sync and an async path, and the SDK ships CamundaClient and CamundaAsyncClient plus three handler contexts (JobContext, ConnectedJobContext, SyncJobContext). Splitting into two protocols would force every call site to know which flavour it holds; one protocol with two sleep methods keeps injection uniform.

    Live implementation wraps time.time() / asyncio.sleep / time.sleep, with the same slew as the other SDKs so readings never go backwards.


    PR slices

    Sized for review, each independently green. The engine binding is specified from the start this time rather than bolted on afterwards.

    1 — Clock protocol, live implementation, injection point.
    runtime/clock.py: the protocol, LiveClock (the single place ambient time is touched, with slew), and a module-level live_clock. Accept clock= on both clients and store it. Plus a conformance suite — the JS slice retrofitted this at the end and it immediately found contract violations in every hand-written clock, so it goes in first here.

    2 — Convert runtime cadence.
    eventual.py, typed_variables.py, backpressure.py, job_worker.py, auth.py. Each site classified before it is touched: cadence (convert), liveness bound (leave on real time), or observational timestamp (leave). job_worker.py has ~46 timeout/drain references to triage — the shutdown drain is the shape that must stay real, or a pinned clock hangs stop() forever.

    3 — ctx.clock on the handler contexts.
    Narrowed to now + both sleeps, no engine-pinning surface. Attached to all three contexts. Document the line from the contract: short in-handler coordination, not business waits — those are BPMN timers.

    4 — Ruff guard.
    flake8-tidy-imports.banned-api (TID251) under [tool.ruff.lint], scoped to runtime/. Verified empirically that it catches every form, including the alias in backpressure.py:

    TID251 `time.monotonic` is banned  -> time.monotonic()
    TID251 `time.monotonic` is banned  -> _t.monotonic()          # alias resolved
    TID251 `time.monotonic` is banned  -> from time import monotonic
    TID251 `asyncio.sleep` is banned   -> await asyncio.sleep(1)
    TID251 `time.sleep` is banned      -> time.sleep(1)
    TID251 `time.time` is banned       -> time.time()
    

    No custom plugin needed; extend-select already carries B, RUF, ASYNC, S, so TID is a one-line addition. Exemptions go per-line with # noqa: TID251 and a reason, not by path — a path exemption blinds the rest of the file.

    5 — Engine-bound clock.
    EngineClock(target, start=None) whose sleep advances engine time via pin_clock instead of waiting, plus pin() and reset(). Acceptance test is the incident from the umbrella: a worker polling for something that never becomes ready, over a minute of engine time, completing in real milliseconds.


    Python-specific risks

    The engine binding is JS-shaped, not C#-shaped — this is the good case. C# had to override TimeProvider.CreateTimer, which carries a schedule/reschedule/dispose/fault lifecycle, and review found ten defects, seven of them in that lifecycle. Python replaces asyncio.sleep, a single call with no lifecycle, so the JS experience transfers and the C# one does not. (Go and Rust will be the C# shape.)

    The sync path has no cancellation. time.sleep cannot be interrupted the way asyncio.sleep can be cancelled. The sync sleep_sync on an engine clock will issue a blocking pin; worth deciding in slice 1 whether the sync surface gets cancellation semantics at all, or documents that it does not.

    Thread handlers. SyncJobContext runs handlers on threads, so a shared engine clock is touched concurrently. The pin serialisation the other two SDKs needed applies here too — a lock rather than a semaphore, since the sync path is blocking.


    Happy to start on slice 1 unless anything above looks wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions