:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(cdp): remove cyclotron v1 rust crates and napi binding (#83200)
Daniel Marchukdeae28c3708e
diff --git a/.dockerignore b/.dockerignoreindex ed5b8017545e..d91c3cd4338c 100644--- a/.dockerignore+++ b/.dockerignore@@ -113,9 +113,6 @@ docs/**/node_modules**/__pycache__rust/.envrust/.github-rust/cyclotron-node/dist-rust/cyclotron-node/index.node-rust/cyclotron-node/node_modulesrust/dockerrust/target**/__snapshots__diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex 9fbbf8ea2427..cffc76b6760d 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -22,10 +22,6 @@dockerfile: ./rust/Dockerfile.sqlx-migrateproject: jmsz6gms8g-- image: cyclotron-janitor- dockerfile: ./rust/Dockerfile- project: r4zm8vtlbw-- image: property-defs-rsdockerfile: ./rust/Dockerfileproject: vznmbshh6qdiff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 3b2925977f50..060816b013cb 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -1145,8 +1145,8 @@ const feProduct = (product) => `fe:product:${product}`const rustCrate = (crate) => `rust:crate:${crate}`// The lanes that import a native module built from the cargo workspace.-// nodejs/package.json is the only dependent of the three binding packages-// (@posthog/cyclotron, @posthog/hogvm-node, @posthog/replay-anonymizer) today,+// nodejs/package.json is the only dependent of the two binding packages+// (@posthog/hogvm-node, @posthog/replay-anonymizer) today,// and the test suite re-derives that from pnpm-workspace.yaml so a second// dependent fails there rather than silently going unclaimed here.const NATIVE_BINDING_CONSUMER_LANES = ['node:ingestion']diff --git a/.github/workflows/ci-migrations-service-separation-check.yml b/.github/workflows/ci-migrations-service-separation-check.ymlindex 98ebb6fb6714..3f5cace4e61a 100644--- a/.github/workflows/ci-migrations-service-separation-check.yml+++ b/.github/workflows/ci-migrations-service-separation-check.yml@@ -60,7 +60,6 @@ jobs:sqlx_migrations:- 'rust/persons_migrations/*.sql'- 'rust/behavioral_cohorts_migrations/*.sql'- - 'rust/cyclotron-core/migrations/*.sql'- 'rust/cyclotron-node-migrations/*.sql'nodejs:- 'nodejs/**'@@ -77,7 +76,6 @@ jobs:- 'rust/**'- '!rust/persons_migrations/**'- '!rust/behavioral_cohorts_migrations/**'- - '!rust/cyclotron-core/migrations/**'- '!rust/cyclotron-node-migrations/**'- name: Check for conflicting changesdiff --git a/.github/workflows/ci-nodejs-container.yml b/.github/workflows/ci-nodejs-container.ymlindex 9d5fd169288b..c7143bb27af0 100644--- a/.github/workflows/ci-nodejs-container.yml+++ b/.github/workflows/ci-nodejs-container.yml@@ -11,7 +11,6 @@ on:- 'common/esbuilder/**'- 'common/replay-shared/**'- 'common/replay-headless/**'- - 'rust/cyclotron-node/**'- 'rust/common/hogvm/**'- 'rust/replay-anonymizer/**'- 'rust/replay-anonymizer-node/**'@@ -63,7 +62,6 @@ jobs:- 'common/esbuilder/**'- 'common/replay-shared/**'- 'common/replay-headless/**'- - 'rust/cyclotron-node/**'- 'rust/common/hogvm/**'- 'rust/replay-anonymizer/**'- 'rust/replay-anonymizer-node/**'diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex 162b9d0c70f9..fc7c5ac6f4cf 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -64,8 +64,6 @@ jobs:- 'rust/replay-anonymizer-node/**'# These native addons are built by Turbo before Node.js tests. Their Rust# dependencies are not part of the ingestion consumer's targeted e2e set.- - 'rust/cyclotron-core/**'- - 'rust/cyclotron-node/**'- 'rust/common/hogvm/**'- '**/crosslang/**'# The clientwarnings consumer e2e replays capture's warning envelope fromdiff --git a/.github/workflows/ci-recording-rasterizer-container.yml b/.github/workflows/ci-recording-rasterizer-container.ymlindex 9f50430dd9a0..1be91c7dd1e9 100644--- a/.github/workflows/ci-recording-rasterizer-container.yml+++ b/.github/workflows/ci-recording-rasterizer-container.yml@@ -11,8 +11,6 @@ on:- 'common/esbuilder/**'- 'common/replay-shared/**'- 'common/replay-headless/**'- - 'rust/cyclotron-node/**'- - 'rust/cyclotron-core/**'- 'Dockerfile.recording-rasterizer'- '.github/workflows/ci-recording-rasterizer-container.yml'- 'bin/turbo'@@ -68,8 +66,6 @@ jobs:- 'common/esbuilder/**'- 'common/replay-shared/**'- 'common/replay-headless/**'- - 'rust/cyclotron-node/**'- - 'rust/cyclotron-core/**'- 'Dockerfile.recording-rasterizer'- '.github/workflows/ci-recording-rasterizer-container.yml'- 'bin/turbo'diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex b73147236a6e..80bc78a30ad2 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -135,9 +135,6 @@ jobs:"common-s3": 31,"cohort-core": 45,"cohort-seeder": 60,- "cyclotron-core": 17,- "cyclotron-janitor": 139,- "cyclotron-node": 31,"cymbal": 168,# Compile-heavy (deltalake dependency tree), light tests."deltalite-core": 180,diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.ymlindex 4a96c9c79656..4f6648292143 100644--- a/.github/workflows/rust-docker-build.yml+++ b/.github/workflows/rust-docker-build.yml@@ -126,9 +126,6 @@ jobs:- release: capture-replaydigest_key: capturevalues_key: image- - release: cyclotron- digest_key: cyclotron-janitor- values_key: janitor_image- release: property-defs-rsdigest_key: property-defs-rsvalues_key: imagediff --git a/Dockerfile.node b/Dockerfile.nodeindex db0114d24b58..952bea2c0321 100644--- a/Dockerfile.node+++ b/Dockerfile.node@@ -71,8 +71,6 @@ COPY ./common/replay-shared/tsconfig.json ./common/replay-shared/COPY ./common/replay-headless/src/ ./common/replay-headless/src/COPY ./common/replay-headless/build.mjs ./common/replay-headless/-# Build cyclotron first-RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/cyclotron build# Build the rust hogvm napi addon (shadow execution of transformations)RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/hogvm-node build@@ -130,9 +128,6 @@ RUN echo ${COMMIT_HASH:-unknown} > /code/commit.txt# Add in the compiled nodejs & its runtime dependencies from the build stage-COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/dist /code/rust/cyclotron-node/dist-COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/package.json /code/rust/cyclotron-node/package.json-COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/index.node /code/rust/cyclotron-node/index.nodeCOPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/package.json /code/rust/common/hogvm/node/package.jsonCOPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/index.js /code/rust/common/hogvm/node/index.jsCOPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/index.node /code/rust/common/hogvm/node/index.nodediff --git a/Dockerfile.recording-rasterizer b/Dockerfile.recording-rasterizerindex e0665dd85d95..6efd902eea3f 100644--- a/Dockerfile.recording-rasterizer+++ b/Dockerfile.recording-rasterizer@@ -67,7 +67,6 @@ COPY ./common/replay-shared/tsconfig.json ./common/replay-shared/COPY ./common/replay-headless/src/ ./common/replay-headless/src/COPY ./common/replay-headless/build.mjs ./common/replay-headless/-RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/cyclotron buildRUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/replay-headless buildRUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/nodejs build@@ -153,9 +152,6 @@ ARG COMMIT_HASHRUN echo ${COMMIT_HASH:-unknown} > /code/commit.txt# Copy compiled nodejs from build stage-COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/dist /code/rust/cyclotron-node/dist-COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/package.json /code/rust/cyclotron-node/package.json-COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/index.node /code/rust/cyclotron-node/index.nodeCOPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/dist /code/common/plugin_transpiler/distCOPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/node_modules /code/common/plugin_transpiler/node_modulesCOPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/package.json /code/common/plugin_transpiler/package.jsondiff --git a/bin/dev-sandbox.sb b/bin/dev-sandbox.sbindex e0e671c5aba9..ee3ce3b76a46 100644--- a/bin/dev-sandbox.sb+++ b/bin/dev-sandbox.sb@@ -73,8 +73,8 @@(literal (string-append (param "HOME") "/.gitconfig"))(literal (string-append (param "HOME") "/.config/git/config"))(literal (string-append (param "HOME") "/.gitconfig.local")) ; common [include] target of ~/.gitconfig- ;; cargo registry/git cache — the cyclotron-node native module is built with- ;; cargo during the nodejs service prestart. (crates.io token re-denied below.)+ ;; cargo registry/git cache — native modules and rust services are built with+ ;; cargo during local dev. (crates.io token re-denied below.)(subpath (string-append (param "HOME") "/.cargo")));; Canonicalization (realpath) lstats every path component, so uv resolving itsdiff --git a/bin/migrate b/bin/migrateindex 03d0806e8c26..f75ba7ad02ce 100755--- a/bin/migrate+++ b/bin/migrate@@ -26,12 +26,6 @@ fi# NOTE when running in docker, rust might not exist so we need to check for itif [ -d "$SCRIPT_DIR/../rust/bin" ] && [ "${DEPLOYMENT:-}" != "hobby" ]; thenif run_scope "cyclotron"; then- bash $SCRIPT_DIR/../rust/bin/migrate-cyclotron- if [ $? -ne 0 ]; then- echo "Error in rust/bin/migrate-cyclotron, exiting."- exit 1- fi-bash $SCRIPT_DIR/../rust/bin/migrate-cyclotron-nodeif [ $? -ne 0 ]; thenecho "Error in rust/bin/migrate-cyclotron-node, exiting."diff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 198cd551ebc1..fd12d036df00 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -250,16 +250,6 @@ procs:layer: Infrastructuretech: Docker- cyclotron-janitor:- shell: |-- bin/wait-for-docker && \- bin/start-rust-service cyclotron-janitor- capability: cyclotron- ready_pattern: 'Running janitor loop'- groups:- layer: Processing- tech: Rust-ai-gateway:shell: 'bin/wait-for-docker && bin/start-ai-gateway'capability: ai_gatewaydiff --git a/bin/start-rust-service b/bin/start-rust-serviceindex 9a8df02963c0..b16f094d4583 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -198,18 +198,6 @@ case "$RS_SVC" inexport ALLOW_INTERNAL_IPS="true";;- cyclotron-janitor)- SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}- export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL- export RUST_BACKTRACE=1- export KAFKA_HOSTS="$DEFAULT_KAFKA"- export KAFKA_TOPIC=clickhouse_app_metrics2- export DATABASE_URL="${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron}"- export BIND_PORT=3310 # default 3303 collides with property-vals-rs in local dev- export DEBUG=1- export ALLOW_INTERNAL_IPS=${ALLOW_INTERNAL_IPS:-true}- ;;-feature-flags)# Download MaxMind DB if it doesn't exist./bin/download-mmdbdiff --git a/docker-compose.base.yml b/docker-compose.base.ymlindex ff0b904bf2ab..a2562084b183 100644--- a/docker-compose.base.yml+++ b/docker-compose.base.yml@@ -784,22 +784,6 @@ services:opensearch:condition: service_healthy- cyclotron-janitor:- image: ghcr.io/posthog/posthog/cyclotron-janitor:master- build:- context: rust/- args:- BIN: cyclotron-janitor- restart: on-failure- environment:- DATABASE_URL: 'postgres://posthog:posthog@db:5432/cyclotron'- KAFKA_HOSTS: 'kafka:9092'- KAFKA_TOPIC: 'clickhouse_app_metrics2'- depends_on:- db:- condition: service_healthy- kafka:- condition: service_startedotel-collector:image: otel/opentelemetry-collector-contrib:0.142.0command: [--config=/etc/otel-collector-config.yaml]diff --git a/docker-compose.dev-full.yml b/docker-compose.dev-full.ymlindex 74f57ff8d859..939502fadf88 100644--- a/docker-compose.dev-full.yml+++ b/docker-compose.dev-full.yml@@ -267,20 +267,6 @@ services:- objectstorage- temporal- cyclotron-janitor:- extends:- file: docker-compose.base.yml- service: cyclotron-janitor- environment:- DATABASE_URL: 'postgres://posthog:posthog@db:5432/cyclotron'- KAFKA_HOSTS: 'kafka:9092'- DEBUG: 1 # Add debug mode like other services- depends_on:- db:- condition: service_healthy- kafka:- condition: service_started-otel-collector:extends:file: docker-compose.base.ymldiff --git a/docker-compose.hobby.yml b/docker-compose.hobby.ymlindex f729000501e1..0fc8a108a3bf 100644--- a/docker-compose.hobby.yml+++ b/docker-compose.hobby.yml@@ -485,22 +485,6 @@ services:- temporal- browserless- cyclotron-janitor:- extends:- file: docker-compose.base.yml- service: cyclotron-janitor- build:- context: ./posthog/rust- logging: *default-logging- environment:- DATABASE_URL: 'postgres://posthog:posthog@db:5432/posthog'- KAFKA_HOSTS: 'kafka:9092'- depends_on:- db:- condition: service_healthy- kafka:- condition: service_started-capture:build:context: ./posthog/rustdiff --git a/nodejs/package.json b/nodejs/package.jsonindex ad1f0f158823..cd8b57718d83 100644--- a/nodejs/package.json+++ b/nodejs/package.json@@ -15,8 +15,6 @@"start:dist": "node dist/index.js","start:dev": "NODE_ENV=dev tsx watch src/index.ts","start:devNoWatch": "NODE_ENV=dev tsx src/index.ts",- "prestart:dev": "pnpm build:cyclotron:dev",- "prestart:devNoWatch": "pnpm build:cyclotron:dev","build": "pnpm clean && pnpm typescript:compile && pnpm typescript:compile-cleanup","clean": "rm -rf dist/*","typescript:compile": "tsc -b && tsc-alias",@@ -33,10 +31,9 @@"setup:dev:clickhouse": "cd .. && DEBUG=1 python manage.py migrate_clickhouse","setup:test": "cd .. && TEST=1 python manage.py setup_test_environment && cd nodejs && pnpm run setup:test:rust","test:full": "docker compose -f ../docker-compose.dev.yml up -d && pnpm setup:test && pnpm test && pnpm test:postgres-parity && pnpm test:rust-ingestion-e2e",- "setup:test:rust": "CYCLOTRON_DATABASE_NAME=test_cyclotron CYCLOTRON_NODE_DATABASE_NAME=test_cyclotron_node PERSONS_DATABASE_NAME=test_persons BEHAVIORAL_COHORTS_DATABASE_NAME=test_behavioral_cohorts ../rust/bin/migrate-entry all --fresh",+ "setup:test:rust": "CYCLOTRON_NODE_DATABASE_NAME=test_cyclotron_node PERSONS_DATABASE_NAME=test_persons BEHAVIORAL_COHORTS_DATABASE_NAME=test_behavioral_cohorts ../rust/bin/migrate-entry all --fresh","setup:test:persons-parity": "PERSONS_DATABASE_NAME=test_persons_parity ../rust/bin/migrate-entry persons --fresh","migrate:persons": "../rust/bin/migrate-persons",- "migrate:cyclotron": "../rust/bin/migrate-cyclotron","migrate:cyclotron-node": "../rust/bin/migrate-cyclotron-node","migrate:behavioral-cohorts": "../rust/bin/migrate-behavioral-cohorts","migrate:rust": "../rust/bin/migrate-entry all",@@ -44,8 +41,6 @@"services:stop": "cd .. && docker compose -f docker-compose.dev.yml down","services:clean": "cd .. && docker compose -f docker-compose.dev.yml rm -v","services": "pnpm services:stop && pnpm services:clean && pnpm services:start",- "build:cyclotron": "pnpm --filter=@posthog/cyclotron package",- "build:cyclotron:dev": "pnpm --filter=@posthog/cyclotron run build:dev","build:hogvm-node": "pnpm --filter=@posthog/hogvm-node build","build:hogvm-node:dev": "pnpm --filter=@posthog/hogvm-node run build:dev","build:replay-anonymizer": "pnpm --filter=@posthog/replay-anonymizer package",@@ -90,7 +85,6 @@"@opentelemetry/sdk-node": "^0.218.0","@opentelemetry/sdk-trace-node": "^2.0.1","@opentelemetry/semantic-conventions": "^1.36.0",- "@posthog/cyclotron": "workspace:*","@posthog/hogvm": "workspace:*","@posthog/hogvm-node": "workspace:*","@posthog/replay-anonymizer": "workspace:*",@@ -200,9 +194,5 @@},"engines": {"node": ">=24 <25"- },- "cyclotron": {- "//This is a short term workaround to ensure that cyclotron changes trigger a rebuild": true,- "version": "0.1.12"}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2aebe3263726..89f73ce8c12c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1582,9 +1582,6 @@ importers:'@opentelemetry/semantic-conventions':specifier: ^1.36.0version: 1.36.0- '@posthog/cyclotron':- specifier: workspace:*- version: link:../rust/cyclotron-node'@posthog/hogvm':specifier: workspace:*version: link:../common/hogvm/typescript@@ -4671,18 +4668,6 @@ importers:rust/common/hogvm/node: {}- rust/cyclotron-node:- devDependencies:- '@types/node':- specifier: ^22.13.14- version: 22.15.17- typescript:- specifier: 6.0.3- version: 6.0.3- undici-types:- specifier: ^7.3.0- version: 7.3.0-rust/replay-anonymizer-node:devDependencies:'@types/node':diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 4a2253685dd6..7cea8724d8d4 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -27,7 +27,6 @@ packages:- services/stripe-app- tools/*- '!tools/hedgebox-dummy'- - rust/cyclotron-node- rust/common/hogvm/node- rust/replay-anonymizer-nodediff --git a/products/replay/skills/debugging-local-replay/references/common-failures.md b/products/replay/skills/debugging-local-replay/references/common-failures.mdindex 3a6c284084c8..e2e94578da9e 100644--- a/products/replay/skills/debugging-local-replay/references/common-failures.md+++ b/products/replay/skills/debugging-local-replay/references/common-failures.md@@ -116,24 +116,6 @@ docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml downhogli start```-## Cargo build lock contention on startup--**Symptoms:** Multiple Node processes show `Blocking waiting for file lock on package cache`-or `Blocking waiting for file lock on build directory` in their phrocs output.-Startup is very slow (5+ minutes) but eventually resolves.--**Cause:** The `bin/posthog-node` script runs `pnpm build:cyclotron:dev` which triggers-`cargo build`. When multiple Node processes start simultaneously (ingestion, ingestion-sessionreplay,-recording-api, nodejs), they all contend on Cargo's file lock.--**Fix:** This is expected on first start or after a Rust code change.-Wait for the first process to finish building — subsequent ones will be fast (cached).-If it persists, pre-build cyclotron before starting phrocs:--```bash-cd rust/cyclotron-node && cargo build-```-## Recorder script build failure**Symptoms:** Browser console shows one or both of:diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 85c69693b768..6127ccf236b4 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3341,58 +3341,6 @@ dependencies = ["cmov",]-[[package]]-name = "cyclotron-core"-version = "0.1.0"-dependencies = [- "chrono",- "common-compression",- "common-metrics",- "csv",- "futures",- "hex",- "serde",- "sqlx",- "thiserror 2.0.18",- "tokio",- "tracing",- "uuid",-]--[[package]]-name = "cyclotron-janitor"-version = "0.1.0"-dependencies = [- "axum 0.7.9",- "chrono",- "common-alloc",- "common-continuous-profiling",- "common-metrics",- "cyclotron-core",- "envconfig",- "eyre",- "health",- "sqlx",- "tokio",- "tracing",- "tracing-subscriber",- "uuid",-]--[[package]]-name = "cyclotron-node"-version = "0.1.0"-dependencies = [- "chrono",- "cyclotron-core",- "neon",- "once_cell",- "serde",- "serde_json",- "tokio",- "uuid",-]-[[package]]name = "cymbal"version = "0.1.0"@@ -4335,16 +4283,6 @@ dependencies = ["pin-project-lite",]-[[package]]-name = "eyre"-version = "0.6.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7cd915d99f24784cdc19fd37ef22b97e3ff0ae756c7e492e9fbfe897d61e2aec"-dependencies = [- "indenter",- "once_cell",-]-[[package]]name = "fallible-iterator"version = "0.2.0"@@ -5960,12 +5898,6 @@ version = "2.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0cfe9645a18782869361d9c8732246be7b410ad4e919d3609ebabdac00ba12c3"-[[package]]-name = "indenter"-version = "0.3.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5"-[[package]]name = "indexmap"version = "1.9.3"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex bdde82af1cbd..8ba440515754 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -39,9 +39,6 @@ members = ["feature-flags","flags-consumer","hypercache-server",- "cyclotron-core",- "cyclotron-node",- "cyclotron-janitor","replay-anonymizer","replay-anonymizer-node","cymbal",@@ -157,7 +154,6 @@ chrono = { version = "0.4.44", features = ["default", "serde"] }chrono-tz = "0.10.1"dashmap = "6.1"envconfig = "0.10.0"-eyre = "0.6.9"flate2 = "1.0"futures = { version = "0.3.29" }futures-timer = "3.0"diff --git a/rust/Dockerfile.sqlx-migrate b/rust/Dockerfile.sqlx-migrateindex e010e51dfd41..1cb5bd8f5d8d 100644--- a/rust/Dockerfile.sqlx-migrate+++ b/rust/Dockerfile.sqlx-migrate@@ -19,20 +19,17 @@ COPY --from=builder /usr/local/cargo/bin/sqlx /usr/local/bin/sqlxWORKDIR /migrationsCOPY ./persons_migrations ./persons_migrations-COPY ./cyclotron-core/migrations ./cyclotron-core/migrationsCOPY ./behavioral_cohorts_migrations ./behavioral_cohorts_migrationsCOPY ./cyclotron-node-migrations ./cyclotron-node-migrationsCOPY ./flags_read_store_migrations ./flags_read_store_migrationsCOPY ./bin/migrate-persons ./bin/migrate-persons-COPY ./bin/migrate-cyclotron ./bin/migrate-cyclotronCOPY ./bin/migrate-cyclotron-node ./bin/migrate-cyclotron-nodeCOPY ./bin/migrate-behavioral-cohorts ./bin/migrate-behavioral-cohortsCOPY ./bin/migrate-entry ./bin/migrate-entryRUN chmod +x /migrations/bin/migrate-entry && \chmod +x /migrations/bin/migrate-persons && \- chmod +x /migrations/bin/migrate-cyclotron && \chmod +x /migrations/bin/migrate-cyclotron-node && \chmod +x /migrations/bin/migrate-behavioral-cohortsdiff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.tomlindex a6285bfd24c1..c2771ab66683 100644--- a/rust/affected-services/determinator-rules.toml+++ b/rust/affected-services/determinator-rules.toml@@ -82,7 +82,6 @@ mark-changed = []globs = ["persons_migrations/**","behavioral_cohorts_migrations/**",- "cyclotron-core/migrations/**","cyclotron-node-migrations/**","flags_read_store_migrations/**","bin/migrate-*",diff --git a/rust/affected-services/src/images.rs b/rust/affected-services/src/images.rsindex dfbe81ec5a52..8caca2cbd34f 100644--- a/rust/affected-services/src/images.rs+++ b/rust/affected-services/src/images.rs@@ -9,7 +9,6 @@ pub const NON_CRATE_IMAGE_TRIGGERS: &[(&str, &[&str])] = &[(&["rust/persons_migrations/","rust/behavioral_cohorts_migrations/",- "rust/cyclotron-core/migrations/","rust/cyclotron-node-migrations/","rust/flags_read_store_migrations/","rust/bin/migrate-",diff --git a/rust/bin/migrate-cyclotron b/rust/bin/migrate-cyclotrondeleted file mode 100755index 4953e72845d0..000000000000--- a/rust/bin/migrate-cyclotron+++ /dev/null@@ -1,12 +0,0 @@-#!/bin/sh-SCRIPT_DIR=$(dirname "$(readlink -f "$0")")--CYCLOTRON_DATABASE_NAME=${CYCLOTRON_DATABASE_NAME:-cyclotron}-CYCLOTRON_DATABASE_URL=${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@localhost:5432/$CYCLOTRON_DATABASE_NAME}--echo "Performing cyclotron migrations for $CYCLOTRON_DATABASE_URL (DATABASE_NAME=$CYCLOTRON_DATABASE_NAME)"--cd $SCRIPT_DIR/..--sqlx database create -D "$CYCLOTRON_DATABASE_URL"-sqlx migrate run -D "$CYCLOTRON_DATABASE_URL" --source cyclotron-core/migrations/diff --git a/rust/bin/migrate-entry b/rust/bin/migrate-entryindex 68f65f812566..67ff05cad327 100755--- a/rust/bin/migrate-entry+++ b/rust/bin/migrate-entry@@ -23,10 +23,9 @@ parse_args() {}show_usage() {- echo "Usage: $0 <all|persons|cyclotron|cyclotron-node|behavioral-cohorts|flags-read-store> [--fresh]"+ echo "Usage: $0 <all|persons|cyclotron-node|behavioral-cohorts|flags-read-store> [--fresh]"echo " all - Run all migrations"echo " persons - Run only persons migrations"- echo " cyclotron - Run only cyclotron migrations"echo " cyclotron-node - Run only cyclotron node migrations"echo " behavioral-cohorts - Run only behavioral cohorts migrations"echo " flags-read-store - Run only flags read store migrations"@@ -101,25 +100,6 @@ run_persons_migrations() {fi}-run_cyclotron_migrations() {- local db_type="cyclotron"- CYCLOTRON_DATABASE_NAME=${CYCLOTRON_DATABASE_NAME:-cyclotron}- CYCLOTRON_DATABASE_URL=${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@localhost:5432/$CYCLOTRON_DATABASE_NAME}-- log_json "info" "Starting migrations" "starting" "$db_type" "\"database_name\":\"$CYCLOTRON_DATABASE_NAME\",\"fresh_mode\":$FRESH_MODE"-- if [ "$FRESH_MODE" = true ]; then- sqlx database reset -y -D "$CYCLOTRON_DATABASE_URL" --source "$MIGRATIONS_BASE/cyclotron-core/migrations/"- log_json "info" "Database reset and migrations completed" "completed" "$db_type"- else- sqlx database create -D "$CYCLOTRON_DATABASE_URL"- log_json "info" "Database created or already exists" "running" "$db_type"-- sqlx migrate run -D "$CYCLOTRON_DATABASE_URL" --source "$MIGRATIONS_BASE/cyclotron-core/migrations/"- log_json "info" "Migrations completed successfully" "completed" "$db_type"- fi-}-run_cyclotron_node_migrations() {local db_type="cyclotron-node"CYCLOTRON_NODE_DATABASE_NAME=${CYCLOTRON_NODE_DATABASE_NAME:-cyclotron_node}@@ -193,9 +173,6 @@ case "$MIGRATION_TYPE" inpersons)run_persons_migrations;;- cyclotron)- run_cyclotron_migrations- ;;cyclotron-node)run_cyclotron_node_migrations;;@@ -207,7 +184,6 @@ case "$MIGRATION_TYPE" in;;all)run_persons_migrations- run_cyclotron_migrationsrun_cyclotron_node_migrationsrun_behavioral_cohorts_migrations;;diff --git a/rust/cyclotron-core/.sqlx/query-075421be22b51c50eb74ac1156175c285bc510766c175b1b8c4e4002e04ff503.json b/rust/cyclotron-core/.sqlx/query-075421be22b51c50eb74ac1156175c285bc510766c175b1b8c4e4002e04ff503.jsondeleted file mode 100644index 35683fb0fb92..000000000000--- a/rust/cyclotron-core/.sqlx/query-075421be22b51c50eb74ac1156175c285bc510766c175b1b8c4e4002e04ff503.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "UPDATE cyclotron_jobs SET last_heartbeat = NOW() WHERE id = $1 AND lock_id = $2",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid"- ]- },- "nullable": []- },- "hash": "075421be22b51c50eb74ac1156175c285bc510766c175b1b8c4e4002e04ff503"-}diff --git a/rust/cyclotron-core/.sqlx/query-0cf1b0b0b21766929e369704f77e496c7033fc03e744d8ee022ff6c2f86156be.json b/rust/cyclotron-core/.sqlx/query-0cf1b0b0b21766929e369704f77e496c7033fc03e744d8ee022ff6c2f86156be.jsondeleted file mode 100644index a8c81abc299a..000000000000--- a/rust/cyclotron-core/.sqlx/query-0cf1b0b0b21766929e369704f77e496c7033fc03e744d8ee022ff6c2f86156be.json+++ /dev/null@@ -1,39 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nINSERT INTO cyclotron_jobs\n (\n id,\n team_id,\n function_id,\n created,\n lock_id,\n last_heartbeat,\n janitor_touch_count,\n transition_count,\n last_transition,\n queue_name,\n state,\n scheduled,\n priority,\n parent_run_id,\n vm_state,\n metadata,\n parameters,\n blob\n )\nVALUES\n ($1, $2, $3, NOW(), NULL, NULL, 0, 0, NOW(), $4, $5, $6, $7, $8, $9, $10, $11, $12)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Int4",- "Uuid",- "Text",- {- "Custom": {- "name": "jobstate",- "kind": {- "Enum": [- "available",- "completed",- "failed",- "running",- "paused",- "canceled"- ]- }- }- },- "Timestamptz",- "Int2",- "Text",- "Bytea",- "Bytea",- "Bytea",- "Bytea"- ]- },- "nullable": []- },- "hash": "0cf1b0b0b21766929e369704f77e496c7033fc03e744d8ee022ff6c2f86156be"-}diff --git a/rust/cyclotron-core/.sqlx/query-229c28c25aec24180c29e6ed636c165376f43116b85921c62b36b1b8e85562b0.json b/rust/cyclotron-core/.sqlx/query-229c28c25aec24180c29e6ed636c165376f43116b85921c62b36b1b8e85562b0.jsondeleted file mode 100644index b6599f458fb8..000000000000--- a/rust/cyclotron-core/.sqlx/query-229c28c25aec24180c29e6ed636c165376f43116b85921c62b36b1b8e85562b0.json+++ /dev/null@@ -1,134 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nWITH available AS (\n SELECT\n id,\n state\n FROM cyclotron_jobs\n WHERE\n state = 'available'::JobState\n AND queue_name = $1\n AND scheduled <= NOW()\n ORDER BY\n priority ASC,\n scheduled ASC\n LIMIT $2\n FOR UPDATE SKIP LOCKED\n)\nUPDATE cyclotron_jobs\nSET\n state = 'running'::JobState,\n lock_id = $3,\n last_heartbeat = NOW(),\n last_transition = NOW(),\n transition_count = transition_count + 1\nFROM available\nWHERE\n cyclotron_jobs.id = available.id\nRETURNING\n cyclotron_jobs.id,\n team_id,\n available.state as \"state: JobState\",\n queue_name,\n priority,\n function_id,\n created,\n last_transition,\n scheduled,\n transition_count,\n NULL::bytea as vm_state,\n metadata,\n parameters,\n blob,\n lock_id,\n last_heartbeat,\n janitor_touch_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "state: JobState",- "type_info": {- "Custom": {- "name": "jobstate",- "kind": {- "Enum": [- "available",- "completed",- "failed",- "running",- "paused",- "canceled"- ]- }- }- }- },- {- "ordinal": 3,- "name": "queue_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "priority",- "type_info": "Int2"- },- {- "ordinal": 5,- "name": "function_id",- "type_info": "Uuid"- },- {- "ordinal": 6,- "name": "created",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "last_transition",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "scheduled",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "transition_count",- "type_info": "Int2"- },- {- "ordinal": 10,- "name": "vm_state",- "type_info": "Bytea"- },- {- "ordinal": 11,- "name": "metadata",- "type_info": "Bytea"- },- {- "ordinal": 12,- "name": "parameters",- "type_info": "Bytea"- },- {- "ordinal": 13,- "name": "blob",- "type_info": "Bytea"- },- {- "ordinal": 14,- "name": "lock_id",- "type_info": "Uuid"- },- {- "ordinal": 15,- "name": "last_heartbeat",- "type_info": "Timestamptz"- },- {- "ordinal": 16,- "name": "janitor_touch_count",- "type_info": "Int2"- }- ],- "parameters": {- "Left": [- "Text",- "Int8",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- true,- false,- false,- false,- false,- null,- true,- true,- true,- true,- true,- false- ]- },- "hash": "229c28c25aec24180c29e6ed636c165376f43116b85921c62b36b1b8e85562b0"-}diff --git a/rust/cyclotron-core/.sqlx/query-2bd3251126625d8dd5143f58f4f9c4bbd0c3a17b7ea65767cf5e7512e5a6ea89.json b/rust/cyclotron-core/.sqlx/query-2bd3251126625d8dd5143f58f4f9c4bbd0c3a17b7ea65767cf5e7512e5a6ea89.jsondeleted file mode 100644index 1bdb0efcc34e..000000000000--- a/rust/cyclotron-core/.sqlx/query-2bd3251126625d8dd5143f58f4f9c4bbd0c3a17b7ea65767cf5e7512e5a6ea89.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "UPDATE cyclotron_jobs SET state = 'running', lock_id = $1, last_heartbeat=NOW() WHERE id = $2 returning queue_name",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "queue_name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "2bd3251126625d8dd5143f58f4f9c4bbd0c3a17b7ea65767cf5e7512e5a6ea89"-}diff --git a/rust/cyclotron-core/.sqlx/query-2ca9ea5e8706bba21b14d9a349f3d0e39f01b19b243d724b09f3ce6617d03dc7.json b/rust/cyclotron-core/.sqlx/query-2ca9ea5e8706bba21b14d9a349f3d0e39f01b19b243d724b09f3ce6617d03dc7.jsondeleted file mode 100644index affa061018ed..000000000000--- a/rust/cyclotron-core/.sqlx/query-2ca9ea5e8706bba21b14d9a349f3d0e39f01b19b243d724b09f3ce6617d03dc7.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "UPDATE cyclotron_jobs SET state = 'available', lock_id = NULL, queue_name = $1 WHERE id = $2",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Uuid"- ]- },- "nullable": []- },- "hash": "2ca9ea5e8706bba21b14d9a349f3d0e39f01b19b243d724b09f3ce6617d03dc7"-}diff --git a/rust/cyclotron-core/.sqlx/query-385e94f4adab0f85174968f6eee873bf6d1d43884cd628df5b36978dd761b025.json b/rust/cyclotron-core/.sqlx/query-385e94f4adab0f85174968f6eee873bf6d1d43884cd628df5b36978dd761b025.jsondeleted file mode 100644index 89a968bc0102..000000000000--- a/rust/cyclotron-core/.sqlx/query-385e94f4adab0f85174968f6eee873bf6d1d43884cd628df5b36978dd761b025.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nSELECT id FROM cyclotron_jobs WHERE state = 'running' AND COALESCE(last_heartbeat, $1) <= $1 AND janitor_touch_count >= $2\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Timestamptz",- "Int2"- ]- },- "nullable": [- false- ]- },- "hash": "385e94f4adab0f85174968f6eee873bf6d1d43884cd628df5b36978dd761b025"-}diff --git a/rust/cyclotron-core/.sqlx/query-4fe6a2cca90f9d4863cb26015716e35debc3041eddc1e81226967cd37a5c3227.json b/rust/cyclotron-core/.sqlx/query-4fe6a2cca90f9d4863cb26015716e35debc3041eddc1e81226967cd37a5c3227.jsondeleted file mode 100644index a1ee168214be..000000000000--- a/rust/cyclotron-core/.sqlx/query-4fe6a2cca90f9d4863cb26015716e35debc3041eddc1e81226967cd37a5c3227.json+++ /dev/null@@ -1,140 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nWITH available AS (\n SELECT\n id,\n state\n FROM cyclotron_jobs\n WHERE\n state = 'available'::JobState\n AND queue_name = $1\n AND scheduled <= NOW()\n ORDER BY\n priority ASC,\n scheduled ASC\n LIMIT $2\n FOR UPDATE SKIP LOCKED\n)\nUPDATE cyclotron_jobs\nSET\n state = 'running'::JobState,\n lock_id = $3,\n last_heartbeat = NOW(),\n last_transition = NOW(),\n transition_count = transition_count + 1\nFROM available\nWHERE\n cyclotron_jobs.id = available.id\nRETURNING\n cyclotron_jobs.id,\n team_id,\n available.state as \"state: JobState\",\n queue_name,\n priority,\n function_id,\n created,\n last_transition,\n scheduled,\n transition_count,\n parent_run_id,\n vm_state,\n metadata,\n parameters,\n blob,\n lock_id,\n last_heartbeat,\n janitor_touch_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "state: JobState",- "type_info": {- "Custom": {- "name": "jobstate",- "kind": {- "Enum": [- "available",- "completed",- "failed",- "running",- "paused",- "canceled"- ]- }- }- }- },- {- "ordinal": 3,- "name": "queue_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "priority",- "type_info": "Int2"- },- {- "ordinal": 5,- "name": "function_id",- "type_info": "Uuid"- },- {- "ordinal": 6,- "name": "created",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "last_transition",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "scheduled",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "transition_count",- "type_info": "Int2"- },- {- "ordinal": 10,- "name": "parent_run_id",- "type_info": "Text"- },- {- "ordinal": 11,- "name": "vm_state",- "type_info": "Bytea"- },- {- "ordinal": 12,- "name": "metadata",- "type_info": "Bytea"- },- {- "ordinal": 13,- "name": "parameters",- "type_info": "Bytea"- },- {- "ordinal": 14,- "name": "blob",- "type_info": "Bytea"- },- {- "ordinal": 15,- "name": "lock_id",- "type_info": "Uuid"- },- {- "ordinal": 16,- "name": "last_heartbeat",- "type_info": "Timestamptz"- },- {- "ordinal": 17,- "name": "janitor_touch_count",- "type_info": "Int2"- }- ],- "parameters": {- "Left": [- "Text",- "Int8",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- true,- false,- false,- false,- false,- true,- true,- true,- true,- true,- true,- true,- false- ]- },- "hash": "4fe6a2cca90f9d4863cb26015716e35debc3041eddc1e81226967cd37a5c3227"-}diff --git a/rust/cyclotron-core/.sqlx/query-54d9afe6952f92b753fbce2c4e8554065b71152389f98d35532c6b332d5a4c9d.json b/rust/cyclotron-core/.sqlx/query-54d9afe6952f92b753fbce2c4e8554065b71152389f98d35532c6b332d5a4c9d.jsondeleted file mode 100644index 6bbfb17e16a2..000000000000--- a/rust/cyclotron-core/.sqlx/query-54d9afe6952f92b753fbce2c4e8554065b71152389f98d35532c6b332d5a4c9d.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nWITH stalled AS (\n SELECT id FROM cyclotron_jobs WHERE state = 'running' AND COALESCE(last_heartbeat, $1) <= $1 FOR UPDATE SKIP LOCKED\n)\nUPDATE cyclotron_jobs\nSET state = 'available', lock_id = NULL, last_heartbeat = NULL, janitor_touch_count = janitor_touch_count + 1\nFROM stalled\nWHERE cyclotron_jobs.id = stalled.id\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Timestamptz"- ]- },- "nullable": []- },- "hash": "54d9afe6952f92b753fbce2c4e8554065b71152389f98d35532c6b332d5a4c9d"-}diff --git a/rust/cyclotron-core/.sqlx/query-78f54fcebc11e2411008448281e4711bdfb8cf78e362ccda8bc14e92324d51f8.json b/rust/cyclotron-core/.sqlx/query-78f54fcebc11e2411008448281e4711bdfb8cf78e362ccda8bc14e92324d51f8.jsondeleted file mode 100644index 44118c740523..000000000000--- a/rust/cyclotron-core/.sqlx/query-78f54fcebc11e2411008448281e4711bdfb8cf78e362ccda8bc14e92324d51f8.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT COUNT(*) FROM cyclotron_jobs WHERE queue_name = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "count",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "78f54fcebc11e2411008448281e4711bdfb8cf78e362ccda8bc14e92324d51f8"-}diff --git a/rust/cyclotron-core/.sqlx/query-9bc5532e30c6d9565386da4f2646498af86a3baedf06ff1aae9800d0d12347c5.json b/rust/cyclotron-core/.sqlx/query-9bc5532e30c6d9565386da4f2646498af86a3baedf06ff1aae9800d0d12347c5.jsondeleted file mode 100644index 90c968752aa9..000000000000--- a/rust/cyclotron-core/.sqlx/query-9bc5532e30c6d9565386da4f2646498af86a3baedf06ff1aae9800d0d12347c5.json+++ /dev/null@@ -1,140 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nWITH available AS (\n SELECT\n id,\n state\n FROM cyclotron_jobs\n WHERE\n state = 'available'::JobState\n AND queue_name = $1\n AND scheduled <= NOW()\n ORDER BY\n priority ASC,\n scheduled ASC\n LIMIT $2\n FOR UPDATE SKIP LOCKED\n)\nUPDATE cyclotron_jobs\nSET\n state = 'running'::JobState,\n lock_id = $3,\n last_heartbeat = NOW(),\n last_transition = NOW(),\n transition_count = transition_count + 1\nFROM available\nWHERE\n cyclotron_jobs.id = available.id\nRETURNING\n cyclotron_jobs.id,\n team_id,\n available.state as \"state: JobState\",\n queue_name,\n priority,\n function_id,\n created,\n last_transition,\n scheduled,\n transition_count,\n parent_run_id,\n NULL::bytea as vm_state,\n metadata,\n parameters,\n blob,\n lock_id,\n last_heartbeat,\n janitor_touch_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "state: JobState",- "type_info": {- "Custom": {- "name": "jobstate",- "kind": {- "Enum": [- "available",- "completed",- "failed",- "running",- "paused",- "canceled"- ]- }- }- }- },- {- "ordinal": 3,- "name": "queue_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "priority",- "type_info": "Int2"- },- {- "ordinal": 5,- "name": "function_id",- "type_info": "Uuid"- },- {- "ordinal": 6,- "name": "created",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "last_transition",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "scheduled",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "transition_count",- "type_info": "Int2"- },- {- "ordinal": 10,- "name": "parent_run_id",- "type_info": "Text"- },- {- "ordinal": 11,- "name": "vm_state",- "type_info": "Bytea"- },- {- "ordinal": 12,- "name": "metadata",- "type_info": "Bytea"- },- {- "ordinal": 13,- "name": "parameters",- "type_info": "Bytea"- },- {- "ordinal": 14,- "name": "blob",- "type_info": "Bytea"- },- {- "ordinal": 15,- "name": "lock_id",- "type_info": "Uuid"- },- {- "ordinal": 16,- "name": "last_heartbeat",- "type_info": "Timestamptz"- },- {- "ordinal": 17,- "name": "janitor_touch_count",- "type_info": "Int2"- }- ],- "parameters": {- "Left": [- "Text",- "Int8",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- true,- false,- false,- false,- false,- true,- null,- true,- true,- true,- true,- true,- false- ]- },- "hash": "9bc5532e30c6d9565386da4f2646498af86a3baedf06ff1aae9800d0d12347c5"-}diff --git a/rust/cyclotron-core/.sqlx/query-aa595eaf28c1f4b872c278be407b59cc00f3125413f4032ac3647a6b5ee1a632.json b/rust/cyclotron-core/.sqlx/query-aa595eaf28c1f4b872c278be407b59cc00f3125413f4032ac3647a6b5ee1a632.jsondeleted file mode 100644index 244f029a6a43..000000000000--- a/rust/cyclotron-core/.sqlx/query-aa595eaf28c1f4b872c278be407b59cc00f3125413f4032ac3647a6b5ee1a632.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT vm_state FROM cyclotron_jobs WHERE id = $1 AND lock_id = $2",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "vm_state",- "type_info": "Bytea"- }- ],- "parameters": {- "Left": [- "Uuid",- "Uuid"- ]- },- "nullable": [- true- ]- },- "hash": "aa595eaf28c1f4b872c278be407b59cc00f3125413f4032ac3647a6b5ee1a632"-}diff --git a/rust/cyclotron-core/.sqlx/query-b420ccc79fa7847f65246adf76a074995829d1372fe8ec1fd683f9524bcebb8b.json b/rust/cyclotron-core/.sqlx/query-b420ccc79fa7847f65246adf76a074995829d1372fe8ec1fd683f9524bcebb8b.jsondeleted file mode 100644index 8a40f0f253f2..000000000000--- a/rust/cyclotron-core/.sqlx/query-b420ccc79fa7847f65246adf76a074995829d1372fe8ec1fd683f9524bcebb8b.json+++ /dev/null@@ -1,26 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT COUNT(*), queue_name FROM cyclotron_jobs WHERE state = 'available' AND scheduled <= NOW() GROUP BY queue_name",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "count",- "type_info": "Int8"- },- {- "ordinal": 1,- "name": "queue_name",- "type_info": "Text"- }- ],- "parameters": {- "Left": []- },- "nullable": [- null,- false- ]- },- "hash": "b420ccc79fa7847f65246adf76a074995829d1372fe8ec1fd683f9524bcebb8b"-}diff --git a/rust/cyclotron-core/.sqlx/query-b8c1b723826d595dca0389d729fa76bd8a7d96d73983a0c408f32f17da5f483b.json b/rust/cyclotron-core/.sqlx/query-b8c1b723826d595dca0389d729fa76bd8a7d96d73983a0c408f32f17da5f483b.jsondeleted file mode 100644index 7733c346c4b7..000000000000--- a/rust/cyclotron-core/.sqlx/query-b8c1b723826d595dca0389d729fa76bd8a7d96d73983a0c408f32f17da5f483b.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO cyclotron_dead_letter_metadata (job_id, original_queue_name, reason, dlq_time) VALUES ($1, $2, $3, NOW())",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "b8c1b723826d595dca0389d729fa76bd8a7d96d73983a0c408f32f17da5f483b"-}diff --git a/rust/cyclotron-core/.sqlx/query-ce036f16a37a41b9dc5a164de0b52345454cd3323568c4bef5b8480380287068.json b/rust/cyclotron-core/.sqlx/query-ce036f16a37a41b9dc5a164de0b52345454cd3323568c4bef5b8480380287068.jsondeleted file mode 100644index 92ecf6b5ab84..000000000000--- a/rust/cyclotron-core/.sqlx/query-ce036f16a37a41b9dc5a164de0b52345454cd3323568c4bef5b8480380287068.json+++ /dev/null@@ -1,134 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nWITH available AS (\n SELECT\n id,\n state\n FROM cyclotron_jobs\n WHERE\n state = 'available'::JobState\n AND queue_name = $1\n AND scheduled <= NOW()\n ORDER BY\n priority ASC,\n scheduled ASC\n LIMIT $2\n FOR UPDATE SKIP LOCKED\n)\nUPDATE cyclotron_jobs\nSET\n state = 'running'::JobState,\n lock_id = $3,\n last_heartbeat = NOW(),\n last_transition = NOW(),\n transition_count = transition_count + 1\nFROM available\nWHERE\n cyclotron_jobs.id = available.id\nRETURNING\n cyclotron_jobs.id,\n team_id,\n available.state as \"state: JobState\",\n queue_name,\n priority,\n function_id,\n created,\n last_transition,\n scheduled,\n transition_count,\n vm_state,\n metadata,\n parameters,\n blob,\n lock_id,\n last_heartbeat,\n janitor_touch_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "state: JobState",- "type_info": {- "Custom": {- "name": "jobstate",- "kind": {- "Enum": [- "available",- "completed",- "failed",- "running",- "paused",- "canceled"- ]- }- }- }- },- {- "ordinal": 3,- "name": "queue_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "priority",- "type_info": "Int2"- },- {- "ordinal": 5,- "name": "function_id",- "type_info": "Uuid"- },- {- "ordinal": 6,- "name": "created",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "last_transition",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "scheduled",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "transition_count",- "type_info": "Int2"- },- {- "ordinal": 10,- "name": "vm_state",- "type_info": "Bytea"- },- {- "ordinal": 11,- "name": "metadata",- "type_info": "Bytea"- },- {- "ordinal": 12,- "name": "parameters",- "type_info": "Bytea"- },- {- "ordinal": 13,- "name": "blob",- "type_info": "Bytea"- },- {- "ordinal": 14,- "name": "lock_id",- "type_info": "Uuid"- },- {- "ordinal": 15,- "name": "last_heartbeat",- "type_info": "Timestamptz"- },- {- "ordinal": 16,- "name": "janitor_touch_count",- "type_info": "Int2"- }- ],- "parameters": {- "Left": [- "Text",- "Int8",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- true,- false,- false,- false,- false,- true,- true,- true,- true,- true,- true,- false- ]- },- "hash": "ce036f16a37a41b9dc5a164de0b52345454cd3323568c4bef5b8480380287068"-}diff --git a/rust/cyclotron-core/.sqlx/query-ed88c403ecb0629c9687fccb09b7e3bc4ecc70af3efd58bf6561e1971ce5aa27.json b/rust/cyclotron-core/.sqlx/query-ed88c403ecb0629c9687fccb09b7e3bc4ecc70af3efd58bf6561e1971ce5aa27.jsondeleted file mode 100644index a1a89f592b58..000000000000--- a/rust/cyclotron-core/.sqlx/query-ed88c403ecb0629c9687fccb09b7e3bc4ecc70af3efd58bf6561e1971ce5aa27.json+++ /dev/null@@ -1,44 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nWITH to_delete AS (\n DELETE FROM cyclotron_jobs\n WHERE state IN ('failed', 'completed', 'canceled')\n RETURNING last_transition, team_id, function_id::text, state::text\n),\naggregated_data AS (\n SELECT\n date_trunc('hour', last_transition) AS hour,\n team_id,\n function_id,\n state,\n COUNT(*) AS count\n FROM to_delete\n GROUP BY hour, team_id, function_id, state\n)\nSELECT\n hour as \"hour!\",\n team_id as \"team_id!\",\n function_id,\n state as \"state!\",\n count as \"count!\"\nFROM aggregated_data",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "hour!",- "type_info": "Timestamptz"- },- {- "ordinal": 1,- "name": "team_id!",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "function_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "state!",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "count!",- "type_info": "Int8"- }- ],- "parameters": {- "Left": []- },- "nullable": [- null,- false,- null,- null,- null- ]- },- "hash": "ed88c403ecb0629c9687fccb09b7e3bc4ecc70af3efd58bf6561e1971ce5aa27"-}diff --git a/rust/cyclotron-core/.sqlx/query-f074766d1fc32df17f92667f412af30c682288988fc6f102e8a063be97c3e51c.json b/rust/cyclotron-core/.sqlx/query-f074766d1fc32df17f92667f412af30c682288988fc6f102e8a063be97c3e51c.jsondeleted file mode 100644index 957440a594c8..000000000000--- a/rust/cyclotron-core/.sqlx/query-f074766d1fc32df17f92667f412af30c682288988fc6f102e8a063be97c3e51c.json+++ /dev/null@@ -1,38 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nINSERT INTO cyclotron_jobs\n (\n id,\n team_id,\n function_id,\n created,\n lock_id,\n last_heartbeat,\n janitor_touch_count,\n transition_count,\n last_transition,\n queue_name,\n state,\n scheduled,\n priority,\n vm_state,\n metadata,\n parameters,\n blob\n )\nVALUES\n ($1, $2, $3, NOW(), NULL, NULL, 0, 0, NOW(), $4, $5, $6, $7, $8, $9, $10, $11)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Int4",- "Uuid",- "Text",- {- "Custom": {- "name": "jobstate",- "kind": {- "Enum": [- "available",- "completed",- "failed",- "running",- "paused",- "canceled"- ]- }- }- },- "Timestamptz",- "Int2",- "Bytea",- "Bytea",- "Bytea",- "Bytea"- ]- },- "nullable": []- },- "hash": "f074766d1fc32df17f92667f412af30c682288988fc6f102e8a063be97c3e51c"-}diff --git a/rust/cyclotron-core/Cargo.toml b/rust/cyclotron-core/Cargo.tomldeleted file mode 100644index 5b3d3ff7c4b3..000000000000--- a/rust/cyclotron-core/Cargo.toml+++ /dev/null@@ -1,23 +0,0 @@-[package]-name = "cyclotron-core"-version = "0.1.0"-edition = "2021"-rust-version = "1.91.1" # please keep in sync with the version in .github/workflows/rust.yml-publish = false--[lints]-workspace = true--[dependencies]-serde = { workspace = true }-sqlx = { workspace = true }-chrono = { workspace = true }-tokio = { workspace = true }-thiserror = { workspace = true }-uuid = { workspace = true }-futures = { workspace = true }-tracing = { workspace = true }-common-compression = { path = "../common/compression" }-common-metrics = { path = "../common/metrics" }-csv = "1.3.1"-hex = "0.4.3"diff --git a/rust/cyclotron-core/migrations/20240804122549_initial_job_queue_schema.sql b/rust/cyclotron-core/migrations/20240804122549_initial_job_queue_schema.sqldeleted file mode 100644index a69c44ef90f7..000000000000--- a/rust/cyclotron-core/migrations/20240804122549_initial_job_queue_schema.sql+++ /dev/null@@ -1,113 +0,0 @@-CREATE TYPE JobState AS ENUM(- 'available',- 'completed',- 'failed',- 'running',- 'paused'-);--------------------------------------------------------------------------- Job table------------------------------------------------------------------------- When a job is dequeued, it is locked by generating a UUID and returning it to the dequeuing--- worker. Any worker that can't provide the correct lock_id when updating will have their updates--- rejected. The reason this is important is because if, e.g., a worker holds a job in a running--- state without updating the heartbeat, the janitor will return the job to the queue eventually,--- and if the worker /then/ tries to update the job after another worker has picked it up, that's a--- race. We track transition count and times alongside lock_id's and heartbeats for reporting and--- debugging purposes, and we track the number of times the janitor has touched a job to spot poison--- pills.-CREATE TABLE IF NOT EXISTS cyclotron_jobs (- ---------------------------------------------------------------------- -- Job metadata- ---------------------------------------------------------------------- id UUID PRIMARY KEY,- team_id INT NOT NULL,- function_id UUID,- created TIMESTAMPTZ NOT NULL,- ---------------------------------------------------------------------- -- Queue bookkeeping - invisible to the worker- ---------------------------------------------------------------------- lock_id UUID,- -- This is set when a job is in a running state, and is required to update the job.- last_heartbeat TIMESTAMPTZ,- -- This is updated by the worker to indicate that the job is making forward progress even- -- without transitions (and should not be reaped)- janitor_touch_count SMALLINT NOT NULL,- transition_count SMALLINT NOT NULL,- last_transition TIMESTAMPTZ NOT NULL,- ---------------------------------------------------------------------- -- Queue components - determines which workers will consume this job- ---------------------------------------------------------------------- queue_name TEXT NOT NULL,- ---------------------------------------------------------------------- -- Job availability and priority (can this job be dequeued, and in what order?)- ---------------------------------------------------------------------- state JobState NOT NULL,- scheduled TIMESTAMPTZ NOT NULL,- priority SMALLINT NOT NULL,- ---------------------------------------------------------------------- -- Job data- ---------------------------------------------------------------------- vm_state TEXT,- -- This is meant for workers "talking to themselves", e.g. tracking retries or something- metadata TEXT,- -- This is meant for "the next guy" - hog might fill it with a URL to fetch, for example- parameters TEXT-);---- For a given worker, the set of "available" jobs depends on state, queue_name, and scheduled (so--- we can exclude sleeping jobs). This index is partial, because we don't care about other states--- for the purpose of dequeuing-CREATE INDEX idx_cyclotron_jobs_dequeue ON cyclotron_jobs (queue_name, state, scheduled, priority)-WHERE- state = 'available';---- We create simple indexes on team_id, function_id and queue_name to support fast joins to future--- control tables-CREATE INDEX idx_queue_team_id ON cyclotron_jobs(team_id);--CREATE INDEX idx_queue_function_id ON cyclotron_jobs(function_id);--CREATE INDEX idx_queue_queue_name ON cyclotron_jobs(queue_name);--------------------------------------------------------------------------- Control tables--------------------------------------------------------------------------- The dead letter metadata table - when a job is DLQ'd, whovever does it leaves a note here for us.-CREATE TABLE IF NOT EXISTS cyclotron_dead_letter_metadata (- job_id UUID PRIMARY KEY,- -- The queue the job was on before it was DLQ'd (important if e.g. we want to re-schedule it after fixing a bug)- original_queue_name TEXT NOT NULL,- -- This is the reason the job was DLQ'd. This should be for humans, but can include structured data if needed (keep in mind the original job will still exist)- reason TEXT NOT NULL,- -- This is the time the job was DLQ'd- dlq_time TIMESTAMPTZ NOT NULL-);---- These are just a starting point, supporting overriding the state for a given team, function or queue--- For now these are entirely unused-CREATE TABLE IF NOT EXISTS cyclotron_team_control (- team_id INT PRIMARY KEY,- state_override JobState,- -- If this is not null, it overrides the state of all jobs for this team (allowing for e.g. pausing or force failing all of a teams jobs)- state_override_expires TIMESTAMPTZ -- State override can be temporary or permanent-);--CREATE TABLE IF NOT EXISTS cyclotron_function_control (- function_id UUID PRIMARY KEY,- state_override JobState,- -- If this is not null, it overrides the state of all jobs for this function (allowing for e.g. pausing or force failing all of a functions jobs)- state_override_expires TIMESTAMPTZ -- State override can be temporary or permanent-);--CREATE TABLE IF NOT EXISTS cyclotron_queue_control (- queue_name TEXT PRIMARY KEY,- state_override JobState,- -- If this is not null, it overrides the state of all jobs for this queue (allowing for e.g. pausing or force failing all of a queues jobs)- state_override_expires TIMESTAMPTZ -- State override can be temporary or permanent-);\ No newline at end of filediff --git a/rust/cyclotron-core/migrations/20240823191751_bytes_over_text.sql b/rust/cyclotron-core/migrations/20240823191751_bytes_over_text.sqldeleted file mode 100644index cbe476e3c30e..000000000000--- a/rust/cyclotron-core/migrations/20240823191751_bytes_over_text.sql+++ /dev/null@@ -1,5 +0,0 @@-ALTER TABLE cyclotron_jobs- ALTER COLUMN vm_state TYPE bytea USING vm_state::bytea,- ALTER COLUMN metadata TYPE bytea USING metadata::bytea,- ALTER COLUMN parameters TYPE bytea USING parameters::bytea,- ADD COLUMN blob bytea;diff --git a/rust/cyclotron-core/migrations/20250205162334_fix_dequeue_index.sql b/rust/cyclotron-core/migrations/20250205162334_fix_dequeue_index.sqldeleted file mode 100644index fa5fe1467216..000000000000--- a/rust/cyclotron-core/migrations/20250205162334_fix_dequeue_index.sql+++ /dev/null@@ -1,5 +0,0 @@--- Worker dequeue query uses priority, and then scheduled, as the ordering args. Original index was the wrong way around--CREATE INDEX idx_cyclotron_jobs_dequeue_correct_order ON cyclotron_jobs (queue_name, state, priority, scheduled)-WHERE- state = 'available';diff --git a/rust/cyclotron-core/migrations/20260115221204_add_parent_run_id_column.sql b/rust/cyclotron-core/migrations/20260115221204_add_parent_run_id_column.sqldeleted file mode 100644index 0bb56fa3aaa6..000000000000--- a/rust/cyclotron-core/migrations/20260115221204_add_parent_run_id_column.sql+++ /dev/null@@ -1 +0,0 @@-ALTER TABLE cyclotron_jobs ADD COLUMN parent_run_id TEXT;diff --git a/rust/cyclotron-core/migrations/20260121092625_add_canceled_job_state.sql b/rust/cyclotron-core/migrations/20260121092625_add_canceled_job_state.sqldeleted file mode 100644index d43dccaee347..000000000000--- a/rust/cyclotron-core/migrations/20260121092625_add_canceled_job_state.sql+++ /dev/null@@ -1,3 +0,0 @@--- Add 'canceled' value to JobState enum for jobs that are intentionally skipped--- (e.g., workflow invocations for disabled/archived workflows)-ALTER TYPE JobState ADD VALUE IF NOT EXISTS 'canceled';diff --git a/rust/cyclotron-core/src/config.rs b/rust/cyclotron-core/src/config.rsdeleted file mode 100644index b4b60a89b1f1..000000000000--- a/rust/cyclotron-core/src/config.rs+++ /dev/null@@ -1,91 +0,0 @@-use std::time::Duration;--use serde::{Deserialize, Serialize};-use sqlx::{pool::PoolOptions, PgPool};--// A pool config object, designed to be passable across API boundaries-#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct PoolConfig {- pub db_url: String,- pub max_connections: Option<u32>, // Default to 10- pub min_connections: Option<u32>, // Default to 1- pub acquire_timeout_seconds: Option<u64>, // Default to 30- pub max_lifetime_seconds: Option<u64>, // Default to 300- pub idle_timeout_seconds: Option<u64>, // Default to 60-}--impl PoolConfig {- pub async fn connect(&self) -> Result<PgPool, sqlx::Error> {- let builder = PoolOptions::new()- .max_connections(self.max_connections.unwrap_or(10))- .min_connections(self.min_connections.unwrap_or(1))- .max_lifetime(Duration::from_secs(- self.max_lifetime_seconds.unwrap_or(300),- ))- .idle_timeout(Duration::from_secs(self.idle_timeout_seconds.unwrap_or(60)))- .acquire_timeout(Duration::from_secs(- self.acquire_timeout_seconds.unwrap_or(30),- ));-- builder.connect(&self.db_url).await- }-}--pub const DEFAULT_QUEUE_DEPTH_LIMIT: u64 = 1_000_000;-pub const DEFAULT_SHARD_HEALTH_CHECK_INTERVAL: u64 = 10;--#[derive(Debug, Serialize, Deserialize, Default)]-pub struct ManagerConfig {- #[serde(alias = "shards")]- pub shards: Vec<PoolConfig>,- #[serde(alias = "shardDepthLimit")]- pub shard_depth_limit: Option<u64>, // Defaults to 10_000 available jobs per shard- #[serde(alias = "shardDepthCheckIntervalSeconds")]- pub shard_depth_check_interval_seconds: Option<u64>, // Defaults to 10 seconds - checking shard capacity- #[serde(alias = "shouldCompressVmState")]- pub should_compress_vm_state: Option<bool>, // Defaults to "false" for now- #[serde(alias = "shouldUseBulkJobCopy")]- pub should_use_bulk_job_copy: Option<bool>, // Defaults to "false" for now-}--#[derive(Debug, Serialize, Deserialize, Default)]-pub struct WorkerConfig {- #[serde(alias = "heartbeatWindowSeconds")]- pub heartbeat_window_seconds: Option<u64>, // Defaults to 5- #[serde(alias = "lingerTimeMs")]- pub linger_time_ms: Option<u64>, // Defaults to 500- #[serde(alias = "maxUpdatesBuffered")]- pub max_updates_buffered: Option<usize>, // Defaults to 100- #[serde(alias = "maxBytesBuffered")]- pub max_bytes_buffered: Option<usize>, // Defaults to 10MB- #[serde(alias = "flushLoopIntervalMs")]- pub flush_loop_interval_ms: Option<u64>, // Defaults to 10- #[serde(alias = "shouldCompressVmState")]- pub should_compress_vm_state: Option<bool>, // Defaults to "false"-}--impl WorkerConfig {- pub fn heartbeat_window(&self) -> chrono::Duration {- chrono::Duration::seconds(self.heartbeat_window_seconds.unwrap_or(5) as i64)- }-- pub fn linger_time(&self) -> chrono::Duration {- chrono::Duration::milliseconds(self.linger_time_ms.unwrap_or(500) as i64)- }-- pub fn flush_loop_interval(&self) -> chrono::Duration {- chrono::Duration::milliseconds(self.flush_loop_interval_ms.unwrap_or(10) as i64)- }-- pub fn max_updates_buffered(&self) -> usize {- self.max_updates_buffered.unwrap_or(100)- }-- pub fn max_bytes_buffered(&self) -> usize {- self.max_bytes_buffered.unwrap_or(10_000_000)- }-- pub fn should_compress_vm_state(&self) -> bool {- self.should_compress_vm_state.unwrap_or(false)- }-}diff --git a/rust/cyclotron-core/src/error.rs b/rust/cyclotron-core/src/error.rsdeleted file mode 100644index bd0554ae03e8..000000000000--- a/rust/cyclotron-core/src/error.rs+++ /dev/null@@ -1,33 +0,0 @@-use uuid::Uuid;--#[derive(Debug, thiserror::Error)]-pub enum QueueError {- #[error("sqlx error: {0}")]- SqlxError(#[from] sqlx::Error),- #[error("Shard over capacity {0} for this manager, insert aborted")]- ShardFull(u64),- #[error("Timed waiting for shard to have capacity")]- TimedOutWaitingForCapacity,- #[error(transparent)]- JobError(#[from] JobError),- #[error("vm_state compression error: {0}")]- CompressionError(String),- #[error("writing in-mem CSV buffer at {0}: {1}")]- CsvError(&'static str, csv::Error),-}--#[derive(Debug, thiserror::Error)]-pub enum JobError {- #[error("Unknown job id: {0}")]- UnknownJobId(Uuid),- #[error("Invalid lock id: {0} for job {1}")]- InvalidLock(Uuid, Uuid),- #[error("Cannot flush job {0} without a next state")]- FlushWithoutNextState(Uuid),- #[error("Deadline to flush update for job {0} exceeded")]- DeadlineExceeded(Uuid),- #[error("Update dropped before being flushed.")]- UpdateDropped,- #[error("vm_state compression error: {0}")]- CompressionError(String),-}diff --git a/rust/cyclotron-core/src/janitor.rs b/rust/cyclotron-core/src/janitor.rsdeleted file mode 100644index 06a1dac40485..000000000000--- a/rust/cyclotron-core/src/janitor.rs+++ /dev/null@@ -1,73 +0,0 @@-use crate::DEAD_LETTER_QUEUE;-use chrono::Duration;-use sqlx::PgPool;--use crate::{- ops::{- janitor::{delete_completed_and_failed_jobs, detect_poison_pills, reset_stalled_jobs},- meta::{count_total_waiting_jobs, dead_letter},- },- types::AggregatedDelete,- PoolConfig, QueueError,-};--// Thin layer on top of the raw janitor operations - mostly just avoids users having to take a dep on sqlx-pub struct Janitor {- pub pool: PgPool,-}--impl Janitor {- pub async fn new(config: PoolConfig) -> Result<Self, QueueError> {- let pool = config.connect().await?;- Ok(Self { pool })- }-- pub fn from_pool(pool: PgPool) -> Self {- Self { pool }- }-- pub async fn delete_completed_and_failed_jobs(- &self,- ) -> Result<Vec<AggregatedDelete>, QueueError> {- delete_completed_and_failed_jobs(&self.pool).await- }-- pub async fn reset_stalled_jobs(&self, timeout: Duration) -> Result<u64, QueueError> {- reset_stalled_jobs(&self.pool, timeout).await- }-- pub async fn delete_poison_pills(- &self,- timeout: Duration,- max_janitor_touched: i16,- ) -> Result<u64, QueueError> {- let poison = detect_poison_pills(&self.pool, timeout, max_janitor_touched).await?;-- for job in &poison {- dead_letter(- &self.pool,- *job,- &format!("poison pill detected based on a timeout of {timeout}"),- )- .await?;- }-- Ok(poison.len() as u64)- }-- pub async fn waiting_jobs(&self) -> Result<Vec<(u64, String)>, QueueError> {- count_total_waiting_jobs(&self.pool).await- }-- pub async fn count_dlq_depth(&self) -> Result<u64, QueueError> {- let result = sqlx::query_scalar!(- "SELECT COUNT(*) FROM cyclotron_jobs WHERE queue_name = $1",- DEAD_LETTER_QUEUE- )- .fetch_one(&self.pool)- .await- .map_err(QueueError::from)?;-- Ok(result.unwrap_or(0) as u64)- }-}diff --git a/rust/cyclotron-core/src/lib.rs b/rust/cyclotron-core/src/lib.rsdeleted file mode 100644index cc11a47a4502..000000000000--- a/rust/cyclotron-core/src/lib.rs+++ /dev/null@@ -1,53 +0,0 @@-mod ops;--// We do this pattern (privately use a module, then re-export parts of it) so we can refactor/rename or generally futz around with the internals without breaking the public API--// Types-mod types;-pub use types::AggregatedDelete;-pub use types::Bytes;-pub use types::Job;-pub use types::JobInit;-pub use types::JobState;-pub use types::JobUpdate;--// Errors-mod error;-// Errors about some job operation - locks being lost, invalid states, flush deadlines exceeded etc-pub use error::JobError;-// Errors about the queue itself - full shards, timeouts, postgres/network errors-pub use error::QueueError;--// Manager-mod manager;-pub use manager::QueueManager;--// Worker-mod worker;-// A handle to a released job update, that can be awaited to block waiting for the flush to complete-pub use worker::FlushHandle;-pub use worker::Worker;--// Janitor-mod janitor;-pub use janitor::Janitor;--// Config-mod config;-pub use config::ManagerConfig;-pub use config::PoolConfig;-pub use config::WorkerConfig;--// The shard id is a fixed value that is set by the janitor when it starts up.-// Workers may use this value when reporting metrics. The `Worker` struct provides-// a method for fetching this value, that caches it appropriately such that it's safe-// to call frequently, while still being up-to-date (even though it should "never" change)-pub const SHARD_ID_KEY: &str = "shard_id";--// This isn't pub because, ideally, nothing using the core will ever need to know it.-const DEAD_LETTER_QUEUE: &str = "_cyclotron_dead_letter";--#[doc(hidden)]-pub mod test_support {- pub use crate::manager::Shard;-}diff --git a/rust/cyclotron-core/src/manager.rs b/rust/cyclotron-core/src/manager.rsdeleted file mode 100644index 01487fde75ae..000000000000--- a/rust/cyclotron-core/src/manager.rs+++ /dev/null@@ -1,238 +0,0 @@-use std::sync::atomic::AtomicUsize;--use chrono::{DateTime, Duration, Utc};-use sqlx::PgPool;-use tokio::sync::RwLock;-use uuid::Uuid;--use crate::{- config::{DEFAULT_QUEUE_DEPTH_LIMIT, DEFAULT_SHARD_HEALTH_CHECK_INTERVAL},- ops::{- manager::{bulk_create_jobs_copy, bulk_create_jobs_upsert, create_job},- meta::count_total_waiting_jobs,- },- JobInit, ManagerConfig, QueueError,-};--pub struct Shard {- pub pool: PgPool,- pub last_healthy: RwLock<DateTime<Utc>>,- pub check_interval: Duration,- pub depth_limit: u64,- pub should_compress_vm_state: bool,- pub should_use_bulk_job_copy: bool,-}--pub struct QueueManager {- shards: RwLock<Vec<Shard>>,- next_shard: AtomicUsize,-}--impl QueueManager {- pub async fn new(config: ManagerConfig) -> Result<Self, QueueError> {- let mut shards = vec![];- let depth_limit = config- .shard_depth_limit- .unwrap_or(DEFAULT_QUEUE_DEPTH_LIMIT);- let check_interval = Duration::seconds(- config- .shard_depth_check_interval_seconds- .unwrap_or(DEFAULT_SHARD_HEALTH_CHECK_INTERVAL) as i64,- );- let should_compress_vm_state = config.should_compress_vm_state.unwrap_or(false);- let should_use_bulk_job_copy = config.should_use_bulk_job_copy.unwrap_or(false);-- for shard in config.shards {- let pool = shard.connect().await.unwrap();- let shard = Shard::new(- pool,- depth_limit,- check_interval,- should_compress_vm_state,- should_use_bulk_job_copy,- );- shards.push(shard);- }- Ok(Self {- shards: RwLock::new(shards),- next_shard: AtomicUsize::new(0),- })- }-- #[doc(hidden)] // Mostly for testing, but safe to expose- pub fn from_pool(- pool: PgPool,- should_compress_vm_state: bool,- should_use_bulk_job_copy: bool,- ) -> Self {- Self {- shards: RwLock::new(vec![Shard::new(- pool,- DEFAULT_QUEUE_DEPTH_LIMIT,- Duration::seconds(DEFAULT_SHARD_HEALTH_CHECK_INTERVAL as i64),- should_compress_vm_state,- should_use_bulk_job_copy,- )]),- next_shard: AtomicUsize::new(0),- }- }-- pub async fn create_job(&self, init: JobInit) -> Result<Uuid, QueueError> {- // TODO - here is where a lot of shard health and failover logic will go, eventually.- let next = self- .next_shard- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let shards = self.shards.read().await;- let shard = &shards[next % shards.len()];- shard.create_job(init).await- }-- pub async fn create_job_blocking(- &self,- init: JobInit,- timeout: Option<Duration>,- ) -> Result<Uuid, QueueError> {- let next = self- .next_shard- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let shards = self.shards.read().await;- let shard = &shards[next % shards.len()];- shard.create_job_blocking(init, timeout).await- }-- pub async fn bulk_create_jobs(&self, inits: Vec<JobInit>) -> Result<Vec<Uuid>, QueueError> {- let next = self- .next_shard- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let shards = self.shards.read().await;- shards[next % shards.len()].bulk_create_jobs(inits).await- }-- pub async fn bulk_create_jobs_blocking(- &self,- inits: Vec<JobInit>,- timeout: Option<Duration>,- ) -> Result<Vec<Uuid>, QueueError> {- let next = self- .next_shard- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let shards = self.shards.read().await;- shards[next % shards.len()]- .bulk_create_jobs_blocking(inits, timeout)- .await- }-}--impl Shard {- pub fn new(- pool: PgPool,- depth_limit: u64,- check_interval: Duration,- should_compress_vm_state: bool,- should_use_bulk_job_copy: bool,- ) -> Self {- Self {- pool,- last_healthy: RwLock::new(Utc::now() - check_interval),- check_interval,- depth_limit,- should_compress_vm_state,- should_use_bulk_job_copy,- }- }-- // Inserts a job, failing if the shard is at capacity- pub async fn create_job(&self, init: JobInit) -> Result<Uuid, QueueError> {- self.insert_guard().await?;- create_job(&self.pool, init, self.should_compress_vm_state).await- }-- // Inserts a vec of jobs, failing if the shard is at capacity. Note "capacity" here just- // means "it isn't totally full" - if there's "capacity" for 1 job, and this is a vec of- // 1000, we still insert all 1000.- pub async fn bulk_create_jobs(&self, inits: Vec<JobInit>) -> Result<Vec<Uuid>, QueueError> {- self.insert_guard().await?;- if self.should_use_bulk_job_copy {- bulk_create_jobs_copy(&self.pool, inits, self.should_compress_vm_state).await- } else {- bulk_create_jobs_upsert(&self.pool, inits, self.should_compress_vm_state).await- }- }-- // Inserts a job, blocking until there's capacity (or until the timeout is reached)- pub async fn create_job_blocking(- &self,- init: JobInit,- timeout: Option<Duration>,- ) -> Result<Uuid, QueueError> {- let start = Utc::now();- while self.is_full().await? {- tokio::time::sleep(Duration::milliseconds(100).to_std().unwrap()).await;- if let Some(timeout) = &timeout {- if Utc::now() - start > *timeout {- return Err(QueueError::TimedOutWaitingForCapacity);- }- }- }-- create_job(&self.pool, init, self.should_compress_vm_state).await- }-- // As above, with the same caveats about what "capacity" means- pub async fn bulk_create_jobs_blocking(- &self,- inits: Vec<JobInit>,- timeout: Option<Duration>,- ) -> Result<Vec<Uuid>, QueueError> {- let start = Utc::now();- while self.is_full().await? {- tokio::time::sleep(Duration::milliseconds(100).to_std().unwrap()).await;- if let Some(timeout) = &timeout {- if Utc::now() - start > *timeout {- return Err(QueueError::TimedOutWaitingForCapacity);- }- }- }-- if self.should_use_bulk_job_copy {- bulk_create_jobs_copy(&self.pool, inits, self.should_compress_vm_state).await- } else {- bulk_create_jobs_upsert(&self.pool, inits, self.should_compress_vm_state).await- }- }-- pub async fn insert_guard(&self) -> Result<(), QueueError> {- if self.is_full().await? {- return Err(QueueError::ShardFull(self.depth_limit));- }-- Ok(())- }-- pub async fn is_full(&self) -> Result<bool, QueueError> {- let last_healthy = self.last_healthy.read().await;- // If we were healthy less than the check interval ago, assume we are still- if Utc::now() - *last_healthy < self.check_interval {- return Ok(false);- }-- // Grab a write lock. This constrains the number of concurrent capacity checks- // to 1, purposefully - if someone spawns a thousand tasks to blockingly create- // a job, we don't want all of them to be querying the available count at once.- drop(last_healthy);- let mut last_healthy = self.last_healthy.write().await;- // TOCTOU - multiple tasks could be racing to re-do the check, and the firs time one- // succeeds all the rest should skip it.- if Utc::now() - *last_healthy < self.check_interval {- return Ok(false);- }-- let pending = count_total_waiting_jobs(&self.pool).await?;- let total_pending = pending.iter().map(|(count, _)| count).sum::<u64>();- let is_full = total_pending >= self.depth_limit;- if !is_full {- *last_healthy = Utc::now();- }- Ok(is_full)- }-}diff --git a/rust/cyclotron-core/src/ops/compress.rs b/rust/cyclotron-core/src/ops/compress.rsdeleted file mode 100644index 15e8f09ffb1a..000000000000--- a/rust/cyclotron-core/src/ops/compress.rs+++ /dev/null@@ -1,150 +0,0 @@-use common_compression::{compress_data, CompressionFormat};--use crate::{error::QueueError, types::Bytes};-use common_metrics::inc;--const DECOMPRESS_METRICS_KEY: &str = "decompress_vm_state";-const COMPRESS_METRICS_KEY: &str = "compress_vm_state";--// this doesn't return an error as we expect errors during the transition-// to compressed vm_state. Returns input buffer and assumes not compressed on fail-pub fn decompress_vm_state(maybe_compressed: Option<Bytes>) -> Option<Bytes> {- match &maybe_compressed {- Some(in_buffer) => {- // Use common compression library with multi-format support- match common_compression::decompress_data(in_buffer) {- Ok(decompressed_str) => {- inc(- DECOMPRESS_METRICS_KEY,- &[("result".to_string(), "success".to_string())],- 1,- );- Some(decompressed_str.into_bytes())- }- Err(_) => {- inc(- DECOMPRESS_METRICS_KEY,- &[("result".to_string(), "fail_or_no_op".to_string())],- 1,- );- maybe_compressed- }- }- }- _ => {- inc(- DECOMPRESS_METRICS_KEY,- &[("result".to_string(), "empty_buffer".to_string())],- 1,- );- maybe_compressed- }- }-}--// returns an error as on the encode side, this would represent corrupted data-pub fn compress_vm_state(uncompressed: Option<Bytes>) -> Result<Option<Bytes>, QueueError> {- if let Some(in_buffer) = &uncompressed {- if in_buffer.is_empty() {- inc(- COMPRESS_METRICS_KEY,- &[("result".to_string(), "empty_buffer".to_string())],- 1,- );- return Ok(uncompressed);- }-- // Use common compression library with gzip (maintaining backward compatibility)- match compress_data(in_buffer, CompressionFormat::Gzip) {- Ok(compressed) => {- inc(- COMPRESS_METRICS_KEY,- &[("result".to_string(), "success".to_string())],- 1,- );- Ok(Some(compressed))- }- Err(e) => {- inc(- COMPRESS_METRICS_KEY,- &[("result".to_string(), "failed".to_string())],- 1,- );- Err(QueueError::CompressionError(e.to_string()))- }- }- } else {- Ok(uncompressed)- }-}--#[cfg(test)]-pub mod test {- use super::{compress_vm_state, decompress_vm_state};- use crate::types::Bytes;-- #[test]- fn test_compress_decompress_json() {- let payload = Some(Vec::from(br#"{"foo": "bar", "hog": "function"}"#));- perform_compression_decompression_test(payload);- }-- #[test]- fn test_compress_decompress_vm_state() {- let payload = Some(Vec::from(VM_STATE_PAYLOAD));- perform_compression_decompression_test(payload);- }-- #[test]- fn test_compress_decompress_empty_buffer_no_ops() {- let payload = Some(Vec::new());- perform_compression_decompression_test(payload);- }-- #[test]- fn test_compress_decompress_none_no_ops() {- let compressed = compress_vm_state(None);- assert!(compressed.is_ok());-- let result = decompress_vm_state(None);- assert!(result.is_none());- }-- #[test]- fn test_corrupt_compressed_payload_decompresses_as_no_op() {- let payload = Some(Vec::from(br#"{"foo": 1, "bar": false}"#));- let compressed = compress_vm_state(payload.clone());- assert!(compressed.is_ok());-- // corrupt the payload and attempt to decompress it- let mut buf = compressed.unwrap().unwrap();- buf[0] = 0;- buf[1] = 0;-- // decompression should fail silently, returning the input buffer- let result = decompress_vm_state(Some(buf.clone()));- assert!(result.is_some());- assert_eq!(result.unwrap(), buf);- }-- #[test]- fn test_decompressing_uncompressed_buffer_no_ops() {- let payload = Some(Vec::from(br#"{"foo": 1, "bar": false}"#));-- // decompression should fail silently, returning the input buffer- let result = decompress_vm_state(payload.clone());- assert!(result.is_some());- assert!(result == payload);- }-- fn perform_compression_decompression_test(payload: Option<Bytes>) {- let compressed = compress_vm_state(payload.clone());- assert!(compressed.is_ok());-- let result = decompress_vm_state(compressed.unwrap());- assert!(result.is_some());- assert_eq!(result.unwrap(), payload.unwrap());- }-- const VM_STATE_PAYLOAD: &[u8; 6194]= br#"{"id":"00000000-0000-0000-0000-000000000000","globals":{"project":{"id":44444,"name":"test fixture","url":"https://us.posthog.com/project/44444"},"event":{"uuid":"00000000-0000-0000-0000-000000000000","event":"$autocapture","elements_chain":"span:text=\"Awesome Site\"nth-child=\"2\"nth-of-type=\"1\"href=\"/as\"attr__style=\"display: flex; align-items: center; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1 1 0%;\"attr__href=\"/as\";button.rt-BaseButton.rt-Button.rt-high-contrast.rt-r-size-2.rt-reset.rt-variant-ghost:text=\"Awesome Site\"nth-child=\"1\"nth-of-type=\"1\"attr__data-accent-color=\"gray\"attr__class=\"rt-reset rt-BaseButton rt-r-size-2 rt-variant-ghost rt-high-contrast rt-Button\"attr__style=\"width: 100%; justify-content: flex-start; gap: var(--space-2);\";a:nth-child=\"3\"nth-of-type=\"3\"href=\"as\"attr__data-discover=\"true\"attr__href=\"as\";div.rt-Flex.rt-r-fd-column.rt-r-fg-0.rt-r-gap-2.rt-r-h.rt-r-overflow-hidden.rt-r-p-2.rt-r-w:nth-child=\"2\"nth-of-type=\"1\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-2 rt-r-p-2 rt-r-w rt-r-h rt-r-overflow-hidden rt-r-fg-0\"attr__style=\"--width: 100%; --height: 100%;\";div.rt-Flex.rt-r-fd-column.rt-r-gap-0.rt-r-w:nth-child=\"3\"nth-of-type=\"3\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-0 rt-r-w\"attr__style=\"--width: 100%;\";div.rt-Flex.rt-r-fd-column.rt-r-gap-4:nth-child=\"2\"nth-of-type=\"2\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-4\";div.rt-Flex.rt-r-fd-column.rt-r-gap-2.rt-r-p-3.rt-r-w:nth-child=\"1\"nth-of-type=\"1\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-2 rt-r-p-3 rt-r-w\"attr__style=\"--width: 190px; border-right: 1px solid var(--gray-a6);\";div:nth-child=\"1\"nth-of-type=\"1\"attr__style=\"position: fixed; z-index: 5; background-color: var(--color-background); height: 100vh; left: 0%;\";div.md:rt-r-display-none.rt-Box.rt-r-display-block:nth-child=\"1\"nth-of-type=\"1\"attr__class=\"rt-Box rt-r-display-block md:rt-r-display-none\";div.rt-Flex.rt-r-gap-0:nth-child=\"2\"nth-of-type=\"1\"attr__class=\"rt-Flex rt-r-gap-0\";div.radix-themes:nth-child=\"8\"nth-of-type=\"1\"attr__data-is-root-theme=\"true\"attr__data-accent-color=\"green\"attr__data-gray-color=\"sage\"attr__data-has-background=\"true\"attr__data-panel-background=\"translucent\"attr__data-radius=\"medium\"attr__data-scaling=\"100%\"attr__style=\"width:100%\"attr__class=\"radix-themes\";body:nth-child=\"2\"nth-of-type=\"1\"attr__style=\"transition: margin 250ms; margin-top: 0px;\"","distinct_id":"00000000-0000-0000-0000-000000000000","properties":{"$process_person_profile":false,"$session_recording_canvas_recording":{},"$os":"iOS","$sdk_debug_retry_queue_size":0,"$replay_sample_rate":null,"$session_entry_pathname":"/","$pageview_id":"00000000-0000-0000-0000-000000000000","$viewport_width":402,"$device_type":"Mobile","distinct_id":"00000000-0000-0000-0000-000000000000","$el_text":"Awesome Site","$session_recording_masking":null,"$session_id":"00000000-0000-0000-0000-000000000000","$pathname":"/","$is_identified":false,"$browser_version":18.3,"$web_vitals_enabled_server_side":true,"$event_type":"click","$initial_person_info":{"r":"$direct","u":"https://some.example.com/?posts%5Bquery%5D=&posts%5Bpage%5D=1"},"$web_vitals_allowed_metrics":null,"$lib_version":"1.230.4","$timezone":"America/New_York","$current_url":"https://some.example.com","$window_id":"00000000-0000-0000-0000-000000000000","$browser_language_prefix":"en","$session_entry_referrer":"$direct","$recording_status":"active","$screen_height":896,"$replay_script_config":null,"$session_recording_network_payload_capture":{"capturePerformance":{"network_timing":true,"web_vitals":true,"web_vitals_allowed_metrics":null}},"$session_entry_referring_domain":"$direct","$lib":"web","$os_version":"18.3.1","$active_feature_flags":[],"$browser":"Mobile Safari","$feature_flag_payloads":{},"token":"redacted","$replay_minimum_duration":null,"$time":1741912549.921,"$sdk_debug_replay_internal_buffer_size":9446,"$dead_clicks_enabled_server_side":false,"$exception_capture_enabled_server_side":false,"$referring_domain":"$direct","$raw_user_agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 18_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Mobile/15E148 Safari/604.1","$browser_language":"en-US","$viewport_height":673,"$host":"some.example.com","$feature_flag_request_id":"00000000-0000-0000-0000-000000000000","$session_entry_url":"https://some.example.com/?posts%5Bquery%5D=&posts%5Bpage%5D=1","$device":"iPhone","$console_log_recording_enabled_server_side":true,"$session_recording_start_reason":"recording_initialized","$insert_id":"redacted","$screen_width":414,"$device_id":"00000000-0000-0000-0000-000000000000","$referrer":"$direct","$configured_session_timeout_ms":1800000,"$session_entry_host":"some.example.com","$sdk_debug_replay_internal_buffer_length":9,"$ce_version":1,"$autocapture_disabled_server_side":false,"$lib_rate_limit_remaining_tokens":99,"$ip":"10.0.0.1","$sent_at":"2025-03-14T00:35:52.922Z","$geoip_city_name":"Springfield","$geoip_country_name":"United States","$geoip_country_code":"US","$geoip_continent_name":"North America","$geoip_continent_code":"NA","$geoip_postal_code":"00000","$geoip_latitude":28.1234,"$geoip_longitude":-81.1234,"$geoip_accuracy_radius":5,"$geoip_time_zone":"America/New_York","$geoip_subdivision_1_code":"FL","$geoip_subdivision_1_name":"Florida","$transformations_succeeded":["GeoIP (00000000-0000-0000-0000-000000000000)"],"$transformations_failed":[]},"timestamp":"2025-03-14T00:35:49.962Z","url":"https://us.posthog.com/project/44444/events/01959214-2a21-7cb4-9bc2-b347c93bec22/2025-03-14T00%3A35%3A49.962Z"},"person":{"id":"00000000-0000-0000-0000-000000000000","properties":{},"name":"00000000-0000-0000-0000-000000000000","url":"https://us.posthog.com/project/44444/person/00000000-0000-0000-0000-000000000000"},"groups":{},"source":{"name":"Acme, Inc.","url":"https://us.posthog.com/project/44444/pipeline/destinations/hog-00000000-0000-0000-0000-000000000000/configuration/"},"inputs":{"email":null,"api_key":"redacted"}},"teamId":44444,"queue":"hog","priority":1,"timings":[],"hogFunctionId":"00000000-0000-0000-0000-000000000000"}"#;-}diff --git a/rust/cyclotron-core/src/ops/janitor.rs b/rust/cyclotron-core/src/ops/janitor.rsdeleted file mode 100644index eafae02e9198..000000000000--- a/rust/cyclotron-core/src/ops/janitor.rs+++ /dev/null@@ -1,100 +0,0 @@-use chrono::{Duration, Utc};-use uuid::Uuid;--use crate::error::QueueError;-use crate::types::AggregatedDelete;--// As a general rule, janitor operations are not queue specific (as in, they don't account for the-// queue name). We can revisit this later, if we decide we need the ability to do janitor operations-// on a per-queue basis.--pub async fn delete_completed_and_failed_jobs<'c, E>(- executor: E,-) -> Result<Vec<AggregatedDelete>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let result: Vec<AggregatedDelete> = sqlx::query_as!(- AggregatedDelete,- r#"-WITH to_delete AS (- DELETE FROM cyclotron_jobs- WHERE state IN ('failed', 'completed', 'canceled')- RETURNING last_transition, team_id, function_id::text, state::text-),-aggregated_data AS (- SELECT- date_trunc('hour', last_transition) AS hour,- team_id,- function_id,- state,- COUNT(*) AS count- FROM to_delete- GROUP BY hour, team_id, function_id, state-)-SELECT- hour as "hour!",- team_id as "team_id!",- function_id,- state as "state!",- count as "count!"-FROM aggregated_data"#- )- .fetch_all(executor)- .await- .map_err(QueueError::from)?;-- Ok(result)-}--// Jobs are considered stalled if their lock is held and their last_heartbeat is older than `timeout`.-//-// TODO - this /could/ return the lock_id's held, which might help with debugging (if workers reported-// the lock_id's they dequeue'd), but lets not do that right now.-pub async fn reset_stalled_jobs<'c, E>(executor: E, timeout: Duration) -> Result<u64, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let oldest_valid_heartbeat = Utc::now() - timeout;- let result = sqlx::query!(r#"-WITH stalled AS (- SELECT id FROM cyclotron_jobs WHERE state = 'running' AND COALESCE(last_heartbeat, $1) <= $1 FOR UPDATE SKIP LOCKED-)-UPDATE cyclotron_jobs-SET state = 'available', lock_id = NULL, last_heartbeat = NULL, janitor_touch_count = janitor_touch_count + 1-FROM stalled-WHERE cyclotron_jobs.id = stalled.id- "#,- oldest_valid_heartbeat- )- .execute(executor)- .await- .map_err(QueueError::from)?;-- Ok(result.rows_affected())-}--// Poison pills are stalled jobs that have been reset by the janitor more than `max_janitor_touched` times.-pub async fn detect_poison_pills<'c, E>(- executor: E,- timeout: Duration,- max_janitor_touched: i16,-) -> Result<Vec<Uuid>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let oldest_valid_heartbeat = Utc::now() - timeout;- // KLUDGE - the lock_id being set isn't checked here. A job in a running state without a lock id is violating an invariant,- // and would be useful to report.- let result = sqlx::query_scalar!(- r#"-SELECT id FROM cyclotron_jobs WHERE state = 'running' AND COALESCE(last_heartbeat, $1) <= $1 AND janitor_touch_count >= $2- "#,- oldest_valid_heartbeat,- max_janitor_touched- ).fetch_all(executor)- .await- .map_err(QueueError::from)?;-- Ok(result)-}diff --git a/rust/cyclotron-core/src/ops/manager.rs b/rust/cyclotron-core/src/ops/manager.rsdeleted file mode 100644index 9a18079f8852..000000000000--- a/rust/cyclotron-core/src/ops/manager.rs+++ /dev/null@@ -1,307 +0,0 @@-use chrono::{DateTime, Utc};-use sqlx::{postgres::PgPoolCopyExt, Pool, Postgres};-use uuid::Uuid;--use crate::{- error::QueueError,- ops::compress::compress_vm_state,- types::{Bytes, JobInit, JobState},-};-use common_metrics::inc;--const ESTIMATED_RECORD_SIZE: usize = 1024;--const COPY_IN_STMT: &str = r#"COPY cyclotron_jobs- (id, team_id, function_id, created, lock_id, last_heartbeat, janitor_touch_count,- transition_count, last_transition, queue_name, state, scheduled, priority, parent_run_id,- vm_state, metadata, parameters, blob)- FROM STDIN WITH (FORMAT CSV, ENCODING 'UTF8')"#;--pub async fn create_job<'c, E>(- executor: E,- mut data: JobInit,- should_compress_vm_state: bool,-) -> Result<Uuid, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let id = data.id.unwrap_or_else(Uuid::now_v7);-- if should_compress_vm_state {- data.vm_state = compress_vm_state(data.vm_state)?;- }-- sqlx::query!(- r#"-INSERT INTO cyclotron_jobs- (- id,- team_id,- function_id,- created,- lock_id,- last_heartbeat,- janitor_touch_count,- transition_count,- last_transition,- queue_name,- state,- scheduled,- priority,- parent_run_id,- vm_state,- metadata,- parameters,- blob- )-VALUES- ($1, $2, $3, NOW(), NULL, NULL, 0, 0, NOW(), $4, $5, $6, $7, $8, $9, $10, $11, $12)- "#,- id,- data.team_id,- data.function_id,- data.queue_name,- JobState::Available as _,- data.scheduled,- data.priority,- data.parent_run_id,- data.vm_state,- data.metadata,- data.parameters,- data.blob- )- .execute(executor)- .await?;-- Ok(id)-}--pub async fn bulk_create_jobs_upsert<'c, E>(- executor: E,- jobs: Vec<JobInit>,- should_compress_vm_state: bool,-) -> Result<Vec<Uuid>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let now = Utc::now();- // Flatten these jobs into a series of vecs of arguments PG can unnest- let mut ids = Vec::with_capacity(jobs.len());- let mut team_ids = Vec::with_capacity(jobs.len());- let mut function_ids = Vec::with_capacity(jobs.len());- let mut created_at = Vec::with_capacity(jobs.len());- let mut lock_ids = Vec::with_capacity(jobs.len());- let mut last_heartbeats = Vec::with_capacity(jobs.len());- let mut janitor_touch_counts = Vec::with_capacity(jobs.len());- let mut transition_counts = Vec::with_capacity(jobs.len());- let mut last_transitions = Vec::with_capacity(jobs.len());- let mut queue_names = Vec::with_capacity(jobs.len());- let mut states = Vec::with_capacity(jobs.len());- let mut scheduleds = Vec::with_capacity(jobs.len());- let mut priorities = Vec::with_capacity(jobs.len());- let mut parent_run_ids = Vec::with_capacity(jobs.len());- let mut vm_states = Vec::with_capacity(jobs.len());- let mut metadatas = Vec::with_capacity(jobs.len());- let mut parameters = Vec::with_capacity(jobs.len());- let mut blob = Vec::with_capacity(jobs.len());-- for d in &jobs {- let vm_state = d.vm_state.clone();- if should_compress_vm_state {- vm_states.push(compress_vm_state(vm_state)?);- } else {- vm_states.push(vm_state);- }-- ids.push(d.id.unwrap_or_else(Uuid::now_v7));- team_ids.push(d.team_id);- function_ids.push(d.function_id);- created_at.push(now);- lock_ids.push(None::<Uuid>);- last_heartbeats.push(None::<DateTime<Utc>>);- janitor_touch_counts.push(0);- transition_counts.push(0);- last_transitions.push(now);- queue_names.push(d.queue_name.clone());- states.push(JobState::Available);- scheduleds.push(d.scheduled);- priorities.push(d.priority);- parent_run_ids.push(d.parent_run_id.clone());- metadatas.push(d.metadata.clone());- parameters.push(d.parameters.clone());- blob.push(d.blob.clone());- }-- // Using the "unnest" function to turn an array of rows into a set of rows- sqlx::query(- r#"-INSERT INTO cyclotron_jobs- (- id,- team_id,- function_id,- created,- lock_id,- last_heartbeat,- janitor_touch_count,- transition_count,- last_transition,- queue_name,- state,- scheduled,- priority,- parent_run_id,- vm_state,- metadata,- parameters,- blob- )-SELECT *-FROM UNNEST(- $1,- $2,- $3,- $4,- $5,- $6,- $7,- $8,- $9,- $10,- $11,- $12,- $13,- $14,- $15,- $16,- $17,- $18- )-"#,- )- .bind(&ids)- .bind(team_ids)- .bind(function_ids)- .bind(created_at)- .bind(lock_ids)- .bind(last_heartbeats)- .bind(janitor_touch_counts)- .bind(transition_counts)- .bind(last_transitions)- .bind(queue_names)- .bind(states)- .bind(scheduleds)- .bind(priorities)- .bind(parent_run_ids)- .bind(vm_states)- .bind(metadatas)- .bind(parameters)- .bind(blob)- .execute(executor)- .await?;-- Ok(ids)-}--// wraps CSV rows to be encoded and batch written-// to Postgres as part of a COPY FROM STDIN stmt-#[derive(Debug, serde::Serialize)]-struct CopyFromJobInit {- id: Uuid,- team_id: i32,- function_id: Option<Uuid>,- created: DateTime<Utc>,- lock_id: Option<Uuid>,- last_heartbeat: Option<DateTime<Utc>>,- janitor_touch_count: i32,- transition_count: i32,- last_transition: DateTime<Utc>,- queue_name: String,- job_state: JobState,- scheduled: DateTime<Utc>,- priority: i16,- parent_run_id: Option<String>,- vm_state: Option<String>,- metadata: Option<String>,- parameters: Option<String>,- blob: Option<String>,-}--pub async fn bulk_create_jobs_copy(- pool: &Pool<Postgres>,- jobs: Vec<JobInit>,- should_compress_vm_state: bool,-) -> Result<Vec<Uuid>, QueueError> {- let mut ids = Vec::with_capacity(jobs.len());- let now = Utc::now();-- // set up CSV in mem buffer for capturing the row data; try to- // avoid too many buffer extension allocations as we fill it- let estimated_buffer_size = jobs.len() * ESTIMATED_RECORD_SIZE;- let buffer = Bytes::with_capacity(estimated_buffer_size);- let mut csv_writer = csv::WriterBuilder::new()- .delimiter(b',')- .has_headers(false)- .from_writer(buffer);-- for j in jobs {- let new_id = j.id.unwrap_or_else(Uuid::now_v7);- ids.push(new_id);-- let mut vm_state = j.vm_state;- if should_compress_vm_state {- vm_state = compress_vm_state(vm_state)?;- }-- let cj = CopyFromJobInit {- id: new_id,- team_id: j.team_id,- function_id: j.function_id,- created: now,- lock_id: None::<Uuid>,- last_heartbeat: None::<DateTime<Utc>>,- janitor_touch_count: 0,- transition_count: 0,- last_transition: now,- queue_name: j.queue_name,- job_state: JobState::Available,- scheduled: j.scheduled,- priority: j.priority,- parent_run_id: j.parent_run_id,- vm_state: encode_pg_bytea(vm_state),- metadata: encode_pg_bytea(j.metadata),- parameters: encode_pg_bytea(j.parameters),- blob: encode_pg_bytea(j.blob),- };-- csv_writer- .serialize(cj)- .map_err(|e| QueueError::CsvError("csv_serialize", e))?;- }-- csv_writer- .flush()- .map_err(|e| QueueError::CsvError("csv_flush", e.into()))?;-- let mut stream = pool.copy_in_raw(COPY_IN_STMT).await?;- let result = stream.send(&csv_writer.get_ref()[..]).await;- if let Err(e) = result {- let _unused = stream- .abort(format!("failed to send COPY IN record: {e}"))- .await;- return Err(QueueError::SqlxError(e));- }-- let _unused = result.unwrap();- let rows_affected = stream.finish().await.map_err(QueueError::SqlxError)?;- inc("bulk_create_jobs_copy_rows_affected", &[], rows_affected);-- Ok(ids)-}--// COPY FROM STDIN with CSV input method must encode BYTEA binary blobs-// as specially-formatted UTF-8 Strings. When the Option is None,-// the CSV field will be empty and the DB column will record a NULL value-fn encode_pg_bytea(buffer: Option<Bytes>) -> Option<String> {- buffer.map(|bs| format!("\\x{}", hex::encode(bs)))-}diff --git a/rust/cyclotron-core/src/ops/meta.rs b/rust/cyclotron-core/src/ops/meta.rsdeleted file mode 100644index 446fe2adfe7a..000000000000--- a/rust/cyclotron-core/src/ops/meta.rs+++ /dev/null@@ -1,82 +0,0 @@-use sqlx::postgres::PgQueryResult;-use uuid::Uuid;--use crate::{- error::{JobError, QueueError},- DEAD_LETTER_QUEUE,-};--pub async fn count_total_waiting_jobs<'c, E>(executor: E) -> Result<Vec<(u64, String)>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- struct Count {- count: Option<i64>,- queue_name: String,- }-- let res = sqlx::query_as!(- Count,- "SELECT COUNT(*), queue_name FROM cyclotron_jobs WHERE state = 'available' AND scheduled <= NOW() GROUP BY queue_name",- )- .fetch_all(executor)- .await?;-- Ok(res- .into_iter()- .map(|r| (r.count.unwrap_or(0) as u64, r.queue_name))- .collect())-}--// Returns an InvalidLock error if the query run did not affect any rows.-pub fn throw_if_no_rows(res: PgQueryResult, job: Uuid, lock: Uuid) -> Result<(), JobError> {- if res.rows_affected() == 0 {- Err(JobError::InvalidLock(lock, job))- } else {- Ok(())- }-}--/// Move a job into the dead letter queue, also updating the metadata table. Note that this operation does not-/// require a lock on the job. This is because the janitor needs to DLQ jobs that are stalled. The worker wrapper-/// around this operation should check that the job is "known" (owned by it) before calling this function.-pub async fn dead_letter<'c, E>(executor: E, job: Uuid, reason: &str) -> Result<(), QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres> + Clone,-{- // The first thing we do here is forcefully take the lock on this job, ensuring any subsequent worker- // operations will fail - we do this because the janitor can move jobs out from under workers. We mark- // the job as "running" and heartbeat so nothing else messes with it.- let lock = Uuid::now_v7();- let original_queue_name = sqlx::query_scalar!(- "UPDATE cyclotron_jobs SET state = 'running', lock_id = $1, last_heartbeat=NOW() WHERE id = $2 returning queue_name",- lock,- job- )- .fetch_optional(executor.clone())- .await?;-- let Some(original_queue_name) = original_queue_name else {- return Err(JobError::UnknownJobId(job).into());- };-- // Now we add an entry to the dead metadata queue- sqlx::query!(- "INSERT INTO cyclotron_dead_letter_metadata (job_id, original_queue_name, reason, dlq_time) VALUES ($1, $2, $3, NOW())",- job,- original_queue_name,- reason- ).execute(executor.clone()).await?;-- // And finally, we move the job to the dead letter queue. Jobs in the DLQ are "available", because if they ever- // get moved back to a queue, they should be re-run.- sqlx::query!(- "UPDATE cyclotron_jobs SET state = 'available', lock_id = NULL, queue_name = $1 WHERE id = $2",- DEAD_LETTER_QUEUE,- job- )- .execute(executor)- .await?;-- Ok(())-}diff --git a/rust/cyclotron-core/src/ops/mod.rs b/rust/cyclotron-core/src/ops/mod.rsdeleted file mode 100644index 59be6e90cc7b..000000000000--- a/rust/cyclotron-core/src/ops/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod compress;-pub mod janitor;-pub mod manager;-pub mod meta;-pub mod worker;diff --git a/rust/cyclotron-core/src/ops/worker.rs b/rust/cyclotron-core/src/ops/worker.rsdeleted file mode 100644index 10992502969c..000000000000--- a/rust/cyclotron-core/src/ops/worker.rs+++ /dev/null@@ -1,315 +0,0 @@-use chrono::{DateTime, Utc};-use sqlx::{postgres::PgArguments, query::Query, Encode, QueryBuilder, Type};-use uuid::Uuid;--use crate::{- error::QueueError,- ops::compress::decompress_vm_state,- types::{Bytes, Job, JobState, JobUpdate},-};--use super::{compress::compress_vm_state, meta::throw_if_no_rows};--// Dequeue the next job batch from the queue, skipping VM state since it can be large-pub async fn dequeue_jobs<'c, E>(- executor: E,- queue: &str,- max: usize,-) -> Result<Vec<Job>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- // Transient lock id. This could be a worker ID, or something, but for now it's totally random (per-batch)- let lock_id = Uuid::now_v7();- Ok(sqlx::query_as!(- Job,- r#"-WITH available AS (- SELECT- id,- state- FROM cyclotron_jobs- WHERE- state = 'available'::JobState- AND queue_name = $1- AND scheduled <= NOW()- ORDER BY- priority ASC,- scheduled ASC- LIMIT $2- FOR UPDATE SKIP LOCKED-)-UPDATE cyclotron_jobs-SET- state = 'running'::JobState,- lock_id = $3,- last_heartbeat = NOW(),- last_transition = NOW(),- transition_count = transition_count + 1-FROM available-WHERE- cyclotron_jobs.id = available.id-RETURNING- cyclotron_jobs.id,- team_id,- available.state as "state: JobState",- queue_name,- priority,- function_id,- created,- last_transition,- scheduled,- transition_count,- parent_run_id,- NULL::bytea as vm_state,- metadata,- parameters,- blob,- lock_id,- last_heartbeat,- janitor_touch_count- "#,- queue,- max as i64,- lock_id- )- .fetch_all(executor)- .await?)-}--// Dequeue a batch of jobs, with their VM state.-pub async fn dequeue_with_vm_state<'c, E>(- executor: E,- queue: &str,- max: usize,-) -> Result<Vec<Job>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let lock_id = Uuid::now_v7();- let result = sqlx::query_as!(- Job,- r#"-WITH available AS (- SELECT- id,- state- FROM cyclotron_jobs- WHERE- state = 'available'::JobState- AND queue_name = $1- AND scheduled <= NOW()- ORDER BY- priority ASC,- scheduled ASC- LIMIT $2- FOR UPDATE SKIP LOCKED-)-UPDATE cyclotron_jobs-SET- state = 'running'::JobState,- lock_id = $3,- last_heartbeat = NOW(),- last_transition = NOW(),- transition_count = transition_count + 1-FROM available-WHERE- cyclotron_jobs.id = available.id-RETURNING- cyclotron_jobs.id,- team_id,- available.state as "state: JobState",- queue_name,- priority,- function_id,- created,- last_transition,- scheduled,- transition_count,- parent_run_id,- vm_state,- metadata,- parameters,- blob,- lock_id,- last_heartbeat,- janitor_touch_count- "#,- queue,- max as i64,- lock_id- )- .fetch_all(executor)- .await?;-- let mut out: Vec<Job> = Vec::with_capacity(result.len());- for mut job in result {- job.vm_state = decompress_vm_state(job.vm_state);- out.push(job);- }-- Ok(out)-}--pub async fn get_vm_state<'c, E>(- executor: E,- job_id: Uuid,- lock_id: Uuid,-) -> Result<Option<Bytes>, QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- struct VMState {- vm_state: Option<Bytes>,- }-- let res = sqlx::query_as!(- VMState,- "SELECT vm_state FROM cyclotron_jobs WHERE id = $1 AND lock_id = $2",- job_id,- lock_id- )- .fetch_one(executor)- .await?;-- Ok(decompress_vm_state(res.vm_state))-}--// NOTE - this clears the lock_id when the job state is set to anything other than "running", since that indicates-// the worker is finished with the job. This means subsequent flushes with the same lock_id will fail.-pub async fn flush_job<'c, E>(- executor: E,- job_id: Uuid,- updates: &JobUpdate,- should_compress_vm_state: bool,-) -> Result<(), QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let job_returned = !matches!(updates.state, Some(JobState::Running));- let lock_id = updates.lock_id;-- let mut query = QueryBuilder::new("UPDATE cyclotron_jobs SET ");- let mut needs_comma = false;-- if let Some(state) = &updates.state {- set_helper(&mut query, "state", state, needs_comma);- needs_comma = true;- }-- if let Some(queue_name) = &updates.queue_name {- set_helper(&mut query, "queue_name", queue_name, needs_comma);- needs_comma = true;- }-- if let Some(priority) = &updates.priority {- set_helper(&mut query, "priority", priority, needs_comma);- needs_comma = true;- }-- if let Some(scheduled) = &updates.scheduled {- set_helper(&mut query, "scheduled", scheduled, needs_comma);- needs_comma = true;- }-- if let Some(parent_run_id) = &updates.parent_run_id {- set_helper(&mut query, "parent_run_id", parent_run_id, needs_comma);- needs_comma = true;- }-- if let Some(vm_state) = &updates.vm_state {- if should_compress_vm_state {- let new_vm_state = compress_vm_state(vm_state.clone())?;- set_helper(&mut query, "vm_state", new_vm_state.to_owned(), needs_comma)- } else {- set_helper(&mut query, "vm_state", vm_state, needs_comma)- }- needs_comma = true;- }-- if let Some(metadata) = &updates.metadata {- set_helper(&mut query, "metadata", metadata, needs_comma);- needs_comma = true;- }-- if let Some(parameters) = &updates.parameters {- set_helper(&mut query, "parameters", parameters, needs_comma);- needs_comma = true;- }-- if let Some(blob) = &updates.blob {- set_helper(&mut query, "blob", blob, needs_comma);- needs_comma = true;- }-- if job_returned {- // If we're returning this job, clear the lock id and the heartbeat- set_helper(&mut query, "lock_id", Option::<Uuid>::None, needs_comma);- set_helper(- &mut query,- "last_heartbeat",- Option::<DateTime<Utc>>::None,- true,- );- } else {- // Otherwise, flushing a job update indicates forward progress, so we update the heartbeat- set_helper(&mut query, "last_heartbeat", Utc::now(), needs_comma);- }-- query.push(" WHERE id = ");- query.push_bind(job_id);- query.push(" AND lock_id = ");- query.push_bind(lock_id);-- assert_does_update(executor, job_id, lock_id, query.build()).await?;- Ok(())-}--fn set_helper<'args, T, DB>(- query: &mut QueryBuilder<'args, DB>,- column_name: &str,- value: T,- needs_comma: bool,-) where- T: 'args + Encode<'args, DB> + Send + Type<DB>,- DB: sqlx::Database,-{- if needs_comma {- query.push(",");- }- query.push(column_name);- query.push(" = ");- query.push_bind(value);-}--pub async fn set_heartbeat<'c, E>(- executor: E,- job_id: Uuid,- lock_id: Uuid,-) -> Result<(), QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let q = sqlx::query!(- "UPDATE cyclotron_jobs SET last_heartbeat = NOW() WHERE id = $1 AND lock_id = $2",- job_id,- lock_id- );- assert_does_update(executor, job_id, lock_id, q).await-}--// Simple wrapper, that just executes a query and returns an InvalidLock error if no rows were affected.-async fn assert_does_update<'c, E>(- executor: E,- job_id: Uuid,- lock_id: Uuid,- query: Query<'_, sqlx::Postgres, PgArguments>,-) -> Result<(), QueueError>-where- E: sqlx::Executor<'c, Database = sqlx::Postgres>,-{- let res = query.execute(executor).await?;-- // JobError -> QueueError- Ok(throw_if_no_rows(res, job_id, lock_id)?)-}diff --git a/rust/cyclotron-core/src/types.rs b/rust/cyclotron-core/src/types.rsdeleted file mode 100644index 1064cff70205..000000000000--- a/rust/cyclotron-core/src/types.rs+++ /dev/null@@ -1,130 +0,0 @@-use chrono::{DateTime, Utc};-use serde::{Deserialize, Serialize};-use std::str::FromStr;-use uuid::Uuid;--pub type Bytes = Vec<u8>;--#[derive(Debug, Deserialize, Serialize, sqlx::Type)]-#[serde(rename_all = "lowercase")]-#[sqlx(type_name = "JobState", rename_all = "lowercase")]-pub enum JobState {- Available,- Running,- Completed,- Failed,- Paused,- Canceled,-}--impl FromStr for JobState {- type Err = ();-- fn from_str(s: &str) -> Result<Self, Self::Err> {- match s {- "available" => Ok(JobState::Available),- "running" => Ok(JobState::Running),- "completed" => Ok(JobState::Completed),- "failed" => Ok(JobState::Failed),- "paused" => Ok(JobState::Paused),- "canceled" => Ok(JobState::Canceled),- _ => Err(()),- }- }-}--// The chunk of data needed to enqueue a job-#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq)]-pub struct JobInit {- pub id: Option<Uuid>,- pub team_id: i32,- pub queue_name: String,- pub priority: i16,- pub scheduled: DateTime<Utc>,- pub function_id: Option<Uuid>,- pub parent_run_id: Option<String>,- pub vm_state: Option<Bytes>,- pub parameters: Option<Bytes>,- pub blob: Option<Bytes>,- pub metadata: Option<Bytes>,-}--#[derive(Debug, Deserialize, Serialize)]-pub struct Job {- // Job metadata- pub id: Uuid,- pub team_id: i32,- pub function_id: Option<Uuid>, // Some jobs might not come from hog, and it doesn't /kill/ use to support that- pub created: DateTime<Utc>,-- // Queue bookkeeping- // This will be set for any worker that ever has a job in the "running" state (so any worker that dequeues a job)- // but I don't want to do the work to encode that in the type system right now - later it should be- pub lock_id: Option<Uuid>,- pub last_heartbeat: Option<DateTime<Utc>>,- pub janitor_touch_count: i16,- pub transition_count: i16,- pub last_transition: DateTime<Utc>,-- // Virtual queue components- pub queue_name: String, // We can have multiple "virtual queues" workers pull from-- // Job availability- pub state: JobState,- pub priority: i16, // For sorting "available" jobs. Lower is higher priority- pub scheduled: DateTime<Utc>,-- // Job data- pub parent_run_id: Option<String>, // Optional batch job ID for tracking batch workflows- pub vm_state: Option<Bytes>, // The state of the VM this job is running on (if it exists)- pub metadata: Option<Bytes>, // Additional fields a worker can tack onto a job, for e.g. tracking some state across retries (or number of retries in general by a given class of worker)- pub parameters: Option<Bytes>, // The actual parameters of the job (function args for a hog function, http request for a fetch function)- pub blob: Option<Bytes>, // An additional, binary, parameter field (for things like fetch request body)-}--// A struct representing a set of updates for a job. Outer none values mean "don't update this field",-// with nested none values meaning "set this field to null" for nullable fields-#[derive(Debug, Deserialize, Serialize)]-pub struct JobUpdate {- pub lock_id: Uuid, // The ID of the lock acquired when this worker dequeued the job, required for any update to be valid- pub state: Option<JobState>,- pub queue_name: Option<String>,- pub priority: Option<i16>,- pub scheduled: Option<DateTime<Utc>>,- pub parent_run_id: Option<Option<String>>,- pub vm_state: Option<Option<Bytes>>,- pub metadata: Option<Option<Bytes>>,- pub parameters: Option<Option<Bytes>>,- pub blob: Option<Option<Bytes>>,- #[serde(skip)]- pub last_heartbeat: Option<DateTime<Utc>>,-}--impl JobUpdate {- pub fn new(lock_id: Uuid) -> Self {- Self {- lock_id,- state: None,- queue_name: None,- priority: None,- scheduled: None,- parent_run_id: None,- vm_state: None,- metadata: None,- parameters: None,- blob: None,- last_heartbeat: Some(Utc::now()), // Dequeueing a job always touches the heartbeat- }- }-}--// Result of janitor's `delete_completed_and_failed_jobs`-#[derive(sqlx::FromRow, Debug)]-pub struct AggregatedDelete {- // `last_transition` column truncated to the hour.- pub hour: DateTime<Utc>,- pub team_id: i64,- pub function_id: Option<String>,- pub state: String,- pub count: i64,-}diff --git a/rust/cyclotron-core/src/worker.rs b/rust/cyclotron-core/src/worker.rsdeleted file mode 100644index ceceecf9d774..000000000000--- a/rust/cyclotron-core/src/worker.rs+++ /dev/null@@ -1,538 +0,0 @@-use std::{- collections::HashMap,- future::Future,- sync::{Arc, Weak},- task::Poll,-};--use chrono::{DateTime, Duration, Utc};-use futures::FutureExt;-use sqlx::PgPool;-use std::sync::Mutex;-use tokio::sync::oneshot;-use tracing::error;-use uuid::Uuid;--use crate::{- config::WorkerConfig,- error::JobError,- ops::{- meta::dead_letter,- worker::{dequeue_jobs, dequeue_with_vm_state, flush_job, get_vm_state, set_heartbeat},- },- types::Bytes,- Job, JobState, JobUpdate, PoolConfig, QueueError,-};--// The worker's interface to the underlying queue system - a worker can do everything except-// create jobs (because job creation has to be shard-aware).-//-// This interface looks stange, because a lot of things that would normally be done with lifetimes-// and references are done with uuid's instead (and we lose some nice raii stuff as a result), but-// the reason for this is that this is designed to be embedded in other runtimes, where handing out-// lifetime'd references or things with drop impls isn't really practical. This makes it a little-// awkward to use, but since it's meant to be the core of other abstractions, I think it's ok for-// now (client libraries should wrap this to provide better interfaces).-pub struct Worker {- pool: PgPool,- // All the jobs the worker is currently working on, and hasn't released for returning- // to the queue.- // TRICKY - this is a sync mutex, because that simplifies using the manager in an FFI- // context (since most functions below can be sync). We have to be careful never to- // hold a lock across an await point, though.- running: Mutex<HashMap<Uuid, JobUpdate>>,-- // When a user calls release, we queue up the update to be flushed, but only flush on- // some conditions.- flush_batch: Arc<Mutex<FlushBatch>>,-- pub heartbeat_window: Duration, // The worker will only pass one heartbeat to the DB per job every heartbeat_window- pub linger: Duration, // Updates will be held at most this long- pub max_buffered: usize, // Updates will be flushed after this many are buffered- pub max_bytes: usize, // Updates will be flushed after the vm_state and blob sizes combined exceed this- pub should_compress_vm_state: bool, // Compress vm_state when persisting to the DB?-}--impl Worker {- pub async fn new(pool: PoolConfig, worker: WorkerConfig) -> Result<Self, QueueError> {- let pool = pool.connect().await?;- Ok(Self::from_pool(pool, worker))- }-- pub fn from_pool(pool: PgPool, worker_config: WorkerConfig) -> Self {- let worker = Self {- pool,- running: Default::default(),- heartbeat_window: worker_config.heartbeat_window(),- flush_batch: Arc::new(Mutex::new(FlushBatch::new(- worker_config.should_compress_vm_state(),- ))),- linger: worker_config.linger_time(),- max_buffered: worker_config.max_updates_buffered(),- max_bytes: worker_config.max_bytes_buffered(),- should_compress_vm_state: worker_config.should_compress_vm_state(),- };-- tokio::spawn(flush_loop(- worker.pool.clone(),- Arc::downgrade(&worker.flush_batch),- worker.max_buffered,- worker.max_bytes,- worker_config.flush_loop_interval(),- ));-- worker- }-- /// Dequeues jobs from the queue, and returns them. Job sorting happens at the queue level,- /// workers can't provide any filtering or sorting criteria - queue managers decide which jobs are run,- /// workers just run them.- pub async fn dequeue_jobs(&self, queue: &str, limit: usize) -> Result<Vec<Job>, QueueError> {- let jobs = dequeue_jobs(&self.pool, queue, limit).await?;-- let mut running = self.running.lock().unwrap();- for job in &jobs {- // We need to hang onto the locks for a job until we flush it, so we can send updates.- let update = JobUpdate::new(- job.lock_id- .expect("Yell at oliver that the dequeuing code is broken. He's very sorry that your process just panicked"),- );- running.insert(job.id, update);- }-- Ok(jobs)- }-- /// This is the same as dequeue_jobs, but it also returns the vm_state of the job- pub async fn dequeue_with_vm_state(- &self,- queue: &str,- limit: usize,- ) -> Result<Vec<Job>, QueueError> {- let jobs = dequeue_with_vm_state(&self.pool, queue, limit).await?;-- let mut running = self.running.lock().unwrap();- for job in &jobs {- // We need to hang onto the locks for a job until we flush it, so we can send updates.- let update = JobUpdate::new(- job.lock_id- .expect("Yell at oliver that the dequeuing (with vm) code is broken. He's very sorry that your process just panicked"),- );- running.insert(job.id, update);- }-- Ok(jobs)- }-- /// Retrieve the VM state for a job, if, for example, you dequeued it and then realised you- /// need the VM state as well.- pub async fn get_vm_state(&self, job_id: Uuid) -> Result<Option<Bytes>, QueueError> {- let lock_id = {- let pending = self.running.lock().unwrap();- pending- .get(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .lock_id- };-- get_vm_state(&self.pool, job_id, lock_id).await- }-- /// Release a job back to the queue. Callers are returned a flush handle, which they- /// may use to await the flushing of the updated job state, which happens asynchronously- /// to allow for batching of updates. Callers may drop the flush handle without impacting- /// the flushing of the update. This function returns an error if the caller tries to release- /// a job that this `Worker` doesn't know about, or if the worker tries to release a job- /// without having provided a next state for it.- ///- /// The flush handle returned here will resolve to an error if the asynchronous flush operation- /// fails in non-retryable fashion. Retryable errors during flush are not surfaced to the handle,- /// and the flush will be retried until it succeeds, a non-retryable error is encountered (e.g.- /// this workers lock on the job has been lost), or until the deadline is exceeded, if one is- /// provided. All updates will have at least one flush attempt.- pub fn release_job(&self, job_id: Uuid, deadline: Option<Duration>) -> FlushHandle {- let update = {- let mut running = self.running.lock().unwrap();- let Some(update) = running.remove(&job_id) else {- return FlushHandle::immediate(Err(JobError::UnknownJobId(job_id)));- };- match update.state {- Some(JobState::Running) | None => {- // Keep track of any /other/ updates that might have been stored, so this- // error is recoverable simply by providing an appropriate new state.- running.insert(job_id, update);- return FlushHandle::immediate(Err(JobError::FlushWithoutNextState(job_id)));- }- _ => update,- }- };-- // If we were given a deadline, this update should be flushed at least as soon as then,- // otherwise we can wait the full linger time before flushing it.- let now = Utc::now();- let flush_by = now + deadline.unwrap_or(self.linger);- let deadline = deadline.map(|d| now + d);-- let (pending, handle) = PendingUpdate::new(job_id, update, deadline);-- let mut batch = self.flush_batch.lock().unwrap();- batch.add(pending, flush_by);- handle- }-- /// Force flush all pending updates, regardless of linger time or buffer size.- /// Transient errors encountered during the flush will cause the operation to- /// be aborted, and the error to be returned to the caller. If no transient errors- /// are encountered, all permanent errors will be dispatched to the relevant flush- /// handle, and this function will return success.- pub async fn force_flush(&self) -> Result<(), QueueError> {- let mut to_flush = { self.flush_batch.lock().unwrap().take() };- let res = if !to_flush.pending.is_empty() {- to_flush.flush(&self.pool).await- } else {- Ok(())- };- // If the flush successed, to_flush is empty, otherwise, we need to retry any- // updates still in it.- self.flush_batch.lock().unwrap().merge(to_flush);- res- }-- /// Jobs are reaped after some seconds (the number is deployment specific, and may become- /// specific on job properties like queue name in the future, as we figure out what /kinds/ of- /// jobs are longer or shorter running). A job is considered "dead" if it's in a running state,- /// and it's last heartbeat was more than the reaping time ago. This, like flush, returns an- /// error if you try to set the heartbeat on a job whose lock you don't have (which can happen- /// if e.g. the job was reaped out from under you).- pub async fn heartbeat(&self, job_id: Uuid) -> Result<(), QueueError> {- let lock_id = {- let mut pending = self.running.lock().unwrap();- let update = pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?;-- let should_heartbeat = update- .last_heartbeat- .is_none_or(|last| Utc::now() - last > self.heartbeat_window);-- if !should_heartbeat {- return Ok(());- }-- update.last_heartbeat = Some(Utc::now());- update.lock_id- };- let mut connection = self.pool.acquire().await?;- set_heartbeat(connection.as_mut(), job_id, lock_id).await- }-- /// This is how you "return" a job to the queue, by setting the state to "available"- pub fn set_state(&self, job_id: Uuid, state: JobState) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .state = Some(state);- Ok(())- }-- pub fn set_queue(&self, job_id: Uuid, queue: &str) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .queue_name = Some(queue.to_string());- Ok(())- }-- /// Jobs are dequeued lowest-priority-first, so this is how you change the "base" priority of a job- /// (control tables may apply further deltas if e.g. a given function is in a degraded state)- pub fn set_priority(&self, job_id: Uuid, priority: i16) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .priority = Some(priority);- Ok(())- }-- /// This is how you do e.g. retries after some time, by setting the scheduled time- /// to some time in the future. Sleeping, retry backoff, scheduling - it's all the same operation,- /// this one.- pub fn set_scheduled_at(&self, job_id: Uuid, scheduled: DateTime<Utc>) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .scheduled = Some(scheduled);- Ok(())- }-- /// Passing None here will clear the vm_state- pub fn set_vm_state(- &self,- job_id: Uuid,- vm_state: Option<Bytes>, // This (and the following) are Options, because the user can null them (by calling with None)- ) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .vm_state = Some(vm_state); // conditional compression applied in ops/worker.rs flush_job()- Ok(())- }-- /// Passing None here will clear the metadata- pub fn set_metadata(&self, job_id: Uuid, metadata: Option<Bytes>) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .metadata = Some(metadata);- Ok(())- }-- /// Passing None here will clear the parameters- pub fn set_parameters(&self, job_id: Uuid, parameters: Option<Bytes>) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .parameters = Some(parameters);- Ok(())- }-- pub async fn dead_letter(&self, job_id: Uuid, reason: &str) -> Result<(), QueueError> {- // KLUDGE: Non-lexical lifetimes are good but they're just not perfect yet -- // changing this to not be a scope bump, and instead explicitly drop'ing the- // lock after the if check, makes the compiler think the lock is held across- // the await point.- {- let pending = self.running.lock().unwrap();- if !pending.contains_key(&job_id) {- return Err(JobError::UnknownJobId(job_id).into());- }- }-- dead_letter(&self.pool, job_id, reason).await- }-- /// Passing None here will clear the blob- pub fn set_blob(&self, job_id: Uuid, blob: Option<Bytes>) -> Result<(), JobError> {- let mut pending = self.running.lock().unwrap();- pending- .get_mut(&job_id)- .ok_or(JobError::UnknownJobId(job_id))?- .blob = Some(blob);- Ok(())- }-}--// Started by each worker on creation, just loops seeing if the passed batch can be flushed, and-// if it can, flushing it.-async fn flush_loop(- pool: PgPool,- batch: Weak<Mutex<FlushBatch>>,- max_buffered: usize,- max_bytes: usize,- interval: Duration,-) {- loop {- let Some(batch) = batch.upgrade() else {- // The batch has been dropped, we should exit.- break;- };- // Contemplating sync mutexes on the tree of woe.- let mut to_flush = { batch.lock().unwrap().take() };- if to_flush.should_flush(max_buffered, max_bytes) {- if let Err(e) = to_flush.flush(&pool).await {- error!("Error flushing batch: {:?}", e);- }- }- // We can always merge the taken batch back into the pending batch - on successful- // flush, the taken batch will be empty, and on failure, we need to re-queue those updates.- // TRICKY - we take care not to bind the lock here. Compilation WILL fail if it's bound,- // because it makes this future !Send, and the tokio::spawn above will fail, but in case- // we change the looping strategy, I'm calling it out explicitly too.- batch.lock().unwrap().merge(to_flush);- tokio::time::sleep(interval.to_std().unwrap()).await;- }-}--struct FlushBatch {- // The minimum of the "flush_by" times of all the updates in the batch- pub next_mandatory_flush: DateTime<Utc>,- // The list of pending updates. Note that the update batch makes no effort- // to deduplicate or compact updates.- pub pending: Vec<PendingUpdate>,- // A running total of all blob bytes held in the batch- pub blobs_size: usize,- // A running total of all vm_state bytes held in the batch- pub vm_states_size: usize,- // Conditionally compress vm_state in write path?- pub should_compress_vm_state: bool,-}--impl FlushBatch {- pub fn new(should_compress_vm_state: bool) -> Self {- Self {- next_mandatory_flush: Utc::now(),- pending: Default::default(),- blobs_size: 0,- vm_states_size: 0,- should_compress_vm_state,- }- }-- pub fn add(&mut self, pending: PendingUpdate, flush_by: DateTime<Utc>) {- // If this is the start of a new batch, reset the first_insert time- if self.pending.is_empty() {- self.next_mandatory_flush = flush_by;- } else {- self.next_mandatory_flush = self.next_mandatory_flush.min(flush_by);- }-- // Update the sizes of the bytes we track- if let Some(Some(blob)) = pending.update.blob.as_ref() {- self.blobs_size += blob.len();- }- if let Some(Some(vm_state)) = pending.update.vm_state.as_ref() {- self.vm_states_size += vm_state.len();- }- self.pending.push(pending);- }-- async fn flush(&mut self, pool: &PgPool) -> Result<(), QueueError> {- let now = Utc::now();- // First, filter any updates whose deadline is exceeded that we have- // already tried to flush once, sending a deadline exceeded error to the- // handle.- let mut i = 0;- while i < self.pending.len() {- if self.pending[i].deadline.is_some_and(|d| d < now) && self.pending[i].tries > 0 {- self.pending.swap_remove(i).fail_deadline_exceeded();- } else {- i += 1;- }- }-- let mut txn = pool.begin().await?;- let mut results = Vec::new();- for to_flush in self.pending.iter_mut() {- to_flush.tries += 1;- let result = flush_job(- &mut *txn,- to_flush.job_id,- &to_flush.update,- self.should_compress_vm_state,- )- .await;- match result {- Ok(()) => {- results.push(Ok(()));- }- Err(QueueError::JobError(e)) => {- results.push(Err(e));- }- Err(e) => {- return Err(e);- }- }- }- txn.commit().await?;-- // We only dispatch results and clear the pending set if we actually commit the transaction, otherwise- // the updates in this batch should be retried.- for (update, result) in self.pending.drain(..).zip(results) {- update.resolve(result);- }- Ok(())- }-- fn should_flush(&self, max_buffered: usize, max_bytes: usize) -> bool {- let would_flush = Utc::now() >= self.next_mandatory_flush- || self.pending.len() >= max_buffered- || self.blobs_size + self.vm_states_size >= max_bytes;-- would_flush && !self.pending.is_empty() // we only should flush if we have something to flush- }-- // Take the current batch, replacing it in memory with an empty one. Used along with "merge"- // to let us flush without holding the batch lock for the duration of the flush- fn take(&mut self) -> Self {- std::mem::replace(self, FlushBatch::new(self.should_compress_vm_state))- }-- // Combine two batches, setting the next mandatory flush to the earliest of the two- fn merge(&mut self, other: Self) {- self.pending.extend(other.pending);- self.blobs_size += other.blobs_size;- self.vm_states_size += other.vm_states_size;- self.next_mandatory_flush = self.next_mandatory_flush.min(other.next_mandatory_flush);- }-}--struct PendingUpdate {- job_id: Uuid,- update: JobUpdate,- deadline: Option<DateTime<Utc>>,- tries: u8,- tx: oneshot::Sender<Result<(), JobError>>,-}--impl PendingUpdate {- pub fn new(- job_id: Uuid,- update: JobUpdate,- deadline: Option<DateTime<Utc>>,- ) -> (Self, FlushHandle) {- let (tx, rx) = oneshot::channel();- let update = Self {- job_id,- update,- deadline,- tries: 0,- tx,- };- (update, FlushHandle { inner: rx })- }-- pub fn fail_deadline_exceeded(self) {- let job_id = self.job_id;- self.resolve(Err(JobError::DeadlineExceeded(job_id)));- }-- pub fn resolve(self, result: Result<(), JobError>) {- // We do not care if someone is waiting for this result or not- let _unused = self.tx.send(result);- }-}--pub struct FlushHandle {- inner: oneshot::Receiver<Result<(), JobError>>,-}--impl FlushHandle {- pub fn immediate(result: Result<(), JobError>) -> Self {- let (tx, rx) = oneshot::channel();- let _unused = tx.send(result);- Self { inner: rx }- }-}--// If the inner oneshot resolves to an error, we know that the update was dropped before being flushed,-// so we just return a JobError::UpdateDropped. Otherwise, we return the result of the inner oneshot.-impl Future for FlushHandle {- type Output = Result<(), JobError>;-- fn poll(- mut self: std::pin::Pin<&mut Self>,- cx: &mut std::task::Context<'_>,- ) -> std::task::Poll<Self::Output> {- match self.inner.poll_unpin(cx) {- Poll::Ready(Ok(result)) => Poll::Ready(result),- Poll::Ready(Err(_)) => Poll::Ready(Err(JobError::UpdateDropped)),- Poll::Pending => Poll::Pending,- }- }-}diff --git a/rust/cyclotron-core/tests/base_ops.rs b/rust/cyclotron-core/tests/base_ops.rsdeleted file mode 100644index 0f00a04c4ba9..000000000000--- a/rust/cyclotron-core/tests/base_ops.rs+++ /dev/null@@ -1,381 +0,0 @@-use std::sync::Arc;--use chrono::{Duration, Utc};-use common::{assert_job_matches_init, create_new_job, dates_match};-use cyclotron_core::{Job, JobState, QueueManager, Worker, WorkerConfig};-use sqlx::PgPool;-use uuid::Uuid;--mod common;--const VM_STATE_PAYLOAD: &[u8; 6194]= br#"{"id":"00000000-0000-0000-0000-000000000000","globals":{"project":{"id":44444,"name":"test fixture","url":"https://us.posthog.com/project/44444"},"event":{"uuid":"00000000-0000-0000-0000-000000000000","event":"$autocapture","elements_chain":"span:text=\"Awesome Site\"nth-child=\"2\"nth-of-type=\"1\"href=\"/as\"attr__style=\"display: flex; align-items: center; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1 1 0%;\"attr__href=\"/as\";button.rt-BaseButton.rt-Button.rt-high-contrast.rt-r-size-2.rt-reset.rt-variant-ghost:text=\"Awesome Site\"nth-child=\"1\"nth-of-type=\"1\"attr__data-accent-color=\"gray\"attr__class=\"rt-reset rt-BaseButton rt-r-size-2 rt-variant-ghost rt-high-contrast rt-Button\"attr__style=\"width: 100%; justify-content: flex-start; gap: var(--space-2);\";a:nth-child=\"3\"nth-of-type=\"3\"href=\"as\"attr__data-discover=\"true\"attr__href=\"as\";div.rt-Flex.rt-r-fd-column.rt-r-fg-0.rt-r-gap-2.rt-r-h.rt-r-overflow-hidden.rt-r-p-2.rt-r-w:nth-child=\"2\"nth-of-type=\"1\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-2 rt-r-p-2 rt-r-w rt-r-h rt-r-overflow-hidden rt-r-fg-0\"attr__style=\"--width: 100%; --height: 100%;\";div.rt-Flex.rt-r-fd-column.rt-r-gap-0.rt-r-w:nth-child=\"3\"nth-of-type=\"3\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-0 rt-r-w\"attr__style=\"--width: 100%;\";div.rt-Flex.rt-r-fd-column.rt-r-gap-4:nth-child=\"2\"nth-of-type=\"2\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-4\";div.rt-Flex.rt-r-fd-column.rt-r-gap-2.rt-r-p-3.rt-r-w:nth-child=\"1\"nth-of-type=\"1\"attr__class=\"rt-Flex rt-r-fd-column rt-r-gap-2 rt-r-p-3 rt-r-w\"attr__style=\"--width: 190px; border-right: 1px solid var(--gray-a6);\";div:nth-child=\"1\"nth-of-type=\"1\"attr__style=\"position: fixed; z-index: 5; background-color: var(--color-background); height: 100vh; left: 0%;\";div.md:rt-r-display-none.rt-Box.rt-r-display-block:nth-child=\"1\"nth-of-type=\"1\"attr__class=\"rt-Box rt-r-display-block md:rt-r-display-none\";div.rt-Flex.rt-r-gap-0:nth-child=\"2\"nth-of-type=\"1\"attr__class=\"rt-Flex rt-r-gap-0\";div.radix-themes:nth-child=\"8\"nth-of-type=\"1\"attr__data-is-root-theme=\"true\"attr__data-accent-color=\"green\"attr__data-gray-color=\"sage\"attr__data-has-background=\"true\"attr__data-panel-background=\"translucent\"attr__data-radius=\"medium\"attr__data-scaling=\"100%\"attr__style=\"width:100%\"attr__class=\"radix-themes\";body:nth-child=\"2\"nth-of-type=\"1\"attr__style=\"transition: margin 250ms; margin-top: 0px;\"","distinct_id":"00000000-0000-0000-0000-000000000000","properties":{"$process_person_profile":false,"$session_recording_canvas_recording":{},"$os":"iOS","$sdk_debug_retry_queue_size":0,"$replay_sample_rate":null,"$session_entry_pathname":"/","$pageview_id":"00000000-0000-0000-0000-000000000000","$viewport_width":402,"$device_type":"Mobile","distinct_id":"00000000-0000-0000-0000-000000000000","$el_text":"Awesome Site","$session_recording_masking":null,"$session_id":"00000000-0000-0000-0000-000000000000","$pathname":"/","$is_identified":false,"$browser_version":18.3,"$web_vitals_enabled_server_side":true,"$event_type":"click","$initial_person_info":{"r":"$direct","u":"https://some.example.com/?posts%5Bquery%5D=&posts%5Bpage%5D=1"},"$web_vitals_allowed_metrics":null,"$lib_version":"1.230.4","$timezone":"America/New_York","$current_url":"https://some.example.com","$window_id":"00000000-0000-0000-0000-000000000000","$browser_language_prefix":"en","$session_entry_referrer":"$direct","$recording_status":"active","$screen_height":896,"$replay_script_config":null,"$session_recording_network_payload_capture":{"capturePerformance":{"network_timing":true,"web_vitals":true,"web_vitals_allowed_metrics":null}},"$session_entry_referring_domain":"$direct","$lib":"web","$os_version":"18.3.1","$active_feature_flags":[],"$browser":"Mobile Safari","$feature_flag_payloads":{},"token":"redacted","$replay_minimum_duration":null,"$time":1741912549.921,"$sdk_debug_replay_internal_buffer_size":9446,"$dead_clicks_enabled_server_side":false,"$exception_capture_enabled_server_side":false,"$referring_domain":"$direct","$raw_user_agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 18_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Mobile/15E148 Safari/604.1","$browser_language":"en-US","$viewport_height":673,"$host":"some.example.com","$feature_flag_request_id":"00000000-0000-0000-0000-000000000000","$session_entry_url":"https://some.example.com/?posts%5Bquery%5D=&posts%5Bpage%5D=1","$device":"iPhone","$console_log_recording_enabled_server_side":true,"$session_recording_start_reason":"recording_initialized","$insert_id":"redacted","$screen_width":414,"$device_id":"00000000-0000-0000-0000-000000000000","$referrer":"$direct","$configured_session_timeout_ms":1800000,"$session_entry_host":"some.example.com","$sdk_debug_replay_internal_buffer_length":9,"$ce_version":1,"$autocapture_disabled_server_side":false,"$lib_rate_limit_remaining_tokens":99,"$ip":"10.0.0.1","$sent_at":"2025-03-14T00:35:52.922Z","$geoip_city_name":"Springfield","$geoip_country_name":"United States","$geoip_country_code":"US","$geoip_continent_name":"North America","$geoip_continent_code":"NA","$geoip_postal_code":"00000","$geoip_latitude":28.1234,"$geoip_longitude":-81.1234,"$geoip_accuracy_radius":5,"$geoip_time_zone":"America/New_York","$geoip_subdivision_1_code":"FL","$geoip_subdivision_1_name":"Florida","$transformations_succeeded":["GeoIP (00000000-0000-0000-0000-000000000000)"],"$transformations_failed":[]},"timestamp":"2025-03-14T00:35:49.962Z","url":"https://us.posthog.com/project/44444/events/01959214-2a21-7cb4-9bc2-b347c93bec22/2025-03-14T00%3A35%3A49.962Z"},"person":{"id":"00000000-0000-0000-0000-000000000000","properties":{},"name":"00000000-0000-0000-0000-000000000000","url":"https://us.posthog.com/project/44444/person/00000000-0000-0000-0000-000000000000"},"groups":{},"source":{"name":"Acme, Inc.","url":"https://us.posthog.com/project/44444/pipeline/destinations/hog-00000000-0000-0000-0000-000000000000/configuration/"},"inputs":{"email":null,"api_key":"redacted"}},"teamId":44444,"queue":"hog","priority":1,"timings":[],"hogFunctionId":"00000000-0000-0000-0000-000000000000"}"#;--// I know this should be a bunch of tests, but for hacking together stuff right now, it'll do-#[sqlx::test(migrations = "./migrations")]-async fn test_queue(db: PgPool) {- let manager = QueueManager::from_pool(db.clone(), true, true); // defaults to vm_state compression; for testing only!- let mut worker = Worker::from_pool(db, Default::default());- worker.max_buffered = 0; // No buffering for testing, flush immediately-- let job_1 = create_new_job();- let mut job_2 = create_new_job();-- job_2.priority = 2; // Lower priority jobs should be returned second-- let queue_name = job_1.queue_name.clone();-- manager- .create_job(job_1.clone())- .await- .expect("failed to create job");- manager- .create_job(job_2.clone())- .await- .expect("failed to create job");-- let jobs = worker- .dequeue_jobs(&queue_name, 2)- .await- .expect("failed to dequeue job");-- assert_eq!(jobs.len(), 2);- // This also assert that the ordering is correct in terms of priority- assert_job_matches_init(&jobs[0], &job_1);- assert_job_matches_init(&jobs[1], &job_2);-- // Now we can re-queue these jobs (imagine we had done work)- worker- .set_state(jobs[0].id, JobState::Available)- .expect("failed to set state");- worker- .set_state(jobs[1].id, JobState::Available)- .expect("failed to set state");-- // Flush the two jobs, having made no other changes, then assert we can re-dequeue them- let handle_1 = worker.release_job(jobs[0].id, None);- let handle_2 = worker.release_job(jobs[1].id, None);-- worker.force_flush().await.unwrap();- handle_1.await.unwrap();- handle_2.await.unwrap();-- let jobs = worker- .dequeue_jobs(&queue_name, 2)- .await- .expect("failed to dequeue job");-- assert_eq!(jobs.len(), 2);- assert_job_matches_init(&jobs[0], &job_1);- assert_job_matches_init(&jobs[1], &job_2);-- // Re-queue them again- worker- .set_state(jobs[0].id, JobState::Available)- .expect("failed to set state");- worker- .set_state(jobs[1].id, JobState::Available)- .expect("failed to set state");-- let handle_1 = worker.release_job(jobs[0].id, None);- let handle_2 = worker.release_job(jobs[1].id, None);-- worker.force_flush().await.unwrap();- handle_1.await.unwrap();- handle_2.await.unwrap();-- // Spin up two tasks to race on dequeuing, and assert at most 2 jobs are dequeued- let worker: Arc<Worker> = Arc::new(worker);- let moved = worker.clone();- let queue_name_moved = queue_name.clone();- let fut_1 = async move {- moved- .dequeue_jobs(&queue_name_moved, 2)- .await- .expect("failed to dequeue job")- };- let moved = worker.clone();- let queue_name_moved = queue_name.clone();- let fut_2 = async move {- moved- .dequeue_jobs(&queue_name_moved, 2)- .await- .expect("failed to dequeue job")- };-- let (jobs_1, jobs_2) = tokio::join!(fut_1, fut_2);- assert_eq!(jobs_1.len() + jobs_2.len(), 2);-- let jobs = jobs_1- .into_iter()- .chain(jobs_2.into_iter())- .collect::<Vec<_>>();-- // And now, any subsequent dequeues will return no jobs- let empty = worker- .dequeue_jobs(&queue_name, 2)- .await- .expect("failed to dequeue job");- assert_eq!(empty.len(), 0);-- // If we try to flush a job without setting what it's next state will be,- // we should get an error. We don't bother forcing a flush here, because- // the worker should return a handle that immediately resolves.- assert!(worker.release_job(jobs[0].id, None).await.is_err());-- // Trying to flush a job with the state "running" should also fail- worker- .set_state(jobs[1].id, JobState::Running)- .expect("failed to set state");- assert!(worker.release_job(jobs[1].id, None).await.is_err());-- // But if we properly set the state to completed or failed, now we can flush- worker- .set_state(jobs[0].id, JobState::Completed)- .expect("failed to set state");- worker- .set_state(jobs[1].id, JobState::Failed)- .expect("failed to set state");-- let handle_1 = worker.release_job(jobs[0].id, None);- let handle_2 = worker.release_job(jobs[1].id, None);-- worker.force_flush().await.expect("failed to flush job");- handle_1.await.unwrap();- handle_2.await.unwrap();-- // And now, any subsequent dequeues will return no jobs (because these jobs are finished)- let empty = worker- .dequeue_jobs(&queue_name, 2)- .await- .expect("failed to dequeue job");- assert_eq!(empty.len(), 0);-- // Now, lets check that we can set every variable on a job-- // Set up some initial values- let now = Utc::now();- let mut job = create_new_job();- job.queue_name = "test".to_string();- job.priority = 0;- job.scheduled = now - Duration::minutes(2);- job.vm_state = None;- job.parameters = None;- job.metadata = None;-- // Queue the job- manager- .create_job(job.clone())- .await- .expect("failed to create job");-- // Then dequeue it- let job = worker- .dequeue_jobs("test", 1)- .await- .expect("failed to dequeue job")- .pop()- .expect("failed to dequeue job");-- // Set everything we're able to set, including state to available, so we can dequeue it again- worker- .set_state(job.id, JobState::Available)- .expect("failed to set state");- worker- .set_queue(job.id, "test_2")- .expect("failed to set queue");- worker- .set_priority(job.id, 1)- .expect("failed to set priority");- worker- .set_scheduled_at(job.id, now - Duration::minutes(10))- .expect("failed to set scheduled_at");- worker- .set_vm_state(job.id, Some("test".as_bytes().to_owned()))- .expect("failed to set vm_state");- worker- .set_parameters(job.id, Some("test".as_bytes().to_owned()))- .expect("failed to set parameters");- worker- .set_blob(job.id, Some("test".as_bytes().to_owned()))- .expect("failed to set blob");- worker- .set_metadata(job.id, Some("test".as_bytes().to_owned()))- .expect("failed to set metadata");-- // Flush the job- let handle = worker.release_job(job.id, None);-- worker.force_flush().await.unwrap();- handle.await.unwrap();- // Then dequeue it again (this time being sure to grab the vm state too)- let job = worker- .dequeue_with_vm_state("test_2", 1)- .await- .expect("failed to dequeue job")- .pop()- .expect("failed to dequeue job");-- // And every value should be the updated one- assert_eq!(job.queue_name, "test_2");- assert_eq!(job.priority, 1);- assert!(dates_match(&job.scheduled, &(now - Duration::minutes(10))),);- assert_eq!(job.vm_state, Some("test".as_bytes().to_owned()));- assert_eq!(job.parameters, Some("test".as_bytes().to_owned()));- assert_eq!(job.metadata, Some("test".as_bytes().to_owned()));-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_bulk_insert(db: PgPool) {- let worker = Worker::from_pool(db.clone(), Default::default());- let manager = QueueManager::from_pool(db.clone(), true, false);-- let job_template = create_new_job();-- let jobs = (0..100)- .map(|_| {- let mut job = job_template.clone();- job.function_id = Some(Uuid::now_v7());- job- })- .collect::<Vec<_>>();-- manager- .bulk_create_jobs(jobs)- .await- .expect("failed to bulk insert jobs");-- let dequeue_jobs = worker- .dequeue_jobs(&job_template.queue_name, 100)- .await- .expect("failed to dequeue job");-- assert_eq!(dequeue_jobs.len(), 100);-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_bulk_insert_copy_from_with_binary_nulls(db: PgPool) {- let worker = Worker::from_pool(db.clone(), Default::default());- let manager = QueueManager::from_pool(db.clone(), false, true);-- let job_template = create_new_job();-- let jobs = (0..1000)- .map(|_| {- let mut job = job_template.clone();- job.function_id = Some(Uuid::now_v7());-- // all BYTEA fields will be None, and record as NULLs-- job- })- .collect::<Vec<_>>();-- manager- .bulk_create_jobs(jobs)- .await- .expect("failed to bulk insert jobs");-- let results = worker- .dequeue_jobs(&job_template.queue_name, 100)- .await- .expect("failed to dequeue job");-- assert_eq!(results.len(), 100);-- for result in results {- assert!(result.function_id.is_some());- let fid = result.function_id.unwrap().to_string();- assert!(Uuid::parse_str(&fid).is_ok());-- assert!(result.vm_state.is_none());- assert!(result.metadata.is_none());- assert!(result.parameters.is_none());- assert!(result.blob.is_none());- }-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_bulk_insert_copy_from_with_binary_blobs(db: PgPool) {- let worker = Worker::from_pool(db.clone(), Default::default());- let manager = QueueManager::from_pool(db.clone(), false, true);-- let job_template = create_new_job();-- let jobs = (0..100)- .map(|_| {- let mut job = job_template.clone();- job.function_id = Some(Uuid::now_v7());-- // populate fields that map to Postgres BYTEA columns- job.vm_state = Some(VM_STATE_PAYLOAD.to_vec());- job.metadata = Some(VM_STATE_PAYLOAD.to_vec());- job.parameters = Some(VM_STATE_PAYLOAD.to_vec());- job.blob = Some(VM_STATE_PAYLOAD.to_vec());-- job- })- .collect::<Vec<_>>();-- manager- .bulk_create_jobs(jobs)- .await- .expect("failed to bulk insert jobs");-- let results: Vec<Job> = worker- .dequeue_jobs(&job_template.queue_name, 100)- .await- .expect("failed to dequeue job");-- assert_eq!(results.len(), 100);- let payload = VM_STATE_PAYLOAD.clone().to_vec();-- for result in results {- assert!(result.function_id.is_some());- let fid = result.function_id.unwrap().to_string();- assert!(Uuid::parse_str(&fid).is_ok());-- // dequeue_jobs always returns vm_state as NULL- assert!(result.vm_state.is_none());-- // other binary blobs columns should be returned and hydrated properly- assert!(result.metadata.is_some());- assert!(result.parameters.is_some());- assert!(result.blob.is_some());- assert_eq!(result.metadata.unwrap(), payload);- assert_eq!(result.parameters.unwrap(), payload);- assert_eq!(result.blob.unwrap(), payload);- }-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_bulk_insert_copy_from_with_compressed_vm_state(db: PgPool) {- let worker_cfg = WorkerConfig {- should_compress_vm_state: Some(true),- ..Default::default()- };- let worker = Worker::from_pool(db.clone(), worker_cfg);- let manager = QueueManager::from_pool(db.clone(), true, true);-- let job_template = create_new_job();- let mut job = job_template.clone();- job.function_id = Some(Uuid::now_v7());- job.vm_state = Some(VM_STATE_PAYLOAD.to_vec());- let queue_name = job.queue_name.clone();-- let ids = manager- .bulk_create_jobs(vec![job])- .await- .expect("failed to bulk insert jobs");- assert_eq!(ids.len(), 1);-- let results: Vec<Job> = worker- .dequeue_with_vm_state(&queue_name, 1)- .await- .expect("failed to dequeue Job vm_state");-- assert_eq!(results.len(), 1);- assert_eq!(- results[0].vm_state.as_ref().unwrap(),- &VM_STATE_PAYLOAD.clone().to_vec()- );-}diff --git a/rust/cyclotron-core/tests/common.rs b/rust/cyclotron-core/tests/common.rsdeleted file mode 100644index 9d02d1f94267..000000000000--- a/rust/cyclotron-core/tests/common.rs+++ /dev/null@@ -1,44 +0,0 @@-use chrono::{DateTime, Duration, Utc};-use cyclotron_core::{Job, JobInit};-use uuid::Uuid;--#[allow(dead_code)]-pub fn create_new_job() -> JobInit {- JobInit {- id: None,- team_id: 1,- function_id: Some(Uuid::now_v7()), // Lets us uniquely identify jobs without having the Uuid- parent_run_id: None,- queue_name: "test".to_string(),- priority: 0,- scheduled: Utc::now() - Duration::minutes(1),- vm_state: None,-- parameters: None,- blob: None,- metadata: None,- }-}--#[allow(dead_code)]-pub fn dates_match(left: &DateTime<Utc>, right: &DateTime<Utc>) -> bool {- // Roundtripping a datetime to PG can cause sub-ms differences, so we need to check within a margin of error- // Seeing errors like this in CI:- // assertion `left == right` failed- // left: 2024-08-08T20:41:55.964936Z- // right: 2024-08-08T20:41:55.964936997Z- let diff = *left - *right;- diff.abs() < Duration::milliseconds(1)-}--#[allow(dead_code)]-pub fn assert_job_matches_init(job: &Job, init: &JobInit) {- assert_eq!(job.team_id, init.team_id);- assert_eq!(job.function_id, init.function_id);- assert_eq!(job.queue_name, init.queue_name);- assert_eq!(job.priority, init.priority);- assert!(dates_match(&job.scheduled, &init.scheduled));- assert_eq!(job.vm_state, init.vm_state);- assert_eq!(job.parameters, init.parameters);- assert_eq!(job.metadata, init.metadata);-}diff --git a/rust/cyclotron-core/tests/shard.rs b/rust/cyclotron-core/tests/shard.rsdeleted file mode 100644index 0a30436dd27a..000000000000--- a/rust/cyclotron-core/tests/shard.rs+++ /dev/null@@ -1,70 +0,0 @@-use chrono::{Duration, Utc};-use common::create_new_job;-use cyclotron_core::test_support::Shard;-use sqlx::PgPool;-use tokio::sync::RwLock;--mod common;--pub fn get_shard(db: PgPool) -> Shard {- Shard {- pool: db,- last_healthy: RwLock::new(Utc::now()),- check_interval: Duration::milliseconds(0), // We always want to check the limit, for these tests- depth_limit: 10,- should_compress_vm_state: true, // enabled by default in test suite- should_use_bulk_job_copy: true, // enabled by default in test suite- }-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_shard_limiting(db: PgPool) {- let shard = get_shard(db.clone());-- // We should be able to insert 10 jobs- for _ in 0..10 {- shard.create_job(create_new_job()).await.unwrap();- }-- // And then we should fail on the 11th- let result = shard.create_job(create_new_job()).await;- assert!(result.is_err());-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_shard_blocking_insert_waits(db: PgPool) {- let shard = get_shard(db.clone());-- // We should be able to insert 10 jobs- for _ in 0..10 {- shard.create_job(create_new_job()).await.unwrap();- }-- let timeout = Some(Duration::milliseconds(50));-- let start = Utc::now();- // And then we should fail on the 11th- let result = shard.create_job_blocking(create_new_job(), timeout).await;- assert!(result.is_err());-- // We should have waited at least 50ms- assert!(Utc::now() - start >= Duration::milliseconds(50));-}--#[sqlx::test(migrations = "./migrations")]-pub async fn test_shard_allows_bulk_inserts_beyond_capacity(db: PgPool) {- let shard = get_shard(db.clone());-- // We should be able to insert 10 jobs- for _ in 0..9 {- shard.create_job(create_new_job()).await.unwrap();- }-- // And then we should be able to bulk insert 1000- let inits = (0..1000).map(|_| create_new_job()).collect::<Vec<_>>();- shard.bulk_create_jobs(inits).await.unwrap();-- // And the next insert should fail- let result = shard.create_job(create_new_job()).await;- assert!(result.is_err());-}diff --git a/rust/cyclotron-janitor/Cargo.toml b/rust/cyclotron-janitor/Cargo.tomldeleted file mode 100644index 8c0c4d0f31c1..000000000000--- a/rust/cyclotron-janitor/Cargo.toml+++ /dev/null@@ -1,26 +0,0 @@-[package]-name = "cyclotron-janitor"-version = "0.1.0"-edition = "2021"-publish = false--[lints]-workspace = true--[dependencies]-tracing-subscriber = { workspace = true }-chrono = { workspace = true }-tokio = { workspace = true }-tracing = { workspace = true }-uuid = { workspace = true }-envconfig = { workspace = true }-axum = { workspace = true }-eyre = { workspace = true }-cyclotron-core = { path = "../cyclotron-core" }-common-metrics = { path = "../common/metrics" }-health = { path = "../common/health" }-common-alloc = { path = "../common/alloc" }-common-continuous-profiling = { path = "../common/continuous_profiling" }--[dev-dependencies]-sqlx = { workspace = true }diff --git a/rust/cyclotron-janitor/bin/entrypoint.sh b/rust/cyclotron-janitor/bin/entrypoint.shdeleted file mode 100755index afbe62cd468d..000000000000--- a/rust/cyclotron-janitor/bin/entrypoint.sh+++ /dev/null@@ -1,23 +0,0 @@-#!/bin/bash-set -e--# I set all possible env vars here, tune them as you like-export RUST_LOG="INFO"-export HOST="::"-export PORT="3302"-export DATABASE_URL="postgres://posthog:posthog@localhost:5432/cyclotron"-export CLEANUP_INTERVAL_SECONDS="10"-export PG_MAX_CONNECTIONS="10"-export PG_MIN_CONNECTIONS="1"-export PG_ACQUIRE_TIMEOUT_SECONDS="5"-export PG_MAX_LIFETIME_SECONDS="300"-export PG_IDLE_TIMEOUT_SECONDS="60"-export JANITOR_ID="test-janitor"-export JANITOR_MAX_TOUCHES="2"-export JANITOR_STALL_TIMEOUT_SECONDS="30"--# Uncomment this to have the database be reset every time you start the janitor-sqlx database reset -y --source ../cyclotron-core/migrations-sqlx migrate run --source ../cyclotron-core/migrations--cargo run --release\ No newline at end of filediff --git a/rust/cyclotron-janitor/src/config.rs b/rust/cyclotron-janitor/src/config.rsdeleted file mode 100644index 8957fc93afce..000000000000--- a/rust/cyclotron-janitor/src/config.rs+++ /dev/null@@ -1,98 +0,0 @@-use chrono::Duration;--use common_continuous_profiling::ContinuousProfilingConfig;-use cyclotron_core::PoolConfig;-use envconfig::Envconfig;-use uuid::Uuid;--#[derive(Envconfig)]-pub struct Config {- #[envconfig(nested = true)]- pub continuous_profiling: ContinuousProfilingConfig,-- #[envconfig(from = "BIND_HOST", default = "::")]- pub host: String,-- #[envconfig(from = "BIND_PORT", default = "3303")]- pub port: u16,-- #[envconfig(default = "postgres://posthog:posthog@localhost:5432/cyclotron")]- pub database_url: String,-- #[envconfig(default = "30")]- pub cleanup_interval_secs: u64,-- #[envconfig(default = "10")]- pub pg_max_connections: u32,-- #[envconfig(default = "1")]- pub pg_min_connections: u32,-- #[envconfig(default = "30")]- pub pg_acquire_timeout_seconds: u64,-- #[envconfig(default = "300")]- pub pg_max_lifetime_seconds: u64,-- #[envconfig(default = "60")]- pub pg_idle_timeout_seconds: u64,-- // Generally, this should be equivalent to a "shard id", as only one janitor should be running- // per shard- #[envconfig(default = "default_janitor_id")]- pub janitor_id: String,-- #[envconfig(default = "default")]- pub shard_id: String, // A fixed shard-id. When a janitor starts up, it will write this to the shard metadata, and workers may use it when reporting metrics-- #[envconfig(default = "10")]- pub janitor_max_touches: i16,-- #[envconfig(default = "60")]- pub janitor_stall_timeout_seconds: u16,-- #[envconfig(default = "false")]- pub should_compress_vm_state: bool, // Defaults to "false" (for now!)-}--#[allow(dead_code)]-fn default_worker_id() -> String {- Uuid::now_v7().to_string()-}--impl Config {- pub fn get_janitor_config(&self) -> JanitorConfig {- let pool_config = PoolConfig {- db_url: self.database_url.clone(),- max_connections: Some(self.pg_max_connections),- min_connections: Some(self.pg_min_connections),- acquire_timeout_seconds: Some(self.pg_acquire_timeout_seconds),- max_lifetime_seconds: Some(self.pg_max_lifetime_seconds),- idle_timeout_seconds: Some(self.pg_idle_timeout_seconds),- };-- let settings = JanitorSettings {- stall_timeout: Duration::seconds(self.janitor_stall_timeout_seconds as i64),- max_touches: self.janitor_max_touches,- id: self.janitor_id.clone(),- shard_id: self.shard_id.clone(),- };-- JanitorConfig {- pool: pool_config,- settings,- }- }-}--pub struct JanitorConfig {- pub pool: PoolConfig,- pub settings: JanitorSettings,-}--pub struct JanitorSettings {- pub stall_timeout: Duration,- pub max_touches: i16,- pub id: String,- pub shard_id: String,-}diff --git a/rust/cyclotron-janitor/src/janitor.rs b/rust/cyclotron-janitor/src/janitor.rsdeleted file mode 100644index 7fd222b579f4..000000000000--- a/rust/cyclotron-janitor/src/janitor.rs+++ /dev/null@@ -1,120 +0,0 @@-use cyclotron_core::{QueueError, SHARD_ID_KEY};-use tracing::{info, warn};--use crate::{- config::{JanitorConfig, JanitorSettings},- metrics_constants::*,-};--// The janitor reports it's own metrics, this is mostly for testing purposes-#[derive(Debug, Clone, Eq, PartialEq)]-pub struct CleanupResult {- pub completed: u64,- pub failed: u64,- pub canceled: u64,- pub poisoned: u64,- pub stalled: u64,-}--pub struct Janitor {- pub inner: cyclotron_core::Janitor,- pub settings: JanitorSettings,- pub metrics_labels: Vec<(String, String)>,-}--impl Janitor {- pub async fn new(config: JanitorConfig) -> Result<Self, QueueError> {- let settings = config.settings;- let inner = cyclotron_core::Janitor::new(config.pool).await?;-- let metrics_labels = vec![- ("janitor_id".to_string(), settings.id.clone()),- (SHARD_ID_KEY.to_string(), settings.shard_id.clone()),- ];-- Ok(Self {- inner,- settings,- metrics_labels,- })- }-- pub async fn run_once(&self) -> Result<CleanupResult, QueueError> {- info!("Running janitor loop");- let _loop_start = common_metrics::timing_guard(RUN_TIME, &self.metrics_labels);- common_metrics::inc(RUN_STARTS, &self.metrics_labels, 1);-- let aggregated_deletes = {- let _time = common_metrics::timing_guard(CLEANUP_TIME, &self.metrics_labels);- self.inner.delete_completed_and_failed_jobs().await?- };-- let mut completed_count = 0u64;- let mut failed_count = 0u64;- let mut canceled_count = 0u64;- for delete in &aggregated_deletes {- if delete.state == "completed" {- completed_count += delete.count as u64;- } else if delete.state == "failed" {- failed_count += delete.count as u64;- } else if delete.state == "canceled" {- canceled_count += delete.count as u64;- }- }- common_metrics::inc(COMPLETED_COUNT, &self.metrics_labels, completed_count);- common_metrics::inc(FAILED_COUNT, &self.metrics_labels, failed_count);- common_metrics::inc(CANCELED_COUNT, &self.metrics_labels, canceled_count);-- let poisoned = {- let _time = common_metrics::timing_guard(POISONED_TIME, &self.metrics_labels);- self.inner- .delete_poison_pills(self.settings.stall_timeout, self.settings.max_touches)- .await?- };- common_metrics::inc(POISONED_COUNT, &self.metrics_labels, poisoned);-- if poisoned > 0 {- warn!("Deleted {} poison pills", poisoned);- }-- let stalled = {- let _time = common_metrics::timing_guard(STALLED_TIME, &self.metrics_labels);- self.inner- .reset_stalled_jobs(self.settings.stall_timeout)- .await?- };- common_metrics::inc(STALLED_COUNT, &self.metrics_labels, stalled);-- if stalled > 0 {- warn!("Reset {} stalled jobs", stalled);- }-- let available = {- let _time = common_metrics::timing_guard(AVAILABLE_DEPTH_TIME, &self.metrics_labels);- self.inner.waiting_jobs().await?- };-- let mut available_labels = self.metrics_labels.clone();- for (count, queue_name) in available {- available_labels.push(("queue_name".to_string(), queue_name));- common_metrics::gauge(AVAILABLE_DEPTH, &available_labels, count as f64);- available_labels.pop();- }-- let dlq_depth = {- let _time = common_metrics::timing_guard(DLQ_DEPTH_TIME, &self.metrics_labels);- self.inner.count_dlq_depth().await?- };- common_metrics::gauge(DLQ_DEPTH, &self.metrics_labels, dlq_depth as f64);-- common_metrics::inc(RUN_ENDS, &self.metrics_labels, 1);- info!("Janitor loop complete");- Ok(CleanupResult {- completed: completed_count,- failed: failed_count,- canceled: canceled_count,- poisoned,- stalled,- })- }-}diff --git a/rust/cyclotron-janitor/src/lib.rs b/rust/cyclotron-janitor/src/lib.rsdeleted file mode 100644index 6952fea2ec3c..000000000000--- a/rust/cyclotron-janitor/src/lib.rs+++ /dev/null@@ -1,3 +0,0 @@-pub mod config;-pub mod janitor;-pub mod metrics_constants;diff --git a/rust/cyclotron-janitor/src/main.rs b/rust/cyclotron-janitor/src/main.rsdeleted file mode 100644index 1fe3c809b532..000000000000--- a/rust/cyclotron-janitor/src/main.rs+++ /dev/null@@ -1,113 +0,0 @@-use axum::{extract::State, routing::get, Router};-use common_metrics::setup_metrics_routes;-use cyclotron_janitor::{config::Config, janitor::Janitor};-use envconfig::Envconfig;-use eyre::Result;-use health::{HealthHandle, HealthRegistry};-use std::{future::ready, time::Duration};-use tracing::{error, info};--common_alloc::used!();--async fn cleanup_loop(janitor: Janitor, livenes: HealthHandle, interval_secs: u64) -> Result<()> {- let mut interval = tokio::time::interval(Duration::from_secs(interval_secs));-- loop {- interval.tick().await;-- if let Err(e) = janitor.run_once().await {- // don't bother reporting unhealthy - a few times around this loop will put us in a stalled state- error!("janitor failed cleanup with: {}", e);- } else {- livenes.report_healthy().await;- }- }-}--async fn listen(app: Router, bind: String) -> Result<()> {- let listener = tokio::net::TcpListener::bind(bind).await?;-- axum::serve(listener, app).await?;-- Ok(())-}--// For axums state stuff-#[derive(Clone)]-struct JanitorId(pub String);--pub fn app(liveness: HealthRegistry, janitor_id: String) -> Router {- Router::new()- .route("/", get(index))- .route("/_readiness", get(index))- .route("/_liveness", get(move || ready(liveness.get_status())))- .with_state(JanitorId(janitor_id))-}--async fn index(State(janitor_id): State<JanitorId>) -> String {- format!("cyclotron janitor {}", janitor_id.0)-}--#[tokio::main]-async fn main() {- let config = Config::init_from_env().expect("failed to load configuration from env");- tracing_subscriber::fmt::init();-- // Start continuous profiling if enabled (keep _agent alive for the duration of the program)- let _profiling_agent = match config.continuous_profiling.start_agent() {- Ok(agent) => agent,- Err(e) => {- error!("Failed to start continuous profiling agent: {e}");- None- }- };-- let liveness = HealthRegistry::new("liveness");-- let janitor_config = config.get_janitor_config();-- let janitor_id = janitor_config.settings.id.clone();- let bind = format!("{}:{}", config.host, config.port);-- info!(- "Starting janitor with ID {:?}, listening at {}",- janitor_id, bind- );-- let janitor = Janitor::new(janitor_config)- .await- .expect("failed to create janitor");-- let janitor_liveness = liveness- .register(- "janitor".to_string(),- Duration::from_secs(config.cleanup_interval_secs * 4),- )- .await;-- let janitor_loop = tokio::spawn(cleanup_loop(- janitor,- janitor_liveness,- config.cleanup_interval_secs,- ));-- let app = setup_metrics_routes(app(liveness, janitor_id));- let http_server = tokio::spawn(listen(app, bind));-- tokio::select! {- res = janitor_loop => {- error!("janitor loop exited");- if let Err(e) = res {- error!("janitor failed with: {}", e)- }- }- res = http_server => {- error!("http server exited");- if let Err(e) = res {- error!("server failed with: {}", e)- }- }- }-- info!("exiting");-}diff --git a/rust/cyclotron-janitor/src/metrics_constants.rs b/rust/cyclotron-janitor/src/metrics_constants.rsdeleted file mode 100644index 695600a95cdb..000000000000--- a/rust/cyclotron-janitor/src/metrics_constants.rs+++ /dev/null@@ -1,20 +0,0 @@-pub const RUN_STARTS: &str = "cyclotron_janitor_run_starts";-pub const RUN_TIME: &str = "cyclotron_janitor_total_run_ms";-pub const RUN_ENDS: &str = "cyclotron_janitor_run_ends";--pub const COMPLETED_COUNT: &str = "cyclotron_janitor_completed_jobs";-pub const FAILED_COUNT: &str = "cyclotron_janitor_failed_jobs";-pub const CANCELED_COUNT: &str = "cyclotron_janitor_canceled_jobs";-pub const CLEANUP_TIME: &str = "cyclotron_janitor_completed_failed_jobs_cleanup_ms";--pub const POISONED_COUNT: &str = "cyclotron_janitor_poison_pills";-pub const POISONED_TIME: &str = "cyclotron_janitor_poison_pills_cleanup_ms";--pub const STALLED_COUNT: &str = "cyclotron_janitor_stalled_jobs_reset";-pub const STALLED_TIME: &str = "cyclotron_janitor_stalled_jobs_reset_ms";--// The janitor should report some basic shard-level metrics-pub const AVAILABLE_DEPTH: &str = "cyclotron_available_jobs";-pub const AVAILABLE_DEPTH_TIME: &str = "cyclotron_available_jobs_ms";-pub const DLQ_DEPTH: &str = "cyclotron_dead_letter_queue_depth";-pub const DLQ_DEPTH_TIME: &str = "cyclotron_dead_letter_queue_depth_ms";diff --git a/rust/cyclotron-janitor/tests/janitor.rs b/rust/cyclotron-janitor/tests/janitor.rsdeleted file mode 100644index c2a9df8f4124..000000000000--- a/rust/cyclotron-janitor/tests/janitor.rs+++ /dev/null@@ -1,272 +0,0 @@-use chrono::{Duration, Utc};-use cyclotron_core::{JobInit, JobState, QueueManager, Worker, WorkerConfig};-use cyclotron_janitor::{config::JanitorSettings, janitor::Janitor};-use sqlx::PgPool;-use uuid::Uuid;--#[sqlx::test(migrations = "../cyclotron-core/migrations")]-async fn janitor_test(db: PgPool) {- // kinda gross, but the from_pool methods are better suited to test usage- let default_worker_cfg = WorkerConfig::default();- let should_compress_vm_state = default_worker_cfg.should_compress_vm_state();-- let worker = Worker::from_pool(db.clone(), default_worker_cfg);- let manager = QueueManager::from_pool(db.clone(), should_compress_vm_state, false);-- // Purposefully MUCH smaller than would be used in production, so- // we can simulate stalled or poison jobs quickly- let stall_timeout = Duration::milliseconds(500);- let max_touches = 3;-- // Workers by default drop any heartbeats for the first 5 seconds, or between- // the last heartbeat and the next 5 seconds. We need to override that window- // to be smaller here, to test heartbeat behaviour- let mut worker = worker;- worker.heartbeat_window = stall_timeout / 2;- worker.max_buffered = 0; // No buffering for testing, flush immediately- let worker = worker;-- let settings = JanitorSettings {- stall_timeout,- max_touches,- id: "test_janitor".to_string(),- shard_id: "test_shard".to_string(),- };- let janitor = Janitor {- inner: cyclotron_core::Janitor::from_pool(db.clone()),- settings,- metrics_labels: vec![],- };-- let now = Utc::now() - Duration::seconds(10);- let queue_name = "default".to_string();-- let uuid = Uuid::now_v7();- let job_init = JobInit {- id: None,- team_id: 1,- queue_name: queue_name.clone(),- priority: 0,- scheduled: now,- function_id: Some(uuid),- parent_run_id: None,- vm_state: None,- parameters: None,- blob: None,- metadata: None,- };-- // if we mark a job as completed, the janitor will clean it up- manager.create_job(job_init.clone()).await.unwrap();- let job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();-- worker.set_state(job.id, JobState::Completed).unwrap();- worker.release_job(job.id, None).await.unwrap();-- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 1);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-- // if we mark a job as canceled, the janitor will clean it up- manager.create_job(job_init.clone()).await.unwrap();- let job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();-- worker.set_state(job.id, JobState::Canceled).unwrap();- worker.release_job(job.id, None).await.unwrap();-- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 1);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-- // if we mark a job as failed, the janitor will clean it up- manager.create_job(job_init.clone()).await.unwrap();- let job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();-- worker.set_state(job.id, JobState::Failed).unwrap();- worker.release_job(job.id, None).await.unwrap();-- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 1);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-- // if we pick up a job, and then hold it for longer than- // the stall timeout, the janitor will reset it. After this, the worker- // cannot flush updates to the job, and must re-dequeue it.-- manager.create_job(job_init.clone()).await.unwrap();- let job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();-- // First, cleanup won't do anything- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-- // Then we stall on the job- tokio::time::sleep(stall_timeout.to_std().unwrap() * 2).await;-- // Now, cleanup will reset the job- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 1);-- // Now, the worker can't flush the job- worker.set_state(job.id, JobState::Completed).unwrap();- let result = worker.release_job(job.id, None).await;- assert!(result.is_err());-- // But if we re-dequeue the job, we can flush it- let job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();- worker.set_state(job.id, JobState::Completed).unwrap();- worker.release_job(job.id, None).await.unwrap();-- janitor.run_once().await.unwrap(); // Clean up the completed job to reset for the next test-- // if a worker holds a job for longer than the stall- // time, but calls heartbeat, the job will not be reset-- manager.create_job(job_init.clone()).await.unwrap();- let job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();-- let start = tokio::time::Instant::now();- loop {- worker.heartbeat(job.id).await.unwrap();- tokio::time::sleep(Duration::milliseconds(25).to_std().unwrap()).await;- if start.elapsed() > stall_timeout.to_std().unwrap() * 3 {- break;- }- }-- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-- // The worker can still flush the job- worker.set_state(job.id, JobState::Completed).unwrap();- worker.release_job(job.id, None).await.unwrap();-- // and now cleanup will work- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 1);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-- // if a job stalls more than max_touches- // it will be marked as poisoned and deleted-- manager.create_job(job_init.clone()).await.unwrap();- let mut job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();-- for _ in 0..max_touches {- tokio::time::sleep(stall_timeout.to_std().unwrap() * 2).await;- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 1);-- // assert we can't update the job (flush and heartbeat fail)- worker.set_state(job.id, JobState::Completed).unwrap();- let result = worker.heartbeat(job.id).await;- assert!(result.is_err());- let result = worker.release_job(job.id, None).await;- assert!(result.is_err());-- // re-dequeue the job- job = worker- .dequeue_jobs(&queue_name, 1)- .await- .unwrap()- .pop()- .unwrap();- }- // At this point, the "janitor touches" on the job is 3 (it's been stalled and reset 3 times), so one more cleanup loop will delete it-- // Now stall one more time, and on cleanup, we should see the job was considered poison and deleted- tokio::time::sleep(stall_timeout.to_std().unwrap() * 2).await;- let result: cyclotron_janitor::janitor::CleanupResult = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 0);- assert_eq!(result.failed, 0);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 1);- assert_eq!(result.stalled, 0);-- // The worker can't flush the job- worker.set_state(job.id, JobState::Completed).unwrap();- let result = worker.release_job(job.id, None).await;- assert!(result.is_err());-- // the janitor can operate on multiple jobs at once- manager.create_job(job_init.clone()).await.unwrap();- manager.create_job(job_init.clone()).await.unwrap();-- let jobs = worker.dequeue_jobs(&queue_name, 2).await.unwrap();-- worker.set_state(jobs[0].id, JobState::Completed).unwrap();- worker.set_state(jobs[1].id, JobState::Failed).unwrap();-- worker.release_job(jobs[0].id, None).await.unwrap();- worker.release_job(jobs[1].id, None).await.unwrap();-- let result = janitor.run_once().await.unwrap();- assert_eq!(result.completed, 1);- assert_eq!(result.failed, 1);- assert_eq!(result.canceled, 0);- assert_eq!(result.poisoned, 0);- assert_eq!(result.stalled, 0);-}diff --git a/rust/cyclotron-node/.gitignore b/rust/cyclotron-node/.gitignoredeleted file mode 100644index 01f3230c629f..000000000000--- a/rust/cyclotron-node/.gitignore+++ /dev/null@@ -1,7 +0,0 @@-target-index.node-**/node_modules-**/.DS_Store-npm-debug.log*cargo.log-cross.log-dist/diff --git a/rust/cyclotron-node/Cargo.toml b/rust/cyclotron-node/Cargo.tomldeleted file mode 100644index a95f4fb4e509..000000000000--- a/rust/cyclotron-node/Cargo.toml+++ /dev/null@@ -1,23 +0,0 @@-[package]-name = "cyclotron-node"-version = "0.1.0"-edition = "2021"-exclude = ["index.node"]-publish = false--[lints]-workspace = true---[lib]-crate-type = ["cdylib"]--[dependencies]-cyclotron-core = { path = "../cyclotron-core" }-neon = { workspace = true }-once_cell = { workspace = true }-tokio = { workspace = true }-serde_json = { workspace = true }-serde = { workspace = true }-uuid = { workspace = true }-chrono = { workspace = true }diff --git a/rust/cyclotron-node/examples/basic.js b/rust/cyclotron-node/examples/basic.jsdeleted file mode 100644index a625dd51ca85..000000000000--- a/rust/cyclotron-node/examples/basic.js+++ /dev/null@@ -1,146 +0,0 @@-const assert = require('assert')-const cyclotron = require('../.')-const crypto = require('crypto')--// Set of available job states-const JOB_STATES = Object.freeze({- AVAILABLE: 'available',- RUNNING: 'running',- FAILED: 'failed',- COMPLETED: 'completed',-})--const AVAILABLE_WORKERS = Object.freeze({- FETCH: 'fetch',- HOG: 'hog',-})--async function main() {- let poolConfig = {- db_url: 'postgresql://posthog:posthog@localhost:5432/cyclotron',- }-- let managerConfig = {- shards: [poolConfig],- }-- // Most processes will only need to do one of these, but we can do both here for demonstration purposes- await cyclotron.initWorker(JSON.stringify(poolConfig))- await cyclotron.initManager(JSON.stringify(managerConfig))-- // Maybe inits won't throw on re-calling, and are also short-circuiting to be almost free, so safe to call frequently- // (although I still wouldn't call them in a loop)- await cyclotron.maybeInitWorker(JSON.stringify(poolConfig))- await cyclotron.maybeInitManager(JSON.stringify(managerConfig))-- let five_mintes_ago = new Date(new Date().getTime() - 5 * 60000).toISOString()- let queue_name = 'default'-- let job_1 = {- team_id: 1,- queue_name,- priority: 0,- scheduled: five_mintes_ago,- function_id: crypto.randomUUID(), // Is nullable- vm_state: null,- parameters: null,- blob: null,- metadata: null,- }-- let job_2 = {- team_id: 1,- queue_name,- priority: 1,- scheduled: five_mintes_ago,- function_id: crypto.randomUUID(), // Is nullable- vm_state: null,- parameters: null,- blob: null,- metadata: null,- }-- await cyclotron.createJob(JSON.stringify(job_1))- await cyclotron.createJob(JSON.stringify(job_2))-- // Jobs (as well as any other 'complex' data shape) are serialized across the API boundary,- // because that's (according to the neon maintainers) /actually faster/ than doing a bunch- // of cross-runtime pointer chasing.- let jobs = JSON.parse(await cyclotron.dequeueJobs(queue_name, 2))- assert(jobs.length === 2)- assert(jobs[0].function_id === job_1.function_id)- assert(jobs[1].function_id === job_2.function_id)-- job_1 = jobs[0]- job_2 = jobs[1]-- // All of these throw if the job hasn't been dequeued by the worker created when init_worker was called,- // or if there's some serde error - generally, interacting with the cyclotron should involve try/catch in- // some far outer catch. We can iterate on this API to make it more ergonomic with time, but- // my js/ts is... rusty (co-pilot wrote this joke)- cyclotron.setState(job_1.id, JOB_STATES.AVAILABLE)- cyclotron.setState(job_2.id, JOB_STATES.AVAILABLE)-- cyclotron.setQueue(job_1.id, 'non-default')- cyclotron.setQueue(job_2.id, 'non-default')-- // Priority is lowest-first, so this means we can assert that job_2 will be returned first on subsequent dequeue_jobs- cyclotron.setPriority(job_1.id, 2)- cyclotron.setPriority(job_2.id, 1)-- let ten_minutes_ago = new Date(new Date().getTime() - 10 * 60000).toISOString()- cyclotron.setScheduledAt(job_1.id, ten_minutes_ago)- cyclotron.setScheduledAt(job_2.id, ten_minutes_ago)-- cyclotron.setVmState(job_1.id, JSON.stringify({ state: 'running' }))- cyclotron.setVmState(job_2.id, JSON.stringify({ state: 'running' }))-- cyclotron.setParameters(job_1.id, JSON.stringify({ parameters: 'running' }))- cyclotron.setParameters(job_2.id, JSON.stringify({ parameters: 'running' }))-- cyclotron.setMetadata(job_1.id, JSON.stringify({ metadata: 'running' }))- cyclotron.setMetadata(job_2.id, JSON.stringify({ metadata: 'running' }))-- // Flush the updates queued up above back to the queue. Subsequent calls to flush- // will throw if a job isn't re-acquired. Flushes will fail if a job state update- // isn't included (workers should not purposefully leave jobs in a running state)- await cyclotron.flushJob(job_1.id)- await cyclotron.flushJob(job_2.id)-- jobs = JSON.parse(await cyclotron.dequeueWithVmState('non-default', 2))-- assert(jobs[0].id == job_2.id)- assert(jobs[1].id == job_1.id)-- assert(jobs[0].function_id === job_2.function_id)- assert(jobs[1].function_id === job_1.function_id)-- assert(jobs[0].team_id === job_2.team_id)- assert(jobs[1].team_id === job_1.team_id)-- assert(jobs[0].queue_name === 'non-default')- assert(jobs[1].queue_name === 'non-default')-- assert(jobs[0].priority === 1)- assert(jobs[1].priority === 2)-- assert(jobs[0].scheduled === ten_minutes_ago)- assert(jobs[1].scheduled === ten_minutes_ago)-- assert(jobs[0].vm_state === JSON.stringify({ state: 'running' }))- assert(jobs[1].vm_state === JSON.stringify({ state: 'running' }))- assert(jobs[0].parameters === JSON.stringify({ parameters: 'running' }))- assert(jobs[1].parameters === JSON.stringify({ parameters: 'running' }))- assert(jobs[0].metadata === JSON.stringify({ metadata: 'running' }))- assert(jobs[1].metadata === JSON.stringify({ metadata: 'running' }))-- // Now we'll mark these jobs as completed- cyclotron.setState(job_1.id, JOB_STATES.COMPLETED)- cyclotron.setState(job_2.id, JOB_STATES.COMPLETED)-- // And flush them back to the queue- await cyclotron.flushJob(job_1.id)- await cyclotron.flushJob(job_2.id)-}--main()diff --git a/rust/cyclotron-node/package.json b/rust/cyclotron-node/package.jsondeleted file mode 100644index 1d513d8bb215..000000000000--- a/rust/cyclotron-node/package.json+++ /dev/null@@ -1,33 +0,0 @@-{- "name": "@posthog/cyclotron",- "version": "0.1.12",- "description": "Node bindings for cyclotron",- "main": "dist/index.js",- "types": "dist/index.d.ts",- "scripts": {- "test": "cargo test",- "build": "pnpm run build:cargo --release && pnpm run build:move-lib && pnpm run build:typescript",- "build:dev": "pnpm run build:cargo && pnpm run build:move-lib:dev && pnpm run build:typescript",- "build:move-lib": "TARGET_DIR=${CARGO_TARGET_DIR:-../target} && cp \"$TARGET_DIR/release/libcyclotron_node.dylib\" index.node 2>/dev/null || cp \"$TARGET_DIR/release/libcyclotron_node.so\" index.node || (echo \"No valid library file found in $TARGET_DIR/release/\" && exit 1)",- "build:move-lib:dev": "TARGET_DIR=${CARGO_TARGET_DIR:-../target} && cp \"$TARGET_DIR/debug/libcyclotron_node.dylib\" index.node 2>/dev/null || cp \"$TARGET_DIR/debug/libcyclotron_node.so\" index.node || (echo \"No valid library file found in $TARGET_DIR/debug/\" && exit 1)",- "build:cargo": "cargo build --message-format=json > cargo.log",- "build:cargo:debug": "pnpm run build:cargo",- "build:cross": "cross build --message-format=json > cross.log",- "build:typescript": "tsc",- "typecheck": "tsc --noEmit",- "typecheck:tsgo": "tsgo --noEmit",- "clean": "rm -rf index.node",- "package": "NODE_ENV=development pnpm --filter=@posthog/cyclotron run build"- },- "author": "",- "license": "MIT",- "devDependencies": {- "@types/node": "^22.13.14",- "typescript": "catalog:",- "undici-types": "^7.3.0"- },- "files": [- "dist",- "index.node"- ]-}diff --git a/rust/cyclotron-node/pnpm-lock.yaml b/rust/cyclotron-node/pnpm-lock.yamldeleted file mode 100644index 5b02038833b3..000000000000--- a/rust/cyclotron-node/pnpm-lock.yaml+++ /dev/null@@ -1,32 +0,0 @@-lockfileVersion: '6.1'--settings:- autoInstallPeers: true- excludeLinksFromLockfile: false--devDependencies:- '@types/node':- specifier: ^22.13.14- version: 22.13.14- typescript:- specifier: ^4.7.4- version: 4.7.4- undici-types:- specifier: ^7.3.0- version: 7.3.0--packages:-- /@types/[email protected]:- resolution: {integrity: sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==}- dev: true-- resolution: {integrity: sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==}- engines: {node: '>=4.2.0'}- hasBin: true- dev: true-- resolution: {integrity: sha512-z2pHpkN2BEJl3QlQo0GtfGCyuhuBbWX60vzGwyn7ex/seM2UkvyGEfEV0Qb9pXc5StNfcJpsstgaf2YTEJa63Q==}- dev: truediff --git a/rust/cyclotron-node/src/helpers.ts b/rust/cyclotron-node/src/helpers.tsdeleted file mode 100644index ba1ace2a3716..000000000000--- a/rust/cyclotron-node/src/helpers.ts+++ /dev/null@@ -1,30 +0,0 @@-import { CyclotronInternalPoolConfig, CyclotronPoolConfig } from './types'--export function convertToInternalPoolConfig(poolConfig: CyclotronPoolConfig): CyclotronInternalPoolConfig {- return {- db_url: poolConfig.dbUrl,- max_connections: poolConfig.maxConnections,- min_connections: poolConfig.minConnections,- acquire_timeout_seconds: poolConfig.acquireTimeoutSeconds,- max_lifetime_seconds: poolConfig.maxLifetimeSeconds,- idle_timeout_seconds: poolConfig.idleTimeoutSeconds,- }-}--export function serializeObject(name: string, obj: Record<string, any> | null): string | null {- if (obj === null) {- return null- } else if (typeof obj === 'object' && obj !== null) {- return JSON.stringify(obj)- }- throw new Error(`${name} must be either an object or null`)-}--export function deserializeObject(name: string, str: any): Record<string, any> | null {- if (str === null) {- return null- } else if (typeof str === 'string') {- return JSON.parse(str)- }- throw new Error(`${name} must be either a string or null`)-}diff --git a/rust/cyclotron-node/src/index.ts b/rust/cyclotron-node/src/index.tsdeleted file mode 100644index e905c5f6cd4a..000000000000--- a/rust/cyclotron-node/src/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export * from './manager'-export * from './types'-export * from './worker'diff --git a/rust/cyclotron-node/src/lib.rs b/rust/cyclotron-node/src/lib.rsdeleted file mode 100644index eb239d3006b3..000000000000--- a/rust/cyclotron-node/src/lib.rs+++ /dev/null@@ -1,766 +0,0 @@-use chrono::{DateTime, Utc};--use cyclotron_core::{- Job, JobInit, JobState, ManagerConfig, PoolConfig, QueueManager, Worker, WorkerConfig,-};-use neon::{- handle::Handle,- object::Object,- prelude::{Context, FunctionContext, ModuleContext, TaskContext},- result::{JsResult, NeonResult},- types::{- buffer::TypedArray, JsArray, JsArrayBuffer, JsNull, JsNumber, JsObject, JsPromise,- JsString, JsUint32Array, JsUint8Array, JsUndefined, JsValue,- },-};-use once_cell::sync::OnceCell;-use serde::de::DeserializeOwned;-use serde::Deserialize;-use serde_json::Value;-use tokio::runtime::Runtime;-use uuid::Uuid;--static WORKER: OnceCell<Worker> = OnceCell::new();-static MANAGER: OnceCell<QueueManager> = OnceCell::new();-static RUNTIME: OnceCell<Runtime> = OnceCell::new();--fn runtime<'a, C: Context<'a>>(cx: &mut C) -> NeonResult<&'static Runtime> {- RUNTIME- .get_or_try_init(Runtime::new)- .or_else(|e| cx.throw_error(format!("failed to create tokio runtime: {e}")))-}--// The general interface for calling our functions takes a JSON serialized stirng,-// because neon has no nice serde support for function arguments (and generally.-// rippping objects from the v8 runtime piece by piece is slower than just passing-// a since chunk of bytes). These are convenience functions for converting between-pub fn from_json_string<'a, T, C>(cx: &mut C, object: Handle<JsString>) -> NeonResult<T>-where- T: DeserializeOwned,- C: Context<'a>,-{- let value: T =- serde_json::from_str(&object.value(cx)).or_else(|e| cx.throw_error(format!("{e}")))?;- Ok(value)-}--pub fn to_json_string<'a, T, C>(cx: &mut C, value: T) -> NeonResult<String>-where- T: serde::Serialize,- C: Context<'a>,-{- let value = serde_json::to_string(&value)- .or_else(|e| cx.throw_error(format!("failed to serialize value: {e}")))?;- Ok(value)-}--fn hello(mut cx: FunctionContext) -> JsResult<JsString> {- let arg1 = cx.argument::<JsString>(0)?;- let value: Value = from_json_string(&mut cx, arg1)?;- let string = to_json_string(&mut cx, value)?;- Ok(cx.string(string))-}--fn init_worker_impl(mut cx: FunctionContext, throw_on_reinit: bool) -> JsResult<JsPromise> {- let arg1 = cx.argument::<JsString>(0)?;-- let config: PoolConfig = from_json_string(&mut cx, arg1)?;-- let worker_config: WorkerConfig = if let Ok(arg2) = cx.argument::<JsString>(1) {- from_json_string(&mut cx, arg2)?- } else {- Default::default()- };-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let worker = Worker::new(config, worker_config).await;- deferred.settle_with(&channel, move |mut cx| {- if WORKER.get().is_some() && !throw_on_reinit {- return Ok(cx.null()); // Short circuit to make using maybe_init a no-op- }- let worker = worker.or_else(|e| cx.throw_error(format!("{e}")))?;- let already_set = WORKER.set(worker).is_err();- if already_set && throw_on_reinit {- cx.throw_error("worker already initialized")- } else {- Ok(cx.null())- }- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn init_manager_impl(mut cx: FunctionContext, throw_on_reinit: bool) -> JsResult<JsPromise> {- let arg1 = cx.argument::<JsString>(0)?;- let config: ManagerConfig = from_json_string(&mut cx, arg1)?;-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let manager = QueueManager::new(config).await;- deferred.settle_with(&channel, move |mut cx| {- if MANAGER.get().is_some() && !throw_on_reinit {- return Ok(cx.null()); // Short circuit to make using maybe_init a no-op- }- let manager = manager.or_else(|e| cx.throw_error(format!("{e}")))?;- let already_set = MANAGER.set(manager).is_err();- if already_set && throw_on_reinit {- cx.throw_error("manager already initialized")- } else {- Ok(cx.null())- }- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn init_worker(cx: FunctionContext) -> JsResult<JsPromise> {- init_worker_impl(cx, true)-}--fn init_manager(cx: FunctionContext) -> JsResult<JsPromise> {- init_manager_impl(cx, true)-}--fn maybe_init_worker(cx: FunctionContext) -> JsResult<JsPromise> {- init_worker_impl(cx, false)-}--fn maybe_init_manager(cx: FunctionContext) -> JsResult<JsPromise> {- init_manager_impl(cx, false)-}--// throw_error has a type signature that makes it inconvenient to use in closures, because-// it requires that you specify the V of the NeonResult<V> returned, even though it's always-// an error. This is a sane thing for it to do, but it's inconvenient for us, because we-// frequently settle promises early, before we have a V to use for type inference. This little-// wrapper makes that easier, by specifying the V as JsNull-fn throw_null_err<'c, C>(cx: &mut C, msg: &str) -> NeonResult<Handle<'c, JsNull>>-where- C: Context<'c>,-{- cx.throw_error(msg)-}--#[derive(Debug, Deserialize)]-pub struct JsJob {- pub id: Option<Uuid>,- pub team_id: i32,- pub queue_name: String,- pub priority: i16,- pub scheduled: DateTime<Utc>,- pub function_id: Option<Uuid>,- pub parent_run_id: Option<String>,- pub vm_state: Option<String>,- pub parameters: Option<String>,- pub metadata: Option<String>,-}--fn create_job(mut cx: FunctionContext) -> JsResult<JsPromise> {- let arg1: Handle<JsString> = cx.argument::<JsString>(0)?;-- let blob = cx.argument::<JsValue>(1)?;- let blob = if blob.is_a::<JsNull, _>(&mut cx) || blob.is_a::<JsUndefined, _>(&mut cx) {- None- } else {- Some(- blob.downcast_or_throw::<JsUint8Array, _>(&mut cx)?- .as_slice(&cx)- .to_vec(),- )- };-- let js_job: JsJob = from_json_string(&mut cx, arg1)?;-- let job = js_job.to_job_init(blob);-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let manager = match MANAGER.get() {- Some(manager) => manager,- None => {- deferred.settle_with(&channel, |mut cx| {- throw_null_err(&mut cx, "manager not initialized")- });- return;- }- };- let res = manager.create_job(job).await;- deferred.settle_with(&channel, move |mut cx| {- let id = res.or_else(|e| cx.throw_error(format!("{e}")))?;- Ok(cx.string(id.to_string()))- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn bulk_create_jobs(mut cx: FunctionContext) -> JsResult<JsPromise> {- let jobs = cx.argument::<JsString>(0)?;- let jobs: Vec<JsJob> = from_json_string(&mut cx, jobs)?;-- let blobs = cx.argument::<JsValue>(1)?;- let blob_lengths = cx.argument::<JsValue>(2)?;-- let blobs = blobs- .downcast_or_throw::<JsUint8Array, _>(&mut cx)?- .as_slice(&cx)- .to_vec();-- let blob_lengths: Vec<usize> = blob_lengths- .downcast_or_throw::<JsUint32Array, _>(&mut cx)?- .as_slice(&cx)- .iter()- .map(|&v| v as usize)- .collect();-- if jobs.len() != blob_lengths.len() {- return cx.throw_error("jobs and blob_lengths must have the same length");- }-- if blobs.len() != blob_lengths.iter().sum::<usize>() {- return cx.throw_error("blob_lengths must sum to the length of blobs");- }-- let mut blob_offset: usize = 0;- let blobs: Vec<Option<Vec<u8>>> = blob_lengths- .iter()- .map(|&len| {- if len == 0 {- return None;- }- let blob = blobs[blob_offset..blob_offset + len].to_vec();- blob_offset += len;- Some(blob)- })- .collect();-- let jobs: Vec<JobInit> = jobs- .into_iter()- .zip(blobs)- .map(|(job, blob)| job.to_job_init(blob))- .collect();-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let manager = match MANAGER.get() {- Some(manager) => manager,- None => {- deferred.settle_with(&channel, |mut cx| {- throw_null_err(&mut cx, "manager not initialized")- });- return;- }- };-- let res = manager.bulk_create_jobs(jobs).await;- deferred.settle_with(&channel, move |mut cx| {- let ids = res.or_else(|e| cx.throw_error(format!("{e}")))?;- let returned = JsArray::new(&mut cx, ids.len());- for (i, id) in ids.iter().enumerate() {- let id = cx.string(id.to_string());- returned.set(&mut cx, i as u32, id)?;- }- Ok(returned)- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn dequeue_jobs(mut cx: FunctionContext) -> JsResult<JsPromise> {- let queue_name = cx.argument::<JsString>(0)?.value(&mut cx);-- let limit = cx.argument::<JsNumber>(1)?.value(&mut cx) as usize; // TODO - I don't love this cast-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let worker = match WORKER.get() {- Some(worker) => worker,- None => {- deferred.settle_with(&channel, |mut cx| {- throw_null_err(&mut cx, "worker not initialized")- });- return;- }- };- let jobs = worker.dequeue_jobs(&queue_name, limit).await;- deferred.settle_with(&channel, move |mut cx| {- let jobs = jobs.or_else(|e| cx.throw_error(format!("{e}")))?;- let jobs = jobs_to_js_array(&mut cx, jobs)?;- Ok(jobs)- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn dequeue_with_vm_state(mut cx: FunctionContext) -> JsResult<JsPromise> {- let queue_name = cx.argument::<JsString>(0)?.value(&mut cx);-- let limit = cx.argument::<JsNumber>(1)?.value(&mut cx) as usize; // TODO - I don't love this cast-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let worker = match WORKER.get() {- Some(worker) => worker,- None => {- deferred.settle_with(&channel, |mut cx| {- throw_null_err(&mut cx, "worker not initialized")- });- return;- }- };- let jobs = worker.dequeue_with_vm_state(&queue_name, limit).await;- deferred.settle_with(&channel, move |mut cx| {- let jobs = jobs.or_else(|e| cx.throw_error(format!("{e}")))?;- let jobs = jobs_to_js_array(&mut cx, jobs)?;- Ok(jobs)- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn release_job(mut cx: FunctionContext) -> JsResult<JsPromise> {- let arg1 = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg1- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg1}")))?;-- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let worker = match WORKER.get() {- Some(worker) => worker,- None => {- deferred.settle_with(&channel, |mut cx| {- throw_null_err(&mut cx, "worker not initialized")- });- return;- }- };- // We await the handle here because this translates waiting on the join handle all the way to- // a Js Promise.await.- let res = worker.release_job(job_id, None).await;- deferred.settle_with(&channel, move |mut cx| {- res.or_else(|e| cx.throw_error(format!("{e}")))?;- Ok(cx.null())- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn force_flush(mut cx: FunctionContext) -> JsResult<JsPromise> {- let (deferred, promise) = cx.promise();- let channel = cx.channel();- let runtime = runtime(&mut cx)?;-- let fut = async move {- let worker = match WORKER.get() {- Some(worker) => worker,- None => {- deferred.settle_with(&channel, |mut cx| {- throw_null_err(&mut cx, "worker not initialized")- });- return;- }- };- let res = worker.force_flush().await;- deferred.settle_with(&channel, |mut cx| {- res.or_else(|e| cx.throw_error(format!("{e}")))?;- Ok(cx.null())- });- };-- runtime.spawn(fut);-- Ok(promise)-}--fn set_state(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- let arg = cx.argument::<JsString>(1)?.value(&mut cx);- let state: JobState = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job state: {arg}")))?;-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_state(job_id, state)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_queue(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- let queue = cx.argument::<JsString>(1)?.value(&mut cx);-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_queue(job_id, &queue)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_priority(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- let arg = cx.argument::<JsNumber>(1)?.value(&mut cx);- let priority = arg as i16; // TODO - I /really/ don't love this cast-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_priority(job_id, priority)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_scheduled_at(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- let arg = cx.argument::<JsString>(1)?.value(&mut cx);- let scheduled: DateTime<Utc> = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid scheduled at: {arg}")))?;-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_scheduled_at(job_id, scheduled)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_vm_state(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- // Tricky - we have to support passing nulls here, because that's how you clear vm state.- let vm_state = cx.argument::<JsValue>(1)?;- let vm_state =- if vm_state.is_a::<JsNull, _>(&mut cx) || vm_state.is_a::<JsUndefined, _>(&mut cx) {- None- } else {- Some(- vm_state- .downcast_or_throw::<JsString, _>(&mut cx)?- .value(&mut cx)- .into_bytes(),- )- };-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_vm_state(job_id, vm_state)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_metadata(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- // Tricky - we have to support passing nulls here, because that's how you clear metadata.- let metadata = cx.argument::<JsValue>(1)?;- let metadata =- if metadata.is_a::<JsNull, _>(&mut cx) || metadata.is_a::<JsUndefined, _>(&mut cx) {- None- } else {- Some(- metadata- .downcast_or_throw::<JsString, _>(&mut cx)?- .value(&mut cx)- .into_bytes(),- )- };-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_metadata(job_id, metadata)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_parameters(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- // Tricky - we have to support passing nulls here, because that's how you clear parameters.- let parameters = cx.argument::<JsValue>(1)?;- let parameters =- if parameters.is_a::<JsNull, _>(&mut cx) || parameters.is_a::<JsUndefined, _>(&mut cx) {- None- } else {- Some(- parameters- .downcast_or_throw::<JsString, _>(&mut cx)?- .value(&mut cx)- .into_bytes(),- )- };-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_parameters(job_id, parameters)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn set_blob(mut cx: FunctionContext) -> JsResult<JsNull> {- let arg = cx.argument::<JsString>(0)?.value(&mut cx);- let job_id: Uuid = arg- .parse()- .or_else(|_| cx.throw_error(format!("invalid job id: {arg}")))?;-- // Tricky - we have to support passing nulls here, because that's how you clear the blob.- let blob = cx.argument::<JsValue>(1)?;- let blob: Option<Vec<u8>> =- if blob.is_a::<JsNull, _>(&mut cx) || blob.is_a::<JsUndefined, _>(&mut cx) {- None- } else {- Some(- blob.downcast_or_throw::<JsUint8Array, _>(&mut cx)?- .as_slice(&cx)- .to_vec(),- )- };-- WORKER- .get()- .map_or_else(|| cx.throw_error("worker not initialized"), Ok)?- .set_blob(job_id, blob)- .or_else(|e| cx.throw_error(format!("{e}")))?;-- Ok(cx.null())-}--fn jobs_to_js_array<'a>(cx: &mut TaskContext<'a>, jobs: Vec<Job>) -> JsResult<'a, JsArray> {- let js_array = JsArray::new(cx, jobs.len());-- for (i, job) in jobs.into_iter().enumerate() {- let js_obj = JsObject::new(cx);- let null = cx.null();-- let id_string = job.id.to_string();- let js_id = cx.string(id_string);- js_obj.set(cx, "id", js_id)?;-- let team_id = cx.number(job.team_id as f64);- js_obj.set(cx, "teamId", team_id)?;-- if let Some(function_id) = job.function_id {- let function_id_string = function_id.to_string();- let js_function_id = cx.string(function_id_string);- js_obj.set(cx, "functionId", js_function_id)?;- } else {- js_obj.set(cx, "functionId", null)?;- }-- let js_created = cx- .date(job.created.timestamp_millis() as f64)- .expect("failed to create date");- js_obj.set(cx, "created", js_created)?;-- if let Some(lock_id) = job.lock_id {- let lock_id_string = lock_id.to_string();- let js_lock_id = cx.string(lock_id_string);- js_obj.set(cx, "lockId", js_lock_id)?;- } else {- js_obj.set(cx, "lockId", null)?;- }-- if let Some(last_heartbeat) = job.last_heartbeat {- let js_last_heartbeat = cx.string(last_heartbeat.to_rfc3339());- js_obj.set(cx, "lastHeartbeat", js_last_heartbeat)?;- } else {- js_obj.set(cx, "lastHeartbeat", null)?;- }-- let janitor_touch_count = cx.number(job.janitor_touch_count as f64);- js_obj.set(cx, "janitorTouchCount", janitor_touch_count)?;- let transition_count = cx.number(job.transition_count as f64);- js_obj.set(cx, "transitionCount", transition_count)?;-- let js_last_transition = cx.string(job.last_transition.to_rfc3339());- js_obj.set(cx, "lastTransition", js_last_transition)?;-- let js_queue_name = cx.string(&job.queue_name);- js_obj.set(cx, "queueName", js_queue_name)?;-- let js_state = cx.string(format!("{:?}", job.state));- js_obj.set(cx, "state", js_state)?;-- let priority = cx.number(job.priority as f64);- js_obj.set(cx, "priority", priority)?;-- let js_scheduled = cx.string(job.scheduled.to_rfc3339());- js_obj.set(cx, "scheduled", js_scheduled)?;-- if let Some(parent_run_id) = &job.parent_run_id {- let js_parent_run_id = cx.string(parent_run_id);- js_obj.set(cx, "parentRunId", js_parent_run_id)?;- } else {- js_obj.set(cx, "parentRunId", null)?;- }-- if let Some(vm_state) = job.vm_state {- let vm_state = match std::str::from_utf8(&vm_state) {- Ok(v) => v,- Err(e) => panic!("Invalid UTF-8 sequence in vm_state: {e}"),- };- let js_vm_state = cx.string(vm_state);- js_obj.set(cx, "vmState", js_vm_state)?;- } else {- js_obj.set(cx, "vmState", null)?;- }-- if let Some(metadata) = job.metadata {- let metadata = match std::str::from_utf8(&metadata) {- Ok(v) => v,- Err(e) => panic!("Invalid UTF-8 sequence in metadata: {e}"),- };- let js_metadata = cx.string(metadata);- js_obj.set(cx, "metadata", js_metadata)?;- } else {- js_obj.set(cx, "metadata", null)?;- }-- if let Some(parameters) = job.parameters {- let parameters = match std::str::from_utf8(¶meters) {- Ok(v) => v,- Err(e) => panic!("Invalid UTF-8 sequence in parameters: {e}"),- };- let js_parameters = cx.string(parameters);- js_obj.set(cx, "parameters", js_parameters)?;- } else {- js_obj.set(cx, "parameters", null)?;- }-- if let Some(blob) = job.blob {- let mut js_blob = JsArrayBuffer::new(cx, blob.len())?;- let js_blob_slice = js_blob.as_mut_slice(cx);- js_blob_slice.copy_from_slice(&blob);- js_obj.set(cx, "blob", js_blob)?;- } else {- js_obj.set(cx, "blob", null)?;- }-- js_array.set(cx, i as u32, js_obj)?;- }-- Ok(js_array)-}--impl JsJob {- fn to_job_init(&self, blob: Option<Vec<u8>>) -> JobInit {- JobInit {- id: self.id,- team_id: self.team_id,- queue_name: self.queue_name.clone(),- priority: self.priority,- scheduled: self.scheduled,- function_id: self.function_id,- parent_run_id: self.parent_run_id.clone(),- vm_state: self.vm_state.as_ref().map(|s| s.as_bytes().to_vec()),- parameters: self.parameters.as_ref().map(|s| s.as_bytes().to_vec()),- metadata: self.metadata.as_ref().map(|s| s.as_bytes().to_vec()),- blob,- }- }-}--#[neon::main]-fn main(mut cx: ModuleContext) -> NeonResult<()> {- cx.export_function("hello", hello)?;- cx.export_function("initWorker", init_worker)?;- cx.export_function("initManager", init_manager)?;- cx.export_function("maybeInitWorker", maybe_init_worker)?;- cx.export_function("maybeInitManager", maybe_init_manager)?;- cx.export_function("createJob", create_job)?;- cx.export_function("bulkCreateJobs", bulk_create_jobs)?;- cx.export_function("dequeueJobs", dequeue_jobs)?;- cx.export_function("dequeueJobsWithVmState", dequeue_with_vm_state)?;- cx.export_function("releaseJob", release_job)?;- cx.export_function("forceFlush", force_flush)?;- cx.export_function("setState", set_state)?;- cx.export_function("setQueue", set_queue)?;- cx.export_function("setPriority", set_priority)?;- cx.export_function("setScheduledAt", set_scheduled_at)?;- cx.export_function("setVmState", set_vm_state)?;- cx.export_function("setMetadata", set_metadata)?;- cx.export_function("setParameters", set_parameters)?;- cx.export_function("setBlob", set_blob)?;-- Ok(())-}diff --git a/rust/cyclotron-node/src/manager.ts b/rust/cyclotron-node/src/manager.tsdeleted file mode 100644index cbd004bfa688..000000000000--- a/rust/cyclotron-node/src/manager.ts+++ /dev/null@@ -1,97 +0,0 @@-// eslint-disable-next-line @typescript-eslint/no-var-requires-const cyclotron = require('../index.node')--import { convertToInternalPoolConfig, serializeObject } from './helpers'-import { CyclotronJobInit, CyclotronPoolConfig, CyclotronInternalPoolConfig } from './types'--type CyclotronManagerInternalConfig = {- shards: CyclotronInternalPoolConfig[]- shardDepthLimit?: number- shardDepthCheckIntervalSeconds?: number- shouldCompressVmState?: boolean- shouldUseBulkJobCopy?: boolean-}--export type CyclotronManagerConfig = Omit<CyclotronManagerInternalConfig, 'shards'> & {- shards: CyclotronPoolConfig[]-}--export class CyclotronManager {- constructor(private config: CyclotronManagerConfig) {- this.config = config- }-- async connect(): Promise<void> {- const config: CyclotronManagerInternalConfig = {- shards: this.config.shards.map((shard) => convertToInternalPoolConfig(shard)),- shardDepthLimit: this.config.shardDepthLimit,- shardDepthCheckIntervalSeconds: this.config.shardDepthCheckIntervalSeconds,- shouldCompressVmState: this.config.shouldCompressVmState,- shouldUseBulkJobCopy: this.config.shouldUseBulkJobCopy,- }- return await cyclotron.maybeInitManager(JSON.stringify(config))- }-- async createJob(job: CyclotronJobInit): Promise<string> {- job.priority ??= 1- job.scheduled ??= new Date().toISOString()-- // TODO: Why is this type of job snake case whereas the dequeue return type is camel case?- const jobInitInternal = {- id: job.id,- team_id: job.teamId,- function_id: job.functionId,- queue_name: job.queueName,- priority: job.priority,- scheduled: job.scheduled,- vm_state: job.vmState ? serializeObject('vmState', job.vmState) : null,- parameters: job.parameters ? serializeObject('parameters', job.parameters) : null,- metadata: job.metadata ? serializeObject('metadata', job.metadata) : null,- }-- const json = JSON.stringify(jobInitInternal)- return await cyclotron.createJob(json, job.blob ? job.blob : undefined)- }-- async bulkCreateJobs(jobs: CyclotronJobInit[]): Promise<string[]> {- const jobInitsInternal = jobs.map((job) => {- job.priority ??= 1- job.scheduled ??= new Date().toISOString()-- return {- id: job.id,- team_id: job.teamId,- function_id: job.functionId,- queue_name: job.queueName,- priority: job.priority,- scheduled: job.scheduled,- vm_state: job.vmState ? serializeObject('vmState', job.vmState) : null,- parameters: job.parameters ? serializeObject('parameters', job.parameters) : null,- metadata: job.metadata ? serializeObject('metadata', job.metadata) : null,- }- })- const json = JSON.stringify(jobInitsInternal)-- const totalBytes = jobs.reduce((total, job) => total + (job.blob ? job.blob.byteLength : 0), 0)-- // The cyclotron API expects a single buffer with all the blobs concatenated, and an array of lengths.- // 0 lengths indicate that the job has no blob.- const blobs = new Uint8Array(totalBytes)- const blobLengths = new Uint32Array(jobs.length)-- let offset = 0- for (let i = 0; i < jobs.length; i++) {- const blob = jobs[i].blob- if (blob) {- blobLengths[i] = blob.byteLength- blobs.set(blob, offset)- offset += blob.byteLength- } else {- blobLengths[i] = 0- }- }-- return await cyclotron.bulkCreateJobs(json, blobs, blobLengths)- }-}-diff --git a/rust/cyclotron-node/src/types.ts b/rust/cyclotron-node/src/types.tsdeleted file mode 100644index b9b4cb36f0de..000000000000--- a/rust/cyclotron-node/src/types.ts+++ /dev/null@@ -1,50 +0,0 @@-export type CyclotronPoolConfig = {- dbUrl: string- maxConnections?: number- minConnections?: number- acquireTimeoutSeconds?: number- maxLifetimeSeconds?: number- idleTimeoutSeconds?: number-}--// Type as expected by Cyclotron.-export type CyclotronInternalPoolConfig = {- db_url: string- max_connections?: number- min_connections?: number- acquire_timeout_seconds?: number- max_lifetime_seconds?: number- idle_timeout_seconds?: number-}---export type CyclotronJobState = 'available' | 'running' | 'completed' | 'failed' | 'paused' | 'canceled'--export type CyclotronJob = {- id: string- teamId: number- functionId: string | null- created: Date- lockId: string | null- lastHeartbeat: Date | null- janitorTouchCount: number- transitionCount: number- lastTransition: Date- queueName: string- state: CyclotronJobState- priority: number- scheduled: string | null- parentRunId: string | null- vmState: object | null- metadata: object | null- parameters: object | null- blob: Uint8Array | null-}--export type CyclotronJobInit = Pick<CyclotronJob, 'teamId' | 'functionId' | 'queueName' | 'priority'> &- Pick<Partial<CyclotronJob>, 'id' | 'scheduled' | 'parentRunId' | 'vmState' | 'parameters' | 'metadata' | 'blob'>--export type CyclotronJobUpdate = Pick<- Partial<CyclotronJob>,- 'queueName' | 'priority' | 'parentRunId' | 'vmState' | 'parameters' | 'metadata' | 'blob' | 'scheduled'->diff --git a/rust/cyclotron-node/src/worker.ts b/rust/cyclotron-node/src/worker.tsdeleted file mode 100644index 19750ace5779..000000000000--- a/rust/cyclotron-node/src/worker.ts+++ /dev/null@@ -1,166 +0,0 @@-// eslint-disable-next-line @typescript-eslint/no-var-requires-const cyclotron = require('../index.node')-import { convertToInternalPoolConfig, deserializeObject, serializeObject } from './helpers'-import {- CyclotronJob,- CyclotronJobState,- CyclotronJobUpdate,- CyclotronPoolConfig,-} from './types'--const parseJob = (job: CyclotronJob): CyclotronJob => {- return {- ...job,- vmState: deserializeObject('vmState', job.vmState),- metadata: deserializeObject('metadata', job.metadata),- parameters: deserializeObject('parameters', job.parameters),- }-}--// Config specific to the node worker-type CyclotronWorkerNodeConfig = {- pool: CyclotronPoolConfig- /** The queue to be consumed from */- queueName: string- /** Max number of jobs to consume in a batch. Default: 100 */- batchMaxSize?: number- /** Whether the vmState will be included or not */- includeVmState?: boolean- /** Amount of delay between dequeue polls. Default: 50ms */- pollDelayMs?: number- /** Heartbeat timeout. After this time without response from the worker loop the worker will be considered unhealthy. Default 30000 */- heartbeatTimeoutMs?: number- /** Include empty batches - useful if you want to track them. Default: false */- includeEmptyBatches?: boolean-}---type CyclotronWorkerInternalConfig = {- /** Heartbeat timeout. After this time without response from the worker loop the worker will be considered unhealthy. Default 30000 */- heartbeatTimeoutMs?: number- /** Heartbeat window. Default 5 */- heartbeatWindowSeconds?: number- /** Linger time. Default 500 */- lingerTimeMs?: number- /** Max updates buffered. Default 100 */- maxUpdatesBuffered?: number- /** Max bytes buffered. Default 10MB */- maxBytesBuffered?: number- /** Flush loop interval. Default 10 */- flushLoopIntervalMs?: number- /** Whether to compress vmState. Default false */- shouldCompressVmState?: boolean-}---export type CyclotronWorkerConfig = CyclotronWorkerNodeConfig & CyclotronWorkerInternalConfig--export class CyclotronWorker {- isConsuming: boolean = false- lastHeartbeat: Date = new Date()-- private consumerLoopPromise: Promise<void> | null = null-- constructor(private config: CyclotronWorkerConfig) {}-- public isHealthy(): boolean {- return (- this.isConsuming &&- new Date().getTime() - this.lastHeartbeat.getTime() < (this.config.heartbeatTimeoutMs ?? 30000)- )- }-- async connect(processBatch: (jobs: CyclotronJob[]) => Promise<void>): Promise<void> {- if (this.isConsuming) {- throw new Error('Already consuming')- }-- const config: CyclotronWorkerInternalConfig = {- heartbeatWindowSeconds: this.config.heartbeatWindowSeconds ?? 5,- lingerTimeMs: this.config.lingerTimeMs ?? 500,- maxUpdatesBuffered: this.config.maxUpdatesBuffered ?? 100,- maxBytesBuffered: this.config.maxBytesBuffered ?? 10000000,- flushLoopIntervalMs: this.config.flushLoopIntervalMs ?? 10,- shouldCompressVmState: this.config.shouldCompressVmState ?? false,- }-- await cyclotron.maybeInitWorker(- JSON.stringify(convertToInternalPoolConfig(this.config.pool)),- JSON.stringify(config)- )-- this.isConsuming = true- this.consumerLoopPromise = this.startConsumerLoop(processBatch).finally(() => {- this.isConsuming = false- this.consumerLoopPromise = null- })- }-- private async startConsumerLoop(processBatch: (jobs: CyclotronJob[]) => Promise<void>): Promise<void> {- try {- this.isConsuming = true-- const batchMaxSize = this.config.batchMaxSize ?? 100- const pollDelayMs = this.config.pollDelayMs ?? 50-- while (this.isConsuming) {- this.lastHeartbeat = new Date()-- const jobs = (- this.config.includeVmState- ? await cyclotron.dequeueJobsWithVmState(this.config.queueName, batchMaxSize)- : await cyclotron.dequeueJobs(this.config.queueName, batchMaxSize)- ).map(parseJob)-- if (!jobs.length) {- // Wait a bit before polling again- await new Promise((resolve) => setTimeout(resolve, pollDelayMs))- if (this.config.includeEmptyBatches) {- await processBatch(jobs)- }- continue- }-- await processBatch(jobs)- }- } catch (e) {- // We only log here so as not to crash the parent process- console.error('[Cyclotron] Error in worker loop', e)- }- }-- async disconnect(): Promise<void> {- this.isConsuming = false- await (this.consumerLoopPromise ?? Promise.resolve())- }-- async releaseJob(jobId: string): Promise<void> {- // We hand the promise back to the user, letting them decide when to await it.- return cyclotron.releaseJob(jobId)- }-- updateJob(id: CyclotronJob['id'], state: CyclotronJobState, updates?: CyclotronJobUpdate): void {- cyclotron.setState(id, state)- if (updates?.queueName !== undefined) {- cyclotron.setQueue(id, updates.queueName)- }- if (updates?.priority !== undefined) {- cyclotron.setPriority(id, updates.priority)- }- if (updates?.parameters !== undefined) {- cyclotron.setParameters(id, serializeObject('parameters', updates.parameters))- }- if (updates?.metadata !== undefined) {- cyclotron.setMetadata(id, serializeObject('metadata', updates.metadata))- }- if (updates?.vmState !== undefined) {- cyclotron.setVmState(id, serializeObject('vmState', updates.vmState))- }- if (updates?.blob !== undefined) {- cyclotron.setBlob(id, updates.blob)- }- if (updates?.scheduled !== undefined) {- cyclotron.setScheduledAt(id, updates.scheduled)- }- }-}diff --git a/rust/cyclotron-node/tsconfig.json b/rust/cyclotron-node/tsconfig.jsondeleted file mode 100644index 9388b0c06d42..000000000000--- a/rust/cyclotron-node/tsconfig.json+++ /dev/null@@ -1,24 +0,0 @@-{- "compilerOptions": {- "module": "nodenext",- "target": "esnext",- "declaration": true,- "removeComments": true,- "emitDecoratorMetadata": true,- "experimentalDecorators": true,- "moduleResolution": "nodenext",- "esModuleInterop": true,- "allowJs": true,- "sourceMap": true,- "rootDir": "src/",- "outDir": "dist/",- "types": ["node"],- "resolveJsonModule": true,- "strict": true,- "noImplicitAny": true,- "useUnknownInCatchVariables": false,- "skipLibCheck": true,- },- "include": ["src"],- "exclude": ["node_modules", "dist", "bin"]-}diff --git a/rust/cyclotron-node/turbo.json b/rust/cyclotron-node/turbo.jsondeleted file mode 100644index e839edff2b19..000000000000--- a/rust/cyclotron-node/turbo.json+++ /dev/null@@ -1,36 +0,0 @@-{- "$schema": "https://turbo.build/schema.json",- "extends": ["//"],- "tasks": {- "build": {- "inputs": [- "src",- "Cargo.toml",- "$TURBO_ROOT$/rust/cyclotron-core/src/**",- "$TURBO_ROOT$/rust/cyclotron-core/.sqlx/**",- "$TURBO_ROOT$/rust/cyclotron-core/Cargo.toml",- "$TURBO_ROOT$/rust/common/compression/src/**",- "$TURBO_ROOT$/rust/common/compression/Cargo.toml",- "$TURBO_ROOT$/rust/common/metrics/src/**",- "$TURBO_ROOT$/rust/common/metrics/Cargo.toml",- "$TURBO_ROOT$/rust/Cargo.toml",- "$TURBO_ROOT$/rust/Cargo.lock"- ]- },- "test": {- "inputs": [- "src",- "Cargo.toml",- "$TURBO_ROOT$/rust/cyclotron-core/src/**",- "$TURBO_ROOT$/rust/cyclotron-core/.sqlx/**",- "$TURBO_ROOT$/rust/cyclotron-core/Cargo.toml",- "$TURBO_ROOT$/rust/common/compression/src/**",- "$TURBO_ROOT$/rust/common/compression/Cargo.toml",- "$TURBO_ROOT$/rust/common/metrics/src/**",- "$TURBO_ROOT$/rust/common/metrics/Cargo.toml",- "$TURBO_ROOT$/rust/Cargo.toml",- "$TURBO_ROOT$/rust/Cargo.lock"- ]- }- }-}