You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Python: injected clock for runtime cadence + ctx.clock handler time (bound to engine clock) #258
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.
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.
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.pyL31, 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.pyL157, L292; test_job_worker.pyL202).
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.pyL53JobContext (attrs), L80ConnectedJobContext, L117SyncJobContext; 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.tomlL72; 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), notgenerated/ — otherwise it flags the copied output and the fix location is wrong.
auth.pyL325/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.pyiL766-767 (sync), L2058-2059 (async); mapped at examples/operation-map.jsonL1024, L1038.
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.pyL350/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.pyL36/L42 already matches the agreed interface, with injection points at L119 and L378 and a working fake clock at tests/acceptance/test_backpressure.pyL31. 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.pyL898) 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.pyL792 stays ambient; seeded-RNG is a follow-up.
auth.pyL325/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/.
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
classClock(Protocol):
defnow(self) ->float:
"""Wall-clock seconds since the epoch. Never decreases."""asyncdefsleep(self, seconds: float) ->None:
"""Async cadence. Must not resolve synchronously."""defsleep_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.
Activity
emilyoram commentedon Aug 26, 2026
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 undergenerated/camunda_orchestration_sdk/runtime/(hooks/post_gen/0300_copy_runtime.pycopies it). Read-only pass, no code changed.Wall-clock call sites
Job worker —
runtime/job_worker.pyL800startup-jitterasyncio.sleep,L898poll-intervalasyncio.sleep,L792random.uniformjitterEventual poller —
runtime/eventual.py, both paths:L139,L153,L171time.monotonic;L163,L179,L189time.sleepL240,L254,L272time.monotonic;L264,L280,L290asyncio.sleepBackpressure backoff —
runtime/backpressure.pyL170(sync),L428(async)Auth —
runtime/auth.pyL258(sync),L491(async)time.timevia_now;L325,L562strftime/gmtimein tarpit metadataTyped variables —
runtime/typed_variables.pyL350,L362,L364(sync);L426,L438,L440(async)No
asyncio.wait_for,asyncio.timeout,loop.call_later,time.perf_counter,datetime.now, ordatetime.utcnowanywhere inruntime/orhooks/.What already exists — this is the seed for the whole contract
runtime/backpressure.pyalready has the cleanest injected clock of any of the five SDKs:L36,L42L119L378tests/acceptance/test_backpressure.pyL31,L114,L299Recommend generalising this Protocol rather than designing a new one. Everything else calls ambient primitives directly and tests on real time (
test_eventual_consistency.pyL157,L292;test_job_worker.pyL202).Auth has
_nowwrappers but no constructor-level injection point.The distinguishing cost here: sync + async duplication
Four subsystems are duplicated across sync and async paths:
eventual_polleventual_poll_asyncBackpressureManagerAsyncBackpressureManagersearch_variables_as_dto_sync..._asyncOnly 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.pyL53JobContext(attrs),L80ConnectedJobContext,L117SyncJobContext; worker atL428.Recommend the optional-with-default route, and adding
clockto all three context classes together so sync and async handlers get the same surface.Lint guard: needs a new rule family
pyproject.tomlL72; selected families atL84areB,RUF,ASYNC,S; per-file ignores atL94.ASYNCalone is not sufficient — it catches blocking calls inside async contexts, not sync time primitives generally.TID(flake8-tidy-imports) and configurebanned-api(TID251) for thetime/asynciosymbols.L94.runtime/(source of truth), notgenerated/— otherwise it flags the copied output and the fix location is wrong.auth.pyL325/L562are observational formatting, not cadence, and will need exempting.Engine endpoints
Present as
pin_clock/reset_clockon both clients —stubs/camunda_orchestration_sdk/client.pyiL766-767(sync),L2058-2059(async); mapped atexamples/operation-map.jsonL1024,L1038.emilyoram commentedon Aug 26, 2026
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.pymoves offtime.monotonic—L139/L153/L171(sync) andL240/L254/L272(async) — onto the injected clock's epoch-msnow(). Same forruntime/typed_variables.pyL350/L362andL426/L438. Auth already usestime.timeand conforms.Python and Rust are the only two SDKs needing this conversion; JS, Go, and C# were already wall-clock.
The backpressure
Protocolis the shape.runtime/backpressure.pyL36/L42already matches the agreed interface, with injection points atL119andL378and a working fake clock attests/acceptance/test_backpressure.pyL31. 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 alongsidenow()andsleep().Ruling 3 replaces the naive loop. The job-worker poll loop (
job_worker.pyL898) and both eventual paths compute the next deadline asmax(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
Protocolshould expose both sync and asyncsleepvariants rather than splitting into two Protocols, so context classes carry one attribute.Jitter is deferred.
random.uniformatjob_worker.pyL792stays ambient; seeded-RNG is a follow-up.auth.pyL325/L562are exempt by category (observationalstrftime/gmtimeformatting). Declare in the per-file-ignores rather than suppressing inline.The Ruff guard from my audit is unchanged: enable
TIDand configurebanned-api(TID251) —ASYNCalone is insufficient — and point it atruntime/, notgenerated/.emilyoram commentedon Aug 28, 2026
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 intogenerated/camunda_orchestration_sdk/runtime/byhooks/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
asyncio.sleeptime.sleeptime.monotonictime.timeeventual.pytyped_variables.pyauth.pyjob_worker.pybackpressure.pyNote
backpressure.pyimports asimport 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:with
Environment.TickCount,TimeProvider.GetTimestamp()andGetElapsedTimebanned for the same reason. JS'screateLiveClockreadsDate.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 /clocktakes epoch milliseconds). Cadence measured on a monotonic source cannot follow a pinned engine, so deliverable 4 of the contract would be unreachable. Python's 12time.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
Both sleep forms are needed:
eventual.pyandtyped_variables.pyeach have a sync and an async path, and the SDK shipsCamundaClientandCamundaAsyncClientplus 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-levellive_clock. Acceptclock=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.pyhas ~46 timeout/drain references to triage — the shutdown drain is the shape that must stay real, or a pinned clock hangsstop()forever.3 —
ctx.clockon 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 toruntime/. Verified empirically that it catches every form, including the alias inbackpressure.py:No custom plugin needed;
extend-selectalready carriesB,RUF,ASYNC,S, soTIDis a one-line addition. Exemptions go per-line with# noqa: TID251and a reason, not by path — a path exemption blinds the rest of the file.5 — Engine-bound clock.
EngineClock(target, start=None)whosesleepadvances engine time viapin_clockinstead of waiting, pluspin()andreset(). 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 replacesasyncio.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.sleepcannot be interrupted the wayasyncio.sleepcan be cancelled. The syncsleep_syncon 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.
SyncJobContextruns 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.
feat: add the injected Clock protocol, live implementation and inject…
feat: resolve runtime cadence through the injected clock (#271)
docs: say what a handler wait is for (#276)